mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-17 08:20:12 +00:00
feat: deploy apps with a Settings drawer instead of the deploy drawer (#11944)
* feat: harmonize flow, script and app settings drawers Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor: name the on-behalf-of setting by the access it grants Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat: add a permissions tab and confirm who apps run on behalf of Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: sandbox draft-only app deploys and keep app settings out of exports Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: keep drafted run-as users and custom url removals Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat: confirm the run-as user on every deploy that uses one Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: let new raw apps take the folder default and follow synced settings Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: start AI-session raw apps without a run-as user Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor: stop drafting an app's access mode and custom url Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat: let a flow or script deploy turn off run on behalf of Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: apply who can open an app on change, as on main Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: mute the error handler from the editor menu and keep it on deploy Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: change only the access mode when it applies on click Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: read the mute flag from the deployed row at its own path Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: change an app's access mode under the deploy row lock Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: defer a mode change to deploy on an app run as another user Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: hold the access toggle while its change is in flight Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: bind the app policy down to the settings drawer Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: keep app draft labels in the mcp session tools Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * revert: leave the deploy panel's access toggle to the settings drawer PR Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: change only the access mode on click and let deploys keep the deployed one Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: keep the caller's draft on a mode-only app update Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: refuse a builder's mode-only change on an unsandboxed app Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * test: check the reason for the unsandboxed mode-only refusal Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: defer a builder's access-mode change on an unsandboxed app Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: state the stored access mode in the chat's raw app deploy note Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: lock the access mode when the server would refuse the change Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: address settings and run-as review findings Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: hold the run-as confirmation until the folder default has loaded Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: keep the run-as dialog cancelable while the folder default loads Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor: harmonize flow and script settings layout Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: name who can change a locked access mode without taking the app over Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: keep the priority input open while it is edited Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat: confirm run-as on flow and script deploy, mute from editor menu Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: keep settings rows open while edited and name the deploying user for non-admins Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: reread the deployed run-as user after a deploy that keeps the editor open Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: write a setting before its row opens and show its real state while edited Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: slide settings rows open to their full height Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: send the popover's deployment message when Deploy is clicked Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: remount a settings row's fields when its toggle turns it on Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: send the popover's deployment message from Deploy & Stay here Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: clear the deployment message after a successful deploy Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: keep app access mode display in sync with the stored mode and badge app settings tabs Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: clear the app Deploy popover's message after a successful deploy Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: read the deployed row before muting from the menu, title Deploy only when icon-only Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: give the app settings badges the chip label and row key Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: mark the app labels and access rows so their badges reach them Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat: show the app settings as three sections instead of tabs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: Ruben Fiszel <ruben@windmill.dev>
This commit is contained in:
co-authored by
Claude Opus 5.5
Ruben Fiszel
parent
68a2f09388
commit
792dd27771
@@ -426,6 +426,9 @@ async fn deploy_app(
|
||||
app.insert("preserve_on_behalf_of".into(), json!(true));
|
||||
}
|
||||
app.insert("policy".into(), Value::Object(policy));
|
||||
if let Some(labels) = non_null(draft.get("labels")) {
|
||||
app.insert("labels".into(), labels.clone());
|
||||
}
|
||||
if let Some(message) = message {
|
||||
app.insert("deployment_message".into(), json!(message));
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult
|
||||
// is_template, language, kind`, + `parent_hash` once forked from a deploy)
|
||||
// flow the `Flow` object (`path, summary, description, value, schema`, +
|
||||
// `version_id` when forked from a deploy)
|
||||
// raw_app `{summary, files, runnables, data, policy?, custom_path?,
|
||||
// raw_app `{summary, files, runnables, data, policy?, custom_path?, labels?,
|
||||
// parent_version?, draft_path?}` (`normalize_app_draft`)
|
||||
// trigger_schedule the schedule request body; `trigger_<kind>` that trigger's body
|
||||
// resource `{path, description, args, labels, wsSpecific, resource_type}`
|
||||
@@ -384,7 +384,13 @@ pub(super) fn normalize_app_draft(value: &Value) -> Value {
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({ "tables": [] })),
|
||||
);
|
||||
for key in ["policy", "custom_path", "parent_version", "draft_path"] {
|
||||
for key in [
|
||||
"policy",
|
||||
"custom_path",
|
||||
"labels",
|
||||
"parent_version",
|
||||
"draft_path",
|
||||
] {
|
||||
put(&mut out, key, value.get(key).cloned());
|
||||
}
|
||||
Value::Object(out)
|
||||
@@ -695,6 +701,7 @@ pub(super) fn app_source_to_draft_value(app: &Value, fallback: Option<&Value>) -
|
||||
out.insert("data".into(), data);
|
||||
put(&mut out, "policy", or_fallback("policy"));
|
||||
put(&mut out, "custom_path", or_fallback("custom_path"));
|
||||
put(&mut out, "labels", or_fallback("labels"));
|
||||
// The fork base: the head of a deployed app's versions, or what a draft already pinned.
|
||||
let head = app
|
||||
.get("versions")
|
||||
@@ -2027,6 +2034,17 @@ mod tests {
|
||||
assert!(draft_item("app", "u/a/s", &draft).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_app_draft_keeps_labels() {
|
||||
// Every session save goes through this whitelist: a field missing here is
|
||||
// stripped from a draft the editor wrote.
|
||||
let draft = json!({ "files": {}, "labels": ["a"] });
|
||||
assert_eq!(
|
||||
normalize_app_draft(&draft).get("labels"),
|
||||
Some(&json!(["a"]))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draft_item_carries_the_variable_expiry() {
|
||||
let draft = json!({ "path": "u/a/v", "variable": { "value": "", "is_secret": true, "description": "" }, "value_valid_until": "2027-01-15T00:00:00Z" });
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
/** Split a CLASSIC app draft into comparable parts. The editor mirrors
|
||||
* summary/draft_path INTO the bare grid it autosaves, while a deployed row
|
||||
* keeps them outside `value` — compared raw, metadata diffs as grid noise.
|
||||
* Also unwraps legacy wrapped drafts ({summary/policy/custom_path, value}). */
|
||||
* summary/draft_path and the app settings (policy, labels) INTO the bare grid
|
||||
* it autosaves, while a deployed row keeps them outside `value` — compared
|
||||
* raw, metadata diffs as grid noise. Also unwraps legacy wrapped drafts
|
||||
* ({summary/policy/custom_path, value}).
|
||||
*
|
||||
* `policy` and `labels` are undefined when the draft predates mirroring them,
|
||||
* so the caller falls back to the deployed row. */
|
||||
export function classicAppDraftParts(json: unknown): {
|
||||
value: unknown
|
||||
summary?: string
|
||||
draftPath?: string
|
||||
policy?: Record<string, unknown>
|
||||
labels?: string[]
|
||||
} {
|
||||
if (json === null || typeof json !== 'object' || Array.isArray(json)) {
|
||||
return { value: json }
|
||||
@@ -27,10 +33,12 @@ export function classicAppDraftParts(json: unknown): {
|
||||
draftPath: (obj.draft_path as string | undefined) ?? inner.draftPath
|
||||
}
|
||||
}
|
||||
const { parent_version: _pv, draft_path, summary, ...value } = obj
|
||||
const { parent_version: _pv, draft_path, summary, policy, labels, ...value } = obj
|
||||
return {
|
||||
value,
|
||||
summary: summary as string | undefined,
|
||||
draftPath: draft_path as string | undefined
|
||||
draftPath: draft_path as string | undefined,
|
||||
policy: policy as Record<string, unknown> | undefined,
|
||||
labels: labels as string[] | undefined
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { deployRawAppValue } from '$lib/rawAppDeploy'
|
||||
import { policyForUpdate } from './publishAccessMode'
|
||||
import DeploymentHistory from './DeploymentHistory.svelte'
|
||||
|
||||
interface Props {
|
||||
@@ -37,7 +38,8 @@
|
||||
workspace: $workspaceStore!,
|
||||
path: app.path,
|
||||
requestBody: {
|
||||
...app
|
||||
...app,
|
||||
policy: app.policy && policyForUpdate(app.policy)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
let {
|
||||
app,
|
||||
path,
|
||||
policy,
|
||||
policy = $bindable(),
|
||||
summary,
|
||||
labels,
|
||||
deployedBaseline = undefined,
|
||||
@@ -897,7 +897,7 @@
|
||||
{onOpenOthersDrafts}
|
||||
{onRestore}
|
||||
{onDeploy}
|
||||
{policy}
|
||||
bind:policy
|
||||
{fromHub}
|
||||
bind:this={appEditorHeader}
|
||||
{diffDrawer}
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
<script lang="ts">
|
||||
import { deployAsksOnBehalfOf } from '$lib/components/itemSettings/onBehalfOf'
|
||||
import {
|
||||
fetchDeployedAccessMode,
|
||||
fetchDeployedRunAs,
|
||||
setDeployedOnBehalfOf
|
||||
} from './appDeploy.svelte'
|
||||
import { useOperatingUser } from '$lib/components/operatingWorkspace.svelte'
|
||||
import DeployOnBehalfOfDialog from '$lib/components/itemSettings/DeployOnBehalfOfDialog.svelte'
|
||||
import { useFolderDefaultPermissionedAs } from '$lib/components/useFolderDefaultPermissionedAs.svelte'
|
||||
import { Drawer, DrawerContent } from '$lib/components/common'
|
||||
import Button from '$lib/components/common/button/Button.svelte'
|
||||
|
||||
@@ -21,7 +30,6 @@
|
||||
FormInput,
|
||||
History,
|
||||
Laptop2,
|
||||
Save,
|
||||
Smartphone,
|
||||
FileClock,
|
||||
Sun,
|
||||
@@ -30,7 +38,8 @@
|
||||
Undo,
|
||||
Redo,
|
||||
Zap,
|
||||
Globe
|
||||
Globe,
|
||||
Settings
|
||||
} from 'lucide-svelte'
|
||||
import { getContext, onDestroy, untrack, type Snippet } from 'svelte'
|
||||
import { orderedJsonStringify, type Value, replaceFalseWithUndefined } from '../../../utils'
|
||||
@@ -46,7 +55,6 @@
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import DeploymentHistory from './DeploymentHistory.svelte'
|
||||
import Awareness from '$lib/components/Awareness.svelte'
|
||||
import { secondaryMenuLeftStore, secondaryMenuRightStore } from './settingsPanel/secondaryMenu'
|
||||
import Dropdown from '$lib/components/DropdownV2.svelte'
|
||||
import AppReportsDrawer from './AppReportsDrawer.svelte'
|
||||
import DebugPanel from './contextPanel/DebugPanel.svelte'
|
||||
@@ -65,9 +73,12 @@
|
||||
import AppJobsDrawer from './AppJobsDrawer.svelte'
|
||||
import LazyModePanel from './contextPanel/LazyModePanel.svelte'
|
||||
import type { DiffDrawerI } from '$lib/components/diff_drawer'
|
||||
import AppEditorHeaderDeploy from './AppEditorHeaderDeploy.svelte'
|
||||
import { computeSecretUrl } from './appDeploy.svelte'
|
||||
import AppSettingsDrawer from './AppSettingsDrawer.svelte'
|
||||
import DeployButton from '$lib/components/DeployButton.svelte'
|
||||
import { updatePolicy } from './appPolicy'
|
||||
import { policyForUpdate, publishAccessMode } from './publishAccessMode'
|
||||
import { appDraftSettings } from './appDraftSettings'
|
||||
import { classicAppDraftParts } from '$lib/appDiffSides'
|
||||
import { editInForkAllowed, editInForkLabel, openEditInFork } from '$lib/utils/editInFork'
|
||||
import { isCloudHosted } from '$lib/cloud'
|
||||
|
||||
@@ -204,17 +215,25 @@
|
||||
})
|
||||
})
|
||||
|
||||
// Mirror the summary onto the autosaved App so a draft persists it (the
|
||||
// autosave stores the bare App value, which has no summary of its own — it
|
||||
// lives in the `app` table column, set only on deploy). Without this the
|
||||
// summary is lost when reopening a draft or deploying it from the Review &
|
||||
// Mirror the summary and the app settings onto the autosaved App so a draft
|
||||
// persists them (the autosave stores the bare App value, which has none of
|
||||
// its own — they live in `app` table columns, set only on deploy). Without
|
||||
// this they are lost when reopening a draft or deploying it from the Review &
|
||||
// Deploy page. Parallels `draft_path`.
|
||||
$effect(() => {
|
||||
const s = $summary
|
||||
const settings = appDraftSettings({
|
||||
policy: $state.snapshot(policy),
|
||||
labels: $state.snapshot(labels)
|
||||
})
|
||||
const a = $app
|
||||
if (!a) return
|
||||
untrack(() => {
|
||||
if (a.summary !== s) a.summary = s
|
||||
// Compared first: every write reaches the autosave.
|
||||
const same = (x: unknown, y: unknown) => orderedJsonStringify(x) === orderedJsonStringify(y)
|
||||
if (!same(a.policy, settings.policy)) a.policy = settings.policy
|
||||
if (!same(a.labels, settings.labels)) a.labels = settings.labels
|
||||
})
|
||||
})
|
||||
|
||||
@@ -251,13 +270,23 @@
|
||||
let pathError: string = $state('')
|
||||
let appExport: AppExportButton | undefined = $state()
|
||||
|
||||
let saveDrawerOpen = $state(false)
|
||||
let settingsOpen = $state(false)
|
||||
let settingsDrawer: AppSettingsDrawer | undefined = $state()
|
||||
let deployRefused = $state(false)
|
||||
let inputsDrawerOpen = $state(untrack(() => fromHub))
|
||||
let historyBrowserDrawerOpen = $state(false)
|
||||
let debugAppDrawerOpen = $state(false)
|
||||
let lazyDrawerOpen = $state(false)
|
||||
let deploymentMsg = $state('')
|
||||
let preserveOnBehalfOf = $state(false)
|
||||
const operatingUser = useOperatingUser()
|
||||
// Only the app's first deploy takes the folder's default user.
|
||||
const folderDefault = useFolderDefaultPermissionedAs(
|
||||
() => (newApp ? newEditedPath : undefined),
|
||||
() => $workspaceStore
|
||||
)
|
||||
let deployDialogOpen = $state(false)
|
||||
let deployButton: DeployButton | undefined = $state(undefined)
|
||||
let deployedRunAs: Awaited<ReturnType<typeof fetchDeployedRunAs>> = $state()
|
||||
|
||||
// Top-bar responsive collapse — container width, not viewport.
|
||||
let topbarWidth = $state(0)
|
||||
@@ -272,20 +301,29 @@
|
||||
// editor/preview switch join the menu compact already shows.
|
||||
const phoneTopbar = $derived(ownsPageHeader && pageHeader.actionFold >= 2)
|
||||
|
||||
function closeSaveDrawer() {
|
||||
saveDrawerOpen = false
|
||||
}
|
||||
|
||||
// `parent_version` is the draft's stale-check base. Deployed, it would put a version
|
||||
// id that changes on every deploy into git-synced files and version diffs.
|
||||
// The draft-only fields mirrored onto `$app` (fork base, staged path, summary and settings)
|
||||
// are columns of the app row or editor state. Deployed inside the value, they would land in
|
||||
// git-synced files and version diffs, `parent_version` changing on every deploy; exported,
|
||||
// they would hand out the publisher's email.
|
||||
function withoutDraftBase<T extends App | undefined>(a: T): T {
|
||||
if (!a) return a
|
||||
const { parent_version: _pv, ...rest } = a
|
||||
return rest as T
|
||||
return classicAppDraftParts(a).value as T
|
||||
}
|
||||
|
||||
async function setAccessMode(mode: NonNullable<Policy['execution_mode']>) {
|
||||
await publishAccessMode($workspaceStore!, $appPath, mode)
|
||||
if (savedApp) savedApp.policy = { ...savedApp.policy, execution_mode: mode }
|
||||
sendUserToast(
|
||||
mode == 'anonymous'
|
||||
? 'App require no login to be accessed'
|
||||
: 'App require login and read-access'
|
||||
)
|
||||
}
|
||||
|
||||
async function createApp(path: string) {
|
||||
policy = await updatePolicy($app, policy)
|
||||
// In place: the settings drawer and the draft mirror hold this object.
|
||||
Object.assign(policy, await updatePolicy($app, policy))
|
||||
setDeployedOnBehalfOf(policy, operatingUser.current, folderDefault.value)
|
||||
try {
|
||||
await AppService.createApp({
|
||||
workspace: $workspaceStore!,
|
||||
@@ -296,7 +334,9 @@
|
||||
policy,
|
||||
deployment_message: deploymentMsg,
|
||||
custom_path: customPath,
|
||||
preserve_on_behalf_of: preserveOnBehalfOf || undefined,
|
||||
// The user the deploy dialog confirmed, which the backend keeps only for a deployer
|
||||
// who may preserve one.
|
||||
preserve_on_behalf_of: true,
|
||||
labels
|
||||
}
|
||||
})
|
||||
@@ -311,8 +351,8 @@
|
||||
custom_path: customPath,
|
||||
labels: $state.snapshot(labels)
|
||||
}
|
||||
closeSaveDrawer()
|
||||
sendUserToast('App deployed successfully')
|
||||
deployButton?.clearMessage()
|
||||
// Remove the autosave at its canonical URL draft key, not the deploy
|
||||
// `path` (they differ for new apps), or the real draft row orphans.
|
||||
// stopSync-bracketed + flushed so AppEditor's mirror can't re-save.
|
||||
@@ -401,25 +441,29 @@
|
||||
}
|
||||
|
||||
async function updateApp(npath: string) {
|
||||
policy = await updatePolicy($app, policy)
|
||||
// In place: the settings drawer and the draft mirror hold this object.
|
||||
Object.assign(policy, await updatePolicy($app, policy))
|
||||
setDeployedOnBehalfOf(policy, operatingUser.current)
|
||||
const deployed = await AppService.updateApp({
|
||||
workspace: $workspaceStore!,
|
||||
path: $appPath!,
|
||||
requestBody: {
|
||||
value: withoutDraftBase($app!),
|
||||
summary: $summary,
|
||||
policy,
|
||||
policy: policyForUpdate(policy),
|
||||
path: npath,
|
||||
deployment_message: deploymentMsg,
|
||||
// custom_path requires admin so to accept update without it, we need to send as undefined when non-admin (when undefined, it will be ignored)
|
||||
// it also means that customPath needs to be set to '' instead of undefined to unset it (when admin)
|
||||
custom_path:
|
||||
$userStore?.is_admin || $userStore?.is_super_admin ? (customPath ?? '') : undefined,
|
||||
preserve_on_behalf_of: preserveOnBehalfOf || undefined,
|
||||
preserve_on_behalf_of: true,
|
||||
labels
|
||||
}
|
||||
})
|
||||
invalidateWorkspacePaths($workspaceStore!)
|
||||
const accessMode = await fetchDeployedAccessMode($workspaceStore!, npath)
|
||||
if (accessMode) policy.execution_mode = accessMode
|
||||
savedApp = {
|
||||
summary: $summary,
|
||||
value: structuredClone($state.snapshot($app)),
|
||||
@@ -449,8 +493,8 @@
|
||||
headAt: head?.created_at
|
||||
})
|
||||
|
||||
closeSaveDrawer()
|
||||
sendUserToast('App deployed successfully')
|
||||
deployButton?.clearMessage()
|
||||
// Canonical autosave key (the URL draft path), not `$appPath` — a
|
||||
// rename leaves the autosave at the original key, so removing at
|
||||
// `$appPath` would miss it. Bracketed + flushed (see createApp).
|
||||
@@ -466,28 +510,47 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function setPublishState(message?: string) {
|
||||
policy = await updatePolicy($app, policy)
|
||||
await AppService.updateApp({
|
||||
workspace: $workspaceStore!,
|
||||
path: $appPath,
|
||||
requestBody: { policy }
|
||||
})
|
||||
if (message) {
|
||||
sendUserToast(message)
|
||||
} else if (policy.execution_mode == 'anonymous') {
|
||||
sendUserToast('App require no login to be accessed')
|
||||
} else {
|
||||
sendUserToast('App require login and read-access')
|
||||
}
|
||||
function openSettings(setting?: string) {
|
||||
settingsDrawer?.openAt(setting)
|
||||
}
|
||||
|
||||
async function save() {
|
||||
$secondaryMenuLeftStore.isOpen = false
|
||||
$secondaryMenuRightStore.isOpen = false
|
||||
async function deploy(message?: string) {
|
||||
if (pathError != '' || customPathError != '') {
|
||||
deployRefused = true
|
||||
openSettings(pathError != '' ? undefined : 'custom-url')
|
||||
return
|
||||
}
|
||||
deploymentMsg = message ?? ''
|
||||
// Compares against the user deployed right now; a failed lookup asks rather than trusting
|
||||
// the loaded one.
|
||||
deployedRunAs = newApp ? undefined : await fetchDeployedRunAs($workspaceStore!, $appPath!)
|
||||
if (
|
||||
(!newApp && !deployedRunAs) ||
|
||||
// Asks while the folder default is loading: the backend would apply it unconfirmed.
|
||||
folderDefault.loading ||
|
||||
deployAsksOnBehalfOf('app', {
|
||||
user: operatingUser.current,
|
||||
email: policy.on_behalf_of_email,
|
||||
permissionedAs: policy.on_behalf_of,
|
||||
savedEmail: deployedRunAs?.on_behalf_of_email,
|
||||
savedPermissionedAs: deployedRunAs?.on_behalf_of,
|
||||
folderDefault: folderDefault.value
|
||||
})
|
||||
) {
|
||||
deployDialogOpen = true
|
||||
return
|
||||
}
|
||||
await deployNow()
|
||||
}
|
||||
|
||||
saveDrawerOpen = true
|
||||
return
|
||||
async function deployNow() {
|
||||
// Use `newApp` (set for /apps/add and draft-only paths), not
|
||||
// `$appPath` — its `draft_{uuid}` is a poor create signal.
|
||||
if (newApp) {
|
||||
await createApp(newEditedPath)
|
||||
} else {
|
||||
await handleUpdateApp(newEditedPath)
|
||||
}
|
||||
}
|
||||
|
||||
let onLatest = $state(true)
|
||||
@@ -699,19 +762,18 @@
|
||||
displayName: 'Export',
|
||||
icon: FileJson,
|
||||
action: () => {
|
||||
appExport?.open($app)
|
||||
appExport?.open(withoutDraftBase($app))
|
||||
}
|
||||
},
|
||||
{
|
||||
displayName: 'Settings',
|
||||
icon: Settings,
|
||||
action: () => openSettings()
|
||||
},
|
||||
{
|
||||
displayName: 'Public URL',
|
||||
icon: Globe,
|
||||
action: async () => {
|
||||
const secretUrl = await AppService.getPublicSecretOfApp({
|
||||
workspace: $workspaceStore!,
|
||||
path: $appPath
|
||||
})
|
||||
window.open(computeSecretUrl(secretUrl), '_blank')
|
||||
}
|
||||
action: () => openSettings('access')
|
||||
},
|
||||
{
|
||||
displayName: 'App inputs',
|
||||
@@ -761,7 +823,11 @@
|
||||
},
|
||||
aiReview: $workspaceStore
|
||||
? { workspaceId: $workspaceStore, kind: 'app', path: savedApp.path }
|
||||
: undefined
|
||||
: undefined,
|
||||
button: {
|
||||
text: 'Looks good, deploy',
|
||||
onClick: () => deploy(deploymentMsg)
|
||||
}
|
||||
},
|
||||
opening
|
||||
)
|
||||
@@ -787,7 +853,7 @@
|
||||
displayName: 'Hub export',
|
||||
icon: FileUp,
|
||||
action: () => {
|
||||
appExport?.open(toStatic($app, $staticExporter, $summary).app)
|
||||
appExport?.open(toStatic(withoutDraftBase($app), $staticExporter, $summary).app)
|
||||
}
|
||||
}
|
||||
]) as Item[]
|
||||
@@ -832,14 +898,28 @@
|
||||
}
|
||||
})
|
||||
|
||||
$effect(() => {
|
||||
saveDrawerOpen && untrack(() => compareVersions())
|
||||
})
|
||||
let settingsHaveErrors = $derived(pathError != '' || customPathError != '')
|
||||
let hasErrors = $derived(Object.keys($errorByComponent).length > 0)
|
||||
</script>
|
||||
|
||||
<svelte:window onkeydown={onKeyDown} />
|
||||
|
||||
<DeployOnBehalfOfDialog
|
||||
kind="app"
|
||||
bind:open={deployDialogOpen}
|
||||
bind:message={deploymentMsg}
|
||||
bind:email={policy.on_behalf_of_email}
|
||||
bind:permissionedAs={policy.on_behalf_of}
|
||||
savedEmail={newApp ? undefined : deployedRunAs?.on_behalf_of_email}
|
||||
savedPermissionedAs={newApp ? undefined : deployedRunAs?.on_behalf_of}
|
||||
isNew={newApp}
|
||||
folderDefault={folderDefault.value}
|
||||
folderDefaultLoading={folderDefault.loading}
|
||||
executionMode={policy.execution_mode}
|
||||
targetWorkspace={$workspaceStore ?? ''}
|
||||
onConfirmed={deployNow}
|
||||
/>
|
||||
|
||||
<DeployOverrideConfirmationModal
|
||||
{deployedBy}
|
||||
{confirmCallback}
|
||||
@@ -874,101 +954,23 @@
|
||||
jobsById={$jobsById}
|
||||
errorByComponent={$errorByComponent}
|
||||
/>
|
||||
<Drawer bind:open={saveDrawerOpen} size="800px">
|
||||
<DrawerContent title="Deploy" on:close={() => closeSaveDrawer()}>
|
||||
{#snippet actions()}
|
||||
<div class="flex flex-row gap-4">
|
||||
<Button
|
||||
variant="accent"
|
||||
disabled={!savedApp || newApp}
|
||||
on:click={async () => {
|
||||
if (!savedApp || newApp) {
|
||||
return
|
||||
}
|
||||
// The other entry point into the same drawer, so it takes an opening too.
|
||||
const opening = diffDrawer?.beginOpening()
|
||||
lastOpening = opening
|
||||
if (opening == null) return
|
||||
// deployedValue should be syncronized when we open Diff
|
||||
await syncWithDeployed(opening)
|
||||
|
||||
if (!diffDrawer?.ownsOpening(opening)) return
|
||||
saveDrawerOpen = false
|
||||
diffDrawer.openDrawer(opening)
|
||||
diffDrawer.setDiff(
|
||||
{
|
||||
mode: 'normal',
|
||||
deployed: deployedValue ?? savedApp,
|
||||
current: {
|
||||
summary: $summary,
|
||||
value: withoutDraftBase($app),
|
||||
path: newEditedPath || savedApp.path,
|
||||
policy,
|
||||
custom_path: customPath,
|
||||
labels
|
||||
},
|
||||
aiReview: $workspaceStore
|
||||
? { workspaceId: $workspaceStore, kind: 'app', path: savedApp.path }
|
||||
: undefined,
|
||||
button: {
|
||||
text: 'Looks good, deploy',
|
||||
onClick: () => {
|
||||
if (newApp) {
|
||||
createApp(newEditedPath)
|
||||
} else {
|
||||
handleUpdateApp(newEditedPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
opening
|
||||
)
|
||||
}}
|
||||
>
|
||||
<div class="flex flex-row gap-2 items-center">
|
||||
<DiffIcon size={14} />
|
||||
Diff
|
||||
</div>
|
||||
</Button>
|
||||
<Button
|
||||
variant="accent"
|
||||
startIcon={{ icon: Save }}
|
||||
disabled={pathError != '' || customPathError != ''}
|
||||
on:click={() => {
|
||||
// Use `newApp` (set for /apps/add and draft-only paths), not
|
||||
// `$appPath` — its `draft_{uuid}` is a poor create signal.
|
||||
if (newApp) {
|
||||
createApp(newEditedPath)
|
||||
} else {
|
||||
handleUpdateApp(newEditedPath)
|
||||
}
|
||||
}}
|
||||
>
|
||||
Deploy
|
||||
</Button>
|
||||
</div>
|
||||
{/snippet}
|
||||
<AppEditorHeaderDeploy
|
||||
{newPath}
|
||||
{newApp}
|
||||
{policy}
|
||||
{setPublishState}
|
||||
appPath={$appPath}
|
||||
{onLatest}
|
||||
{headUnknown}
|
||||
{savedApp}
|
||||
bind:summary={$summary}
|
||||
bind:customPath
|
||||
bind:deploymentMsg
|
||||
bind:customPathError
|
||||
bind:pathError
|
||||
bind:newEditedPath
|
||||
bind:preserveOnBehalfOf
|
||||
bind:labels
|
||||
hideSecretUrl={false}
|
||||
/>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
<AppSettingsDrawer
|
||||
bind:this={settingsDrawer}
|
||||
bind:open={settingsOpen}
|
||||
{newPath}
|
||||
{newApp}
|
||||
bind:policy
|
||||
appPath={$appPath}
|
||||
{savedApp}
|
||||
bind:summary={$summary}
|
||||
bind:customPath
|
||||
bind:customPathError
|
||||
bind:pathError
|
||||
bind:newEditedPath
|
||||
bind:labels
|
||||
showErrors={deployRefused}
|
||||
{setAccessMode}
|
||||
/>
|
||||
|
||||
<Drawer bind:open={inputsDrawerOpen} size="600px">
|
||||
<DrawerContent title="App inputs configuration" on:close={() => (inputsDrawerOpen = false)}>
|
||||
@@ -1318,14 +1320,31 @@
|
||||
seeing the app is most of what an app editor is good for on one. -->
|
||||
<AppExportButton bind:this={appExport} />
|
||||
<PreviewToggle loading={loading.save} iconOnly={phoneTopbar} />
|
||||
<Button
|
||||
variant="accent"
|
||||
loading={loading.save}
|
||||
startIcon={{ icon: Save }}
|
||||
on:click={save}
|
||||
{#if !phoneTopbar}
|
||||
<div class="relative shrink-0">
|
||||
{#if settingsHaveErrors}
|
||||
<span
|
||||
class="absolute inline-flex rounded-full bg-red-600 h-2 w-2 z-50 -right-0.5 -top-0.5"
|
||||
></span>
|
||||
{/if}
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="md"
|
||||
startIcon={{ icon: Settings }}
|
||||
iconOnly={compactTopbar}
|
||||
title="Settings"
|
||||
on:click={() => openSettings()}
|
||||
>
|
||||
Settings
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
<DeployButton
|
||||
bind:this={deployButton}
|
||||
loadingSave={loading.save}
|
||||
iconOnly={phoneTopbar}
|
||||
title="Deploy"
|
||||
unifiedSize={phoneTopbar ? 'sm' : 'md'}
|
||||
on:save={({ detail }) => deploy(detail)}
|
||||
dropdownItems={$appPath != ''
|
||||
? () => [
|
||||
{
|
||||
@@ -1346,8 +1365,6 @@
|
||||
: [])
|
||||
]
|
||||
: undefined}
|
||||
>
|
||||
Deploy
|
||||
</Button>
|
||||
/>
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
@@ -1,695 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { Alert, Section } from '$lib/components/common'
|
||||
import Toggle from '$lib/components/Toggle.svelte'
|
||||
import Badge from '$lib/components/Badge.svelte'
|
||||
import { enterpriseLicense, userStore } from '$lib/stores'
|
||||
import { useRoleCapabilities } from '$lib/operatorWriteRights'
|
||||
import { AlertTriangle, Loader2 } from 'lucide-svelte'
|
||||
|
||||
import Tooltip from '$lib/components/Tooltip.svelte'
|
||||
|
||||
import ClipboardPanel from '$lib/components/details/ClipboardPanel.svelte'
|
||||
import { untrack } from 'svelte'
|
||||
import { AppService, SettingService, WorkspaceService } from '$lib/gen'
|
||||
import type { GuestUsage } from '$lib/gen'
|
||||
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
|
||||
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
|
||||
import Path from '$lib/components/Path.svelte'
|
||||
import { computeSecretUrl } from './appDeploy.svelte'
|
||||
import { isCloudHosted } from '$lib/cloud'
|
||||
import EEOnly from '$lib/components/EEOnly.svelte'
|
||||
import TextInput from '$lib/components/text_input/TextInput.svelte'
|
||||
import LabelsInput from '$lib/components/LabelsInput.svelte'
|
||||
import OnBehalfOfSelector, {
|
||||
type OnBehalfOfChoice
|
||||
} from '$lib/components/OnBehalfOfSelector.svelte'
|
||||
import { canUserBypassRuleKind, protectionRulesState } from '$lib/workspaceProtectionRules.svelte'
|
||||
import { FRONTEND_SDK_SCOPES, sdkScopesToConfirm } from '$lib/components/raw_apps/sdkScopes'
|
||||
import { logFeatureUsage } from '$lib/utils/featureUsage'
|
||||
import {
|
||||
useOperatingUser,
|
||||
useOperatingWorkspace
|
||||
} from '$lib/components/operatingWorkspace.svelte'
|
||||
|
||||
const operatingWorkspaceStore = useOperatingWorkspace()
|
||||
const operatingUser = useOperatingUser()
|
||||
const actingUser = $derived(operatingUser.current)
|
||||
const roleCaps = useRoleCapabilities()
|
||||
// The server forces a composed app into sandbox isolation.
|
||||
const composeOnlyApps = $derived($roleCaps.apps === 'compose')
|
||||
|
||||
const WM_DEPLOYERS_GROUP = 'wm_deployers'
|
||||
|
||||
let {
|
||||
policy,
|
||||
setPublishState,
|
||||
appPath,
|
||||
customPath = $bindable(),
|
||||
onLatest,
|
||||
headUnknown = false,
|
||||
savedApp,
|
||||
summary = $bindable(),
|
||||
deploymentMsg = $bindable(),
|
||||
customPathError = $bindable(),
|
||||
pathError = $bindable(),
|
||||
newEditedPath = $bindable(),
|
||||
newPath,
|
||||
hideSecretUrl = false,
|
||||
preserveOnBehalfOf = $bindable(false),
|
||||
labels = $bindable(),
|
||||
rawApp = false,
|
||||
newApp = false,
|
||||
operatingWorkspace = undefined
|
||||
}: {
|
||||
policy: any
|
||||
setPublishState: (message?: string) => void
|
||||
appPath: string
|
||||
customPath: string | undefined
|
||||
onLatest: boolean
|
||||
/** The comparison behind `onLatest` could not read the deployed head, so the warning
|
||||
* is caution rather than an observed newer version. */
|
||||
headUnknown?: boolean
|
||||
savedApp: any
|
||||
summary: string
|
||||
deploymentMsg: string | undefined
|
||||
customPathError: string
|
||||
pathError: string
|
||||
newEditedPath: string
|
||||
newPath: string
|
||||
hideSecretUrl?: boolean
|
||||
preserveOnBehalfOf?: boolean
|
||||
labels?: string[] | undefined
|
||||
// Only raw apps are offered the `wm_coep` embedding hint: on a classic
|
||||
// (low-code) app COEP breaks no-CORP cross-origin subresources (external
|
||||
// images, {@html} embeds, CDN imports) that the app cannot opt out of.
|
||||
rawApp?: boolean
|
||||
/** True while the editor is on a draft-only URL (`/edit/u/{user}/draft_{uuid}`
|
||||
* with no deployed row yet). Suppresses the public-secret-URL fetch
|
||||
* (`/secret_of/...` 404s with no `app` row) and renders a placeholder
|
||||
* instead of the eternally-spinning link. */
|
||||
newApp?: boolean
|
||||
/** Workspace the app is deployed to. The secret-URL / custom-path / folder /
|
||||
* on-behalf-of lookups target it; defaults to the operating workspace. */
|
||||
operatingWorkspace?: string
|
||||
} = $props()
|
||||
|
||||
const opWs = $derived(operatingWorkspace ?? $operatingWorkspaceStore)
|
||||
|
||||
let isDeployer = $derived(actingUser?.groups?.includes(WM_DEPLOYERS_GROUP) ?? false)
|
||||
// Admins always pass the backend check. For everyone else, fail closed
|
||||
// while the workspace protection rules are still loading so the toggle
|
||||
// is never briefly enabled for a user the rules will end up restricting.
|
||||
let rulesetsLoaded = $derived(protectionRulesState.rulesets !== undefined)
|
||||
let canSetAnonymous = $derived(
|
||||
!!actingUser?.is_admin ||
|
||||
!!actingUser?.is_super_admin ||
|
||||
(rulesetsLoaded &&
|
||||
canUserBypassRuleKind('RestrictAnonymousAppDeployment', $userStore ?? undefined))
|
||||
)
|
||||
let canSetGuest = $derived(
|
||||
!!actingUser?.is_admin ||
|
||||
!!actingUser?.is_super_admin ||
|
||||
(rulesetsLoaded &&
|
||||
canUserBypassRuleKind('RestrictGuestAppDeployment', $userStore ?? undefined))
|
||||
)
|
||||
// The three rungs of the access control, widest last. `viewer` is a fourth
|
||||
// execution mode that this control never sets (it runs components as the viewer,
|
||||
// which a guest cannot be), so an app in it shows as members-only here.
|
||||
let accessMode = $derived(
|
||||
policy.execution_mode == 'anonymous'
|
||||
? 'anonymous'
|
||||
: policy.execution_mode == 'guest'
|
||||
? 'guest'
|
||||
: 'publisher'
|
||||
)
|
||||
let guestUsage: GuestUsage | undefined = $state(undefined)
|
||||
// Whether the deployment can have guests at all; off, the mode is not on offer. The
|
||||
// backend decides; the hostname stands in until it has answered, the shared cloud
|
||||
// being the only deployment where guests are unavailable.
|
||||
let guestsAvailable = $derived.by(() => guestUsage?.available ?? !isCloudHosted())
|
||||
|
||||
$effect(() => {
|
||||
const ws = opWs
|
||||
if (ws === undefined) return
|
||||
untrack(() => {
|
||||
WorkspaceService.getGuestUsage({ workspace: ws })
|
||||
.then((u) => (guestUsage = u))
|
||||
.catch(() => (guestUsage = undefined))
|
||||
})
|
||||
})
|
||||
|
||||
function onAccessModeChange(mode: string | undefined) {
|
||||
if (mode === undefined || mode === accessMode) return
|
||||
policy.execution_mode = mode
|
||||
// Same as sandbox: a not-yet-deployed app has no row to PATCH, so
|
||||
// `setPublishState` would 404. The mode is carried by the first deploy's
|
||||
// policy; persist incrementally only once the app exists.
|
||||
if (savedApp && !newApp) {
|
||||
setPublishState()
|
||||
}
|
||||
}
|
||||
let canPreserve = $derived(!!actingUser?.is_admin || !!actingUser?.is_super_admin || isDeployer)
|
||||
let savedOnBehalfOfEmail = $derived(savedApp?.policy?.on_behalf_of_email)
|
||||
let savedOnBehalfOf = $derived(savedApp?.policy?.on_behalf_of)
|
||||
let onBehalfOfChoice: OnBehalfOfChoice = $state(undefined)
|
||||
let customOnBehalfOfEmail: string = $state('')
|
||||
let myOnBehalfOf = $derived(actingUser?.username ? `u/${actingUser.username}` : undefined)
|
||||
// Without the right to preserve, the backend runs the redeployed app as the deployer whatever
|
||||
// the policy says, as it does for "me".
|
||||
let deployOnBehalfOf = $derived.by(() => {
|
||||
if (!canPreserve || onBehalfOfChoice === 'me') return myOnBehalfOf
|
||||
if (onBehalfOfChoice === 'custom') return policy.on_behalf_of
|
||||
return savedOnBehalfOf
|
||||
})
|
||||
let onBehalfOfWillChange = $derived(
|
||||
!newApp && !!savedOnBehalfOf && !!deployOnBehalfOf && deployOnBehalfOf !== savedOnBehalfOf
|
||||
)
|
||||
let dirtyCustomPath = $state(false)
|
||||
let path: Path | undefined = $state(undefined)
|
||||
|
||||
let dirtyPath = $state(false)
|
||||
|
||||
async function appExists(customPath: string) {
|
||||
return await AppService.customPathExists({
|
||||
workspace: opWs!,
|
||||
customPath
|
||||
})
|
||||
}
|
||||
|
||||
let globalWorkspacedRoute = $state(false)
|
||||
|
||||
async function loadGlobalWorkspacedRouteSetting() {
|
||||
try {
|
||||
const setting = await SettingService.getGlobal({ key: 'app_workspaced_route' })
|
||||
globalWorkspacedRoute = (setting as boolean) ?? false
|
||||
} catch (error) {
|
||||
globalWorkspacedRoute = false
|
||||
}
|
||||
}
|
||||
|
||||
loadGlobalWorkspacedRouteSetting()
|
||||
|
||||
let secretUrl: string | undefined = $state(undefined)
|
||||
let secretUrlHref = $derived(secretUrl ? computeSecretUrl(secretUrl) : undefined)
|
||||
let fullCustomUrl = $derived(
|
||||
`${window.location.origin}/a/${
|
||||
isCloudHosted() || globalWorkspacedRoute ? opWs + '/' : ''
|
||||
}${customPath}`
|
||||
)
|
||||
|
||||
// The app URL a guest JWT rides on: append `guest.<jwt>` and the viewer authenticates the
|
||||
// token as a seatless guest. Uses the custom URL when set, else the public secret URL.
|
||||
let guestJwtBase = $derived(customPath !== undefined ? fullCustomUrl : secretUrlHref)
|
||||
|
||||
let embedMode = $state(false)
|
||||
function toEmbedSnippet(url: string): string {
|
||||
return `<iframe src="${url}" title="Windmill app" width="100%" height="600"></iframe>`
|
||||
}
|
||||
async function getSecretUrl() {
|
||||
secretUrl = await AppService.getPublicSecretOfApp({
|
||||
workspace: opWs!,
|
||||
path: appPath
|
||||
})
|
||||
}
|
||||
|
||||
let validateTimeout: number | undefined = undefined
|
||||
async function validateCustomPath(customPath: string): Promise<void> {
|
||||
customPathError = ''
|
||||
if (validateTimeout) {
|
||||
clearTimeout(validateTimeout)
|
||||
}
|
||||
validateTimeout = setTimeout(async () => {
|
||||
if (!/^[\w-]+(\/[\w-]+)*$/.test(customPath)) {
|
||||
customPathError = 'Invalid path'
|
||||
} else if (customPath !== savedApp?.custom_path && (await appExists(customPath))) {
|
||||
customPathError = 'Path already taken'
|
||||
} else {
|
||||
customPathError = ''
|
||||
}
|
||||
validateTimeout = undefined
|
||||
}, 500)
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
;[customPath]
|
||||
untrack(() => customPath !== undefined && validateCustomPath(customPath))
|
||||
})
|
||||
|
||||
$effect(() => {
|
||||
// Skip the secret URL fetch on draft-only items — `/secret_of/...`
|
||||
// has no `app` row to look up and would 404, leaving the UI
|
||||
// component spinning indefinitely.
|
||||
!newApp &&
|
||||
appPath &&
|
||||
appPath != '' &&
|
||||
savedApp &&
|
||||
secretUrl == undefined &&
|
||||
untrack(() => getSecretUrl())
|
||||
})
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-8">
|
||||
{#if !onLatest}
|
||||
<Alert
|
||||
title={headUnknown
|
||||
? 'Could not check the deployed version. '
|
||||
: "You're not on the latest app version. "}
|
||||
type="warning"
|
||||
>
|
||||
{headUnknown
|
||||
? "Deploying may overwrite changes made by other users. Press 'Deploy' to see diff."
|
||||
: "By deploying, you may overwrite changes made by other users. Press 'Deploy' to see diff."}
|
||||
</Alert>
|
||||
{/if}
|
||||
|
||||
<div class="flex flex-col gap-6">
|
||||
<div class="flex flex-col gap-1">
|
||||
<label for="summary" class="text-emphasis text-xs font-semibold">Summary</label>
|
||||
<!-- svelte-ignore a11y_autofocus -->
|
||||
<TextInput
|
||||
inputProps={{
|
||||
id: 'summary',
|
||||
autofocus: true,
|
||||
placeholder: 'App summary',
|
||||
onkeydown: (e) => {
|
||||
e.stopPropagation()
|
||||
},
|
||||
onkeyup: () => {
|
||||
if (appPath == '' && summary?.length > 0 && !dirtyPath) {
|
||||
path?.setName(
|
||||
summary
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9_]/g, '_')
|
||||
.replace(/-+/g, '_')
|
||||
.replace(/^-|-$/g, '')
|
||||
)
|
||||
}
|
||||
}
|
||||
}}
|
||||
bind:value={summary}
|
||||
/>
|
||||
<LabelsInput bind:labels />
|
||||
</div>
|
||||
<div class="flex flex-col gap-1">
|
||||
<label for="deploymentMsg" class="text-emphasis text-xs font-semibold">
|
||||
Deployment message
|
||||
</label>
|
||||
<TextInput
|
||||
inputProps={{
|
||||
id: 'deploymentMsg',
|
||||
placeholder: 'Optional deployment message'
|
||||
}}
|
||||
bind:value={deploymentMsg}
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1">
|
||||
<label for="path" class="text-emphasis text-xs font-semibold">Path</label>
|
||||
<Path
|
||||
bind:this={path}
|
||||
bind:dirty={dirtyPath}
|
||||
bind:error={pathError}
|
||||
bind:path={newEditedPath}
|
||||
initialPath={newPath}
|
||||
namePlaceholder="app"
|
||||
kind="app"
|
||||
autofocus={false}
|
||||
workspaceOverride={operatingWorkspace}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Section
|
||||
label="Run on behalf of"
|
||||
tooltip={`The app's runnables run as this user whoever opens the app, so viewers need no access of their own. To keep that safe, the app can call only the runnables it was deployed with, and viewers cannot override their static inputs. Runnables still get the viewer's email in WM_END_USER_EMAIL${rawApp ? ', and inline ones can be set to read data tables and object storage as the viewer' : ''}.`}
|
||||
>
|
||||
<div class="flex flex-col items-start gap-1">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<OnBehalfOfSelector
|
||||
targetWorkspace={opWs ?? ''}
|
||||
targetValue={savedOnBehalfOfEmail}
|
||||
selected={onBehalfOfChoice}
|
||||
onSelect={(choice, details) => {
|
||||
onBehalfOfChoice = choice
|
||||
if (choice === 'me') {
|
||||
policy.on_behalf_of_email = $userStore?.email
|
||||
policy.on_behalf_of = `u/${$userStore?.username}`
|
||||
customOnBehalfOfEmail = ''
|
||||
preserveOnBehalfOf = false
|
||||
} else if (choice === 'target') {
|
||||
policy.on_behalf_of_email = savedOnBehalfOfEmail
|
||||
policy.on_behalf_of = savedOnBehalfOf
|
||||
customOnBehalfOfEmail = ''
|
||||
preserveOnBehalfOf = true
|
||||
} else if (choice === 'custom' && details) {
|
||||
policy.on_behalf_of_email = details.email
|
||||
policy.on_behalf_of = details.permissionedAs
|
||||
customOnBehalfOfEmail = details.email
|
||||
preserveOnBehalfOf = true
|
||||
}
|
||||
}}
|
||||
kind="app"
|
||||
{canPreserve}
|
||||
customValue={customOnBehalfOfEmail}
|
||||
isDeployment={false}
|
||||
myPermissionedAs={myOnBehalfOf}
|
||||
readOnlyWithoutPreserve
|
||||
/>
|
||||
{#if onBehalfOfWillChange}
|
||||
<AlertTriangle class="w-3.5 h-3.5 text-yellow-500" />
|
||||
<span class="text-2xs text-yellow-600 dark:text-yellow-400"
|
||||
>will change from <strong>{savedOnBehalfOf}</strong> on deploy</span
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="text-2xs text-secondary">
|
||||
{#if canPreserve}
|
||||
Viewers run the app's runnables as this user.
|
||||
{:else}
|
||||
Only workspace admins and members of {WM_DEPLOYERS_GROUP} can pick another user.
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section label="Sandbox isolation">
|
||||
<Toggle
|
||||
options={{
|
||||
right: "Isolate the app from the viewer's browser session",
|
||||
rightTooltip:
|
||||
"Controls what the app's browser-side code can reach in each viewer's browser, separately from who its runnables run as. A sandboxed app gets a narrowly scoped token on every surface, public URL and in-workspace. On by default for new apps. Turn it off only if the app needs IndexedDB, third-party sign-in or OAuth redirects."
|
||||
}}
|
||||
checked={composeOnlyApps || policy.sandbox == true}
|
||||
on:change={(e) => {
|
||||
policy.sandbox = e.detail || undefined
|
||||
// Counted where the toggle is flipped rather than where the policy is
|
||||
// persisted: a not-yet-deployed app only mutates it locally, and skipping
|
||||
// those would read as unused in the case where it is picked up front.
|
||||
logFeatureUsage('app_sandbox', 'toggled', {
|
||||
key: `${rawApp ? 'raw' : 'low_code'}:${e.detail ? 'on' : 'off'}`
|
||||
})
|
||||
// Frontend API access exists only for a sandboxed app, so turning
|
||||
// isolation off drops the declared scopes with it rather than leaving
|
||||
// them set but inert.
|
||||
if (!e.detail) {
|
||||
policy.frontend_sdk_scopes = undefined
|
||||
}
|
||||
// A not-yet-deployed app has no row to PATCH — `setPublishState` (POST
|
||||
// /apps/update) would 404. The flag rides along in the `policy` the first
|
||||
// deploy sends (createApp), so here we only mutate it locally. Persist
|
||||
// incrementally once the app exists.
|
||||
if (savedApp && !newApp) {
|
||||
setPublishState(e.detail ? 'Sandbox isolation enabled' : 'Sandbox isolation disabled')
|
||||
}
|
||||
}}
|
||||
disabled={!savedApp || composeOnlyApps}
|
||||
/>
|
||||
{#if composeOnlyApps || newApp}
|
||||
<div class="text-2xs text-secondary mt-1">
|
||||
{#if composeOnlyApps}
|
||||
Required for apps composed by your role, and cannot be turned off.
|
||||
{/if}
|
||||
{#if newApp}
|
||||
Takes effect when you first deploy this app.
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{#if !composeOnlyApps && policy.sandbox != true}
|
||||
<div class="mt-3">
|
||||
<Alert type="warning" title="Not isolated" size="xs">
|
||||
The app's frontend code runs with each viewer's full Windmill permissions. A future
|
||||
version will ask viewers to approve this. Keep isolation off only if the app needs it.
|
||||
</Alert>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if rawApp && policy.sandbox == true}
|
||||
<div class="mt-6">
|
||||
<Section
|
||||
label="Frontend API access"
|
||||
small
|
||||
collapsable
|
||||
tooltip="Each viewer approves these scopes before the app runs. The app's code, or an XSS bug in it, can use them as that viewer."
|
||||
>
|
||||
{#snippet badge()}
|
||||
{#if sdkScopesToConfirm(policy.frontend_sdk_scopes ?? []).length}
|
||||
<div class="flex grow min-w-0 flex-wrap gap-1 ps-2">
|
||||
{#each FRONTEND_SDK_SCOPES.filter( (s) => policy.frontend_sdk_scopes.includes(s.value) ) as scope (scope.value)}
|
||||
<Badge twBgColor="bg-surface-sunken" twTextColor="text-primary"
|
||||
>{scope.label}</Badge
|
||||
>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
{/snippet}
|
||||
<div class="text-xs text-secondary mb-3">
|
||||
Let the app's frontend call the Windmill API as <b>the viewer</b> through the
|
||||
<code>windmill-client</code> SDK, which it lists as a dependency. Grant only what the app
|
||||
needs.
|
||||
</div>
|
||||
<div class="flex flex-col gap-2">
|
||||
{#each FRONTEND_SDK_SCOPES as scope (scope.value)}
|
||||
<div>
|
||||
<Toggle
|
||||
size="xs"
|
||||
options={{ right: scope.label }}
|
||||
checked={policy.frontend_sdk_scopes?.includes(scope.value) ?? false}
|
||||
on:change={(e) => {
|
||||
const current: string[] = policy.frontend_sdk_scopes ?? []
|
||||
const next = e.detail
|
||||
? [...current, scope.value]
|
||||
: current.filter((s) => s !== scope.value)
|
||||
// Keep the curated order so the consent banner and the stored
|
||||
// consent compare stably across deploys. A leftover implicit scope is
|
||||
// not in the list, so it drops here rather than keep minting a token
|
||||
// for an app whose toggles all read off.
|
||||
const ordered = FRONTEND_SDK_SCOPES.map((s) => s.value).filter((s) =>
|
||||
next.includes(s)
|
||||
)
|
||||
policy.frontend_sdk_scopes = ordered.length > 0 ? ordered : undefined
|
||||
// Same as sandbox: a not-yet-deployed app has no row to PATCH, so the
|
||||
// scopes ride along in the first deploy's policy instead.
|
||||
if (savedApp && !newApp) {
|
||||
setPublishState('Frontend API access updated')
|
||||
}
|
||||
}}
|
||||
disabled={!savedApp}
|
||||
/>
|
||||
<div class="text-2xs text-hint ml-9">{scope.description}</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{#if sdkScopesToConfirm(policy.frontend_sdk_scopes ?? []).length}
|
||||
<div class="mt-3">
|
||||
<Alert type="info" title="Redeploy to use the SDK from a sandboxed app" size="xs">
|
||||
A sandboxed app calls the API cross-origin, which older <code>windmill-client</code>
|
||||
versions cannot do. An app bundled before this Windmill version fails with a CORS error
|
||||
until you deploy it again, which re-bundles it against a current client.
|
||||
</Alert>
|
||||
</div>
|
||||
{/if}
|
||||
</Section>
|
||||
</div>
|
||||
{/if}
|
||||
</Section>
|
||||
|
||||
{#if !hideSecretUrl}
|
||||
<Section label="Access">
|
||||
<div class="flex flex-col gap-2">
|
||||
{#if rulesetsLoaded && !canSetAnonymous && policy.execution_mode != 'anonymous'}
|
||||
<Alert type="warning" title="Restricted by a workspace protection rule" size="xs">
|
||||
Opening this app to anyone with the link is restricted to workspace admins and bypass
|
||||
users by a workspace protection rule
|
||||
</Alert>
|
||||
{/if}
|
||||
{#if rulesetsLoaded && !canSetGuest && policy.execution_mode != 'guest' && guestsAvailable}
|
||||
<Alert type="warning" title="Restricted by a workspace protection rule" size="xs">
|
||||
Opening this app to guests is restricted to workspace admins and bypass users by a
|
||||
workspace protection rule
|
||||
</Alert>
|
||||
{/if}
|
||||
<div>
|
||||
<ToggleButtonGroup
|
||||
selected={accessMode}
|
||||
on:selected={(e) => onAccessModeChange(e.detail)}
|
||||
disabled={!savedApp}
|
||||
>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton
|
||||
label="Members"
|
||||
value="publisher"
|
||||
tooltip="Workspace members with read access on this app."
|
||||
{item}
|
||||
/>
|
||||
<ToggleButton
|
||||
label="Guests"
|
||||
value="guest"
|
||||
disabled={policy.execution_mode != 'guest' && (!guestsAvailable || !canSetGuest)}
|
||||
tooltip={!guestsAvailable
|
||||
? 'Not available on Windmill Cloud. Guests require a self-hosted instance or a dedicated Windmill Cloud deployment.'
|
||||
: "Anyone your identity provider authenticates who has no Windmill account, plus workspace members. No membership, no seat up to the instance's allowance."}
|
||||
{item}
|
||||
/>
|
||||
<ToggleButton
|
||||
label="Public"
|
||||
value="anonymous"
|
||||
disabled={!canSetAnonymous && policy.execution_mode != 'anonymous'}
|
||||
tooltip="Anyone with the secret URL. No login."
|
||||
{item}
|
||||
/>
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
</div>
|
||||
<div class="text-xs text-secondary">
|
||||
{#if policy.execution_mode == 'anonymous'}
|
||||
Anyone holding the secret URL below can open this app without signing in.
|
||||
{:else if policy.execution_mode == 'guest'}
|
||||
{#if !guestsAvailable}
|
||||
Guests are not available on Windmill Cloud, so this app still admits members only.
|
||||
They require a self-hosted instance or a dedicated Windmill Cloud deployment.
|
||||
{:else}
|
||||
Anyone your identity provider authenticates can open this app without a Windmill
|
||||
account. They join no workspace. Members of this workspace can open it too.
|
||||
{#if guestUsage}
|
||||
{guestUsage.guest_count} of {guestUsage.free_allowance} free guests used across this
|
||||
instance in the last {guestUsage.window_days} days; beyond that, {guestUsage.metered
|
||||
? 'every four guests count as one seat'
|
||||
: 'new guests are refused until the count drops'}.
|
||||
{/if}
|
||||
{/if}
|
||||
{:else}
|
||||
Only workspace members with read access on this app can open it.
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-1 mt-6">
|
||||
{#if !savedApp || newApp}
|
||||
<ClipboardPanel content={`Deploy this app once to get the public secret URL`} size="md" />
|
||||
{:else if secretUrlHref}
|
||||
<div class="flex justify-end">
|
||||
<Toggle
|
||||
size="xs"
|
||||
checked={embedMode}
|
||||
on:change={(e) => (embedMode = e.detail)}
|
||||
options={{ left: 'URL', right: 'Embed' }}
|
||||
/>
|
||||
</div>
|
||||
<ClipboardPanel
|
||||
content={embedMode ? toEmbedSnippet(secretUrlHref) : secretUrlHref}
|
||||
size="md"
|
||||
/>
|
||||
{:else}<Loader2 class="animate-spin" />
|
||||
{/if}
|
||||
<div class="text-2xs text-secondary">
|
||||
{#if embedMode}
|
||||
Paste this iframe snippet into another app.
|
||||
{#if rawApp}
|
||||
To embed it in a cross-origin isolated page, add <code>wm_coep=on</code>
|
||||
<Tooltip
|
||||
>Sets the cross-origin isolation headers (COEP) on the app, which such a page
|
||||
requires of its iframes. The app then only loads cross-origin resources that send
|
||||
CORS or a Cross-Origin-Resource-Policy header.</Tooltip
|
||||
> to the URL.
|
||||
{/if}
|
||||
(if requiring login, top-level domain of embedding app must be the same as the one of Windmill)
|
||||
{:else}
|
||||
Share this URL directly, or switch to <b>Embed</b> to get an iframe snippet. Only the latest
|
||||
deployed version is served.
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if embedMode && policy.execution_mode == 'guest' && guestJwtBase && guestsAvailable}
|
||||
<div class="mt-6 flex flex-col gap-2">
|
||||
<div class="text-xs font-semibold text-emphasis">
|
||||
Embed for your own authenticated users (guest JWT)
|
||||
</div>
|
||||
<div class="text-xs text-secondary">
|
||||
To open this app for a user your own product already authenticates, mint a short-lived
|
||||
JWT in your backend and append it to the app URL as <code>guest.<jwt></code>. Each
|
||||
token is its own seatless guest, confined to this app. Unlike the plain secret URL
|
||||
above, there is no shared secret and no Windmill account.
|
||||
</div>
|
||||
<div class="text-xs text-secondary">
|
||||
Windmill verifies the token against the workspace's guest JWT key (Workspace settings →
|
||||
Guests): a PEM public key or a JWKS URL{#if !isCloudHosted()}, or the instance's
|
||||
configured issuer (<code>JWT_EXT_JWKS_URL</code>) when no workspace key is set{/if}.
|
||||
Set the <b>public</b> half there; in your backend, sign each token with the matching
|
||||
<b>private</b> key using RS256/384/512, PS256/384/512 or ES256/384 (symmetric HS* is
|
||||
refused), carrying <code>email</code>, <code>workspace_id</code> = <code>{opWs}</code>,
|
||||
<code>app_path</code> = <code>{appPath}</code> and <code>exp</code> (at most 24h ahead).
|
||||
</div>
|
||||
<ClipboardPanel
|
||||
content={toEmbedSnippet(`${guestJwtBase}/guest.YOUR_GUEST_JWT`)}
|
||||
size="md"
|
||||
/>
|
||||
<div class="text-2xs text-secondary">
|
||||
Replace <code>YOUR_GUEST_JWT</code> with the token your backend signs per user. Past the
|
||||
instance's free guest allowance a new guest email is refused (see the count above); guests
|
||||
already seen in the window keep working.
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="flex flex-col gap-2 mt-6">
|
||||
{#if !(actingUser?.is_admin || actingUser?.is_super_admin)}
|
||||
<Alert type="warning" title="Admin only" size="xs">
|
||||
Custom path can only be set by workspace admins
|
||||
</Alert>
|
||||
{/if}
|
||||
<div class="flex items-center gap-2">
|
||||
<Toggle
|
||||
on:change={({ detail }) => {
|
||||
customPath = detail ? '' : undefined
|
||||
if (customPath === undefined) {
|
||||
customPathError = ''
|
||||
}
|
||||
}}
|
||||
checked={customPath !== undefined}
|
||||
options={{
|
||||
right: 'Use a custom URL'
|
||||
}}
|
||||
disabled={!$enterpriseLicense || !(actingUser?.is_admin || actingUser?.is_super_admin)}
|
||||
/>
|
||||
{#if !$enterpriseLicense}
|
||||
<EEOnly />
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if customPath !== undefined}
|
||||
<div class="flex flex-col gap-1">
|
||||
<label for="customPath" class="text-emphasis text-xs font-semibold">Custom path</label>
|
||||
<TextInput
|
||||
inputProps={{
|
||||
id: 'customPath',
|
||||
autocomplete: 'off',
|
||||
disabled: !(actingUser?.is_admin || actingUser?.is_super_admin),
|
||||
oninput: () => {
|
||||
dirtyCustomPath = true
|
||||
}
|
||||
}}
|
||||
bind:value={customPath}
|
||||
error={dirtyCustomPath ? customPathError : undefined}
|
||||
/>
|
||||
{#if dirtyCustomPath && customPathError}
|
||||
<div class="text-2xs text-red-600 dark:text-red-400">{customPathError}</div>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="text-emphasis text-xs font-semibold">Custom public URL</div>
|
||||
<ClipboardPanel
|
||||
content={embedMode ? toEmbedSnippet(fullCustomUrl) : fullCustomUrl}
|
||||
size="md"
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<a
|
||||
href="https://www.windmill.dev/docs/advanced/external_auth_with_jwt#embed-public-apps-using-your-own-authentification"
|
||||
class="block mt-6 text-2xs"
|
||||
>Embed this app in your own product to be used by your own users</a
|
||||
>
|
||||
</Section>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,687 @@
|
||||
<script lang="ts">
|
||||
import { Alert, Drawer, DrawerContent, Section } from '$lib/components/common'
|
||||
import Toggle from '$lib/components/Toggle.svelte'
|
||||
import Label from '$lib/components/Label.svelte'
|
||||
import { enterpriseLicense, userStore } from '$lib/stores'
|
||||
import { useRoleCapabilities } from '$lib/operatorWriteRights'
|
||||
import { Loader2 } from 'lucide-svelte'
|
||||
|
||||
import Tooltip from '$lib/components/Tooltip.svelte'
|
||||
|
||||
import ClipboardPanel from '$lib/components/details/ClipboardPanel.svelte'
|
||||
import { tick, untrack } from 'svelte'
|
||||
import { revealSetting } from '$lib/components/itemSettings/ActiveSettingChips.svelte'
|
||||
import { AppService, SettingService, WorkspaceService } from '$lib/gen'
|
||||
import type { GuestUsage, Policy } from '$lib/gen'
|
||||
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
|
||||
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
|
||||
import Path from '$lib/components/Path.svelte'
|
||||
import { computeSecretUrl } from './appDeploy.svelte'
|
||||
import { isCloudHosted } from '$lib/cloud'
|
||||
import TextInput from '$lib/components/text_input/TextInput.svelte'
|
||||
import LabelsInput from '$lib/components/LabelsInput.svelte'
|
||||
import RunOnBehalfOfSetting from '$lib/components/itemSettings/RunOnBehalfOfSetting.svelte'
|
||||
import {
|
||||
appOnBehalfOfTooltip,
|
||||
canPreserveOnBehalfOf
|
||||
} from '$lib/components/itemSettings/onBehalfOf'
|
||||
import SettingToggle from '$lib/components/itemSettings/SettingToggle.svelte'
|
||||
import SettingIcons from '$lib/components/itemSettings/SettingIcons.svelte'
|
||||
import {
|
||||
getAppMetadataBadges,
|
||||
getAppPermissionBadges,
|
||||
getAppSharingBadges
|
||||
} from './appSettingsBadges'
|
||||
import { canUserBypassRuleKind, protectionRulesState } from '$lib/workspaceProtectionRules.svelte'
|
||||
import { FRONTEND_SDK_SCOPES, sdkScopesToConfirm } from '$lib/components/raw_apps/sdkScopes'
|
||||
import { logFeatureUsage } from '$lib/utils/featureUsage'
|
||||
import {
|
||||
useOperatingUser,
|
||||
useOperatingWorkspace
|
||||
} from '$lib/components/operatingWorkspace.svelte'
|
||||
|
||||
const operatingWorkspaceStore = useOperatingWorkspace()
|
||||
const operatingUser = useOperatingUser()
|
||||
const actingUser = $derived(operatingUser.current)
|
||||
const roleCaps = useRoleCapabilities()
|
||||
// The server forces a composed app into sandbox isolation.
|
||||
const composeOnlyApps = $derived($roleCaps.apps === 'compose')
|
||||
|
||||
let {
|
||||
open = $bindable(),
|
||||
policy = $bindable(),
|
||||
appPath,
|
||||
customPath = $bindable(),
|
||||
savedApp,
|
||||
summary = $bindable(),
|
||||
customPathError = $bindable(),
|
||||
pathError = $bindable(),
|
||||
newEditedPath = $bindable(),
|
||||
newPath,
|
||||
labels = $bindable(),
|
||||
rawApp = false,
|
||||
newApp = false,
|
||||
operatingWorkspace = undefined,
|
||||
showErrors = false,
|
||||
setAccessMode
|
||||
}: {
|
||||
open: boolean
|
||||
/** Mutated in place and deployed with the app, except who can open it: see `setAccessMode`. */
|
||||
policy: Policy
|
||||
appPath: string
|
||||
customPath: string | undefined
|
||||
savedApp: { path: string; policy: any; custom_path?: string } | undefined
|
||||
summary: string
|
||||
customPathError: string
|
||||
pathError: string
|
||||
newEditedPath: string
|
||||
newPath: string
|
||||
labels?: string[] | undefined
|
||||
// Only raw apps are offered the `wm_coep` embedding hint: on a classic
|
||||
// (low-code) app COEP breaks no-CORP cross-origin subresources (external
|
||||
// images, {@html} embeds, CDN imports) that the app cannot opt out of.
|
||||
rawApp?: boolean
|
||||
/** True while the editor is on a draft-only URL (`/edit/u/{user}/draft_{uuid}`
|
||||
* with no deployed row yet). Suppresses the public-secret-URL fetch
|
||||
* (`/secret_of/...` 404s with no `app` row) and renders a placeholder
|
||||
* instead of the eternally-spinning link. */
|
||||
newApp?: boolean
|
||||
/** Workspace the app is deployed to. The secret-URL / custom-path / folder /
|
||||
* on-behalf-of lookups target it; defaults to the operating workspace. */
|
||||
operatingWorkspace?: string
|
||||
/** A deploy was refused over these errors: show them before the fields are edited. */
|
||||
showErrors?: boolean
|
||||
/** Changes who can open the deployed app at once, leaving the rest of its deployed policy. */
|
||||
setAccessMode: (mode: NonNullable<Policy['execution_mode']>) => Promise<void>
|
||||
} = $props()
|
||||
|
||||
let body: HTMLElement | undefined = $state()
|
||||
|
||||
/** Opens the drawer scrolled to the row whose `data-setting` is `setting`, or at the top. */
|
||||
export async function openAt(setting?: string) {
|
||||
open = true
|
||||
if (!setting) return
|
||||
await tick()
|
||||
revealSetting(body, setting)
|
||||
}
|
||||
|
||||
const opWs = $derived(operatingWorkspace ?? $operatingWorkspaceStore)
|
||||
|
||||
// Admins always pass the backend check. For everyone else, fail closed
|
||||
// while the workspace protection rules are still loading so the toggle
|
||||
// is never briefly enabled for a user the rules will end up restricting.
|
||||
let rulesetsLoaded = $derived(protectionRulesState.rulesets !== undefined)
|
||||
let canSetAnonymous = $derived(
|
||||
!!actingUser?.is_admin ||
|
||||
!!actingUser?.is_super_admin ||
|
||||
(rulesetsLoaded &&
|
||||
canUserBypassRuleKind('RestrictAnonymousAppDeployment', $userStore ?? undefined))
|
||||
)
|
||||
let canSetGuest = $derived(
|
||||
!!actingUser?.is_admin ||
|
||||
!!actingUser?.is_super_admin ||
|
||||
(rulesetsLoaded &&
|
||||
canUserBypassRuleKind('RestrictGuestAppDeployment', $userStore ?? undefined))
|
||||
)
|
||||
// The three rungs of the access control, widest last. `viewer` is a fourth
|
||||
// execution mode that this control never sets (it runs components as the viewer,
|
||||
// which a guest cannot be), so an app in it shows as members-only here.
|
||||
let accessMode = $derived(
|
||||
policy.execution_mode == 'anonymous'
|
||||
? 'anonymous'
|
||||
: policy.execution_mode == 'guest'
|
||||
? 'guest'
|
||||
: 'publisher'
|
||||
)
|
||||
let guestUsage: GuestUsage | undefined = $state(undefined)
|
||||
// Whether the deployment can have guests at all; off, the mode is not on offer. The
|
||||
// backend decides; the hostname stands in until it has answered, the shared cloud
|
||||
// being the only deployment where guests are unavailable.
|
||||
let guestsAvailable = $derived.by(() => guestUsage?.available ?? !isCloudHosted())
|
||||
|
||||
$effect(() => {
|
||||
const ws = opWs
|
||||
if (ws === undefined) return
|
||||
untrack(() => {
|
||||
WorkspaceService.getGuestUsage({ workspace: ws })
|
||||
.then((u) => (guestUsage = u))
|
||||
.catch(() => (guestUsage = undefined))
|
||||
})
|
||||
})
|
||||
|
||||
// The server refuses to change the mode alone of an app that runs as someone else unless the
|
||||
// caller may keep that identity, and always for a builder, who is also refused on an app whose
|
||||
// deployed policy is not sandboxed. The control is locked rather than holding the choice for a
|
||||
// deploy: no draft carries the mode, so a held choice would be lost on reload or Review & Deploy.
|
||||
let deployedApp = $derived(!!savedApp && !newApp)
|
||||
let deployedRunsAs = $derived(savedApp?.policy?.on_behalf_of as string | undefined)
|
||||
let runsAsAnotherForCaller = $derived(
|
||||
deployedApp &&
|
||||
!!deployedRunsAs &&
|
||||
deployedRunsAs !== (actingUser?.username ? `u/${actingUser.username}` : undefined) &&
|
||||
(!canPreserveOnBehalfOf(actingUser) || composeOnlyApps)
|
||||
)
|
||||
let unsandboxedForBuilder = $derived(
|
||||
deployedApp && composeOnlyApps && savedApp?.policy?.sandbox !== true
|
||||
)
|
||||
let accessModeLocked = $derived(runsAsAnotherForCaller || unsandboxedForBuilder)
|
||||
// One change at a time: a failed request puts back the mode it replaced, which would
|
||||
// overwrite a newer selection that already succeeded.
|
||||
let accessModePending = $state(false)
|
||||
async function onAccessModeChange(mode: string | undefined) {
|
||||
if (mode === undefined || mode === accessMode || accessModePending || accessModeLocked) return
|
||||
const previous = policy.execution_mode
|
||||
policy.execution_mode = mode as Policy['execution_mode']
|
||||
// A not-yet-deployed app has no row to update: its first deploy carries the mode.
|
||||
if (!deployedApp) return
|
||||
accessModePending = true
|
||||
try {
|
||||
await setAccessMode(mode as NonNullable<Policy['execution_mode']>)
|
||||
} catch (e) {
|
||||
policy.execution_mode = previous
|
||||
throw e
|
||||
} finally {
|
||||
accessModePending = false
|
||||
}
|
||||
}
|
||||
|
||||
let isAdmin = $derived(!!actingUser?.is_admin || !!actingUser?.is_super_admin)
|
||||
|
||||
// The URLs below only serve what is deployed, so a pending custom URL must not read as live.
|
||||
let sharingChanged = $derived(!newApp && (customPath ?? null) !== (savedApp?.custom_path ?? null))
|
||||
let pathChanged = $derived(
|
||||
!newApp && !!savedApp?.path && !!newEditedPath && newEditedPath !== savedApp.path
|
||||
)
|
||||
|
||||
let dirtyCustomPath = $state(false)
|
||||
let path: Path | undefined = $state(undefined)
|
||||
|
||||
let dirtyPath = $state(false)
|
||||
|
||||
async function appExists(customPath: string) {
|
||||
return await AppService.customPathExists({
|
||||
workspace: opWs!,
|
||||
customPath
|
||||
})
|
||||
}
|
||||
|
||||
let globalWorkspacedRoute = $state(false)
|
||||
|
||||
async function loadGlobalWorkspacedRouteSetting() {
|
||||
try {
|
||||
const setting = await SettingService.getGlobal({ key: 'app_workspaced_route' })
|
||||
globalWorkspacedRoute = (setting as boolean) ?? false
|
||||
} catch (error) {
|
||||
globalWorkspacedRoute = false
|
||||
}
|
||||
}
|
||||
|
||||
loadGlobalWorkspacedRouteSetting()
|
||||
|
||||
let secretUrl: string | undefined = $state(undefined)
|
||||
let secretUrlHref = $derived(secretUrl ? computeSecretUrl(secretUrl, opWs) : undefined)
|
||||
let fullCustomUrl = $derived(
|
||||
`${window.location.origin}/a/${
|
||||
isCloudHosted() || globalWorkspacedRoute ? opWs + '/' : ''
|
||||
}${customPath}`
|
||||
)
|
||||
|
||||
// The app URL a guest JWT rides on: append `guest.<jwt>` and the viewer authenticates the
|
||||
// token as a seatless guest. Uses the custom URL when set, else the public secret URL.
|
||||
let guestJwtBase = $derived(customPath !== undefined ? fullCustomUrl : secretUrlHref)
|
||||
|
||||
let embedMode = $state(false)
|
||||
function toEmbedSnippet(url: string): string {
|
||||
return `<iframe src="${url}" title="Windmill app" width="100%" height="600"></iframe>`
|
||||
}
|
||||
async function getSecretUrl() {
|
||||
secretUrl = await AppService.getPublicSecretOfApp({
|
||||
workspace: opWs!,
|
||||
path: appPath
|
||||
})
|
||||
}
|
||||
|
||||
let validateTimeout: number | undefined = undefined
|
||||
async function validateCustomPath(customPath: string): Promise<void> {
|
||||
customPathError = ''
|
||||
if (validateTimeout) {
|
||||
clearTimeout(validateTimeout)
|
||||
}
|
||||
validateTimeout = setTimeout(async () => {
|
||||
if (!/^[\w-]+(\/[\w-]+)*$/.test(customPath)) {
|
||||
customPathError = 'Invalid path'
|
||||
} else if (customPath !== savedApp?.custom_path && (await appExists(customPath))) {
|
||||
customPathError = 'Path already taken'
|
||||
} else {
|
||||
customPathError = ''
|
||||
}
|
||||
validateTimeout = undefined
|
||||
}, 500)
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
;[customPath]
|
||||
untrack(() => customPath !== undefined && validateCustomPath(customPath))
|
||||
})
|
||||
|
||||
$effect(() => {
|
||||
// Skip the secret URL fetch on draft-only items — `/secret_of/...`
|
||||
// has no `app` row to look up and would 404, leaving the UI
|
||||
// component spinning indefinitely.
|
||||
open &&
|
||||
!newApp &&
|
||||
appPath &&
|
||||
appPath != '' &&
|
||||
savedApp &&
|
||||
secretUrl == undefined &&
|
||||
untrack(() => getSecretUrl())
|
||||
})
|
||||
</script>
|
||||
|
||||
{#snippet sandboxHint()}
|
||||
{#if composeOnlyApps}
|
||||
Required for apps composed by your role, and cannot be turned off.
|
||||
{:else}
|
||||
<Alert type="warning" title="Not isolated" size="xs">
|
||||
The app's frontend code runs with each viewer's full Windmill permissions. A future version
|
||||
will ask viewers to approve this. Keep isolation off only if the app needs it.
|
||||
</Alert>
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
{#snippet adminOnlyHint()}
|
||||
Only workspace admins can set a custom URL.
|
||||
{/snippet}
|
||||
|
||||
<Drawer bind:open size="800px">
|
||||
<DrawerContent noPadding title="Settings" on:close={() => (open = false)}>
|
||||
<div bind:this={body} class="h-full overflow-y-auto">
|
||||
<div class="flex flex-col gap-10 p-4 pb-8">
|
||||
<Section label="Metadata">
|
||||
{#snippet labelExtra()}
|
||||
<SettingIcons badges={getAppMetadataBadges(labels)} />
|
||||
{/snippet}
|
||||
<div class="flex flex-col gap-6">
|
||||
<Label label="Summary" for="app-summary">
|
||||
<!-- svelte-ignore a11y_autofocus -->
|
||||
<TextInput
|
||||
inputProps={{
|
||||
id: 'app-summary',
|
||||
autofocus: true,
|
||||
placeholder: 'Short summary to be displayed when listed',
|
||||
onkeydown: (e) => {
|
||||
e.stopPropagation()
|
||||
},
|
||||
onkeyup: () => {
|
||||
if (appPath == '' && summary?.length > 0 && !dirtyPath) {
|
||||
path?.setName(
|
||||
summary
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9_]/g, '_')
|
||||
.replace(/-+/g, '_')
|
||||
.replace(/^-|-$/g, '')
|
||||
)
|
||||
}
|
||||
}
|
||||
}}
|
||||
bind:value={summary}
|
||||
/>
|
||||
</Label>
|
||||
<div data-setting="labels" class="-mt-4"><LabelsInput bind:labels /></div>
|
||||
<Label label="Path">
|
||||
{#snippet header()}
|
||||
<Tooltip
|
||||
documentationLink="https://www.windmill.dev/docs/core_concepts/roles_and_permissions#path"
|
||||
>
|
||||
The unique identifier of the app in the workspace that defines permissions
|
||||
</Tooltip>
|
||||
{/snippet}
|
||||
<Path
|
||||
bind:this={path}
|
||||
bind:dirty={dirtyPath}
|
||||
bind:error={pathError}
|
||||
bind:path={newEditedPath}
|
||||
initialPath={newPath}
|
||||
namePlaceholder="app"
|
||||
kind="app"
|
||||
autofocus={false}
|
||||
workspaceOverride={operatingWorkspace}
|
||||
/>
|
||||
{#if pathChanged}
|
||||
<Alert
|
||||
type="info"
|
||||
size="xs"
|
||||
title="Deploy the app to make the path change effective."
|
||||
class="mt-2"
|
||||
/>
|
||||
{/if}
|
||||
</Label>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section label="Permissions">
|
||||
{#snippet labelExtra()}
|
||||
<SettingIcons
|
||||
badges={getAppPermissionBadges(policy, composeOnlyApps || policy.sandbox == true)}
|
||||
/>
|
||||
{/snippet}
|
||||
<div class="flex flex-col gap-6">
|
||||
<RunOnBehalfOfSetting
|
||||
kind="app"
|
||||
required
|
||||
tooltip={appOnBehalfOfTooltip(rawApp)}
|
||||
bind:email={policy.on_behalf_of_email}
|
||||
bind:permissionedAs={policy.on_behalf_of}
|
||||
savedEmail={savedApp?.policy?.on_behalf_of_email}
|
||||
savedPermissionedAs={savedApp?.policy?.on_behalf_of}
|
||||
targetWorkspace={opWs ?? ''}
|
||||
isNew={newApp}
|
||||
/>
|
||||
|
||||
<SettingToggle
|
||||
setting="sandbox"
|
||||
label="Sandbox isolation"
|
||||
tooltip="Controls what the app's browser-side code can reach in each viewer's browser, separately from who its runnables run as. A sandboxed app gets a narrowly scoped token on every surface, public URL and in-workspace. On by default for new apps. Turn it off only if the app needs IndexedDB, third-party sign-in or OAuth redirects."
|
||||
checked={composeOnlyApps || policy.sandbox == true}
|
||||
disabled={composeOnlyApps}
|
||||
hint={composeOnlyApps || policy.sandbox != true ? sandboxHint : undefined}
|
||||
onchange={(on) => {
|
||||
policy.sandbox = on || undefined
|
||||
// Counted where the toggle is flipped rather than where the policy is
|
||||
// persisted, so a choice made before the first deploy counts too.
|
||||
logFeatureUsage('app_sandbox', 'toggled', {
|
||||
key: `${rawApp ? 'raw' : 'low_code'}:${on ? 'on' : 'off'}`
|
||||
})
|
||||
// Frontend API access exists only for a sandboxed app, so turning
|
||||
// isolation off drops the declared scopes with it rather than leaving
|
||||
// them set but inert.
|
||||
if (!on) {
|
||||
policy.frontend_sdk_scopes = undefined
|
||||
}
|
||||
}}
|
||||
>
|
||||
{#if rawApp}
|
||||
<Label
|
||||
label="Frontend API access"
|
||||
tooltip="Each viewer approves these scopes before the app runs. The app's code, or an XSS bug in it, can use them as that viewer."
|
||||
>
|
||||
<div class="text-xs text-secondary">
|
||||
Let the app's frontend call the Windmill API as <b>the viewer</b> through the
|
||||
<code>windmill-client</code> SDK, which it lists as a dependency. Grant only what
|
||||
the app needs.
|
||||
</div>
|
||||
<div class="flex flex-col gap-2 mt-2">
|
||||
{#each FRONTEND_SDK_SCOPES as scope (scope.value)}
|
||||
<div>
|
||||
<Toggle
|
||||
size="xs"
|
||||
options={{ right: scope.label }}
|
||||
checked={policy.frontend_sdk_scopes?.includes(scope.value) ?? false}
|
||||
on:change={(e) => {
|
||||
const current: string[] = policy.frontend_sdk_scopes ?? []
|
||||
const next = e.detail
|
||||
? [...current, scope.value]
|
||||
: current.filter((s) => s !== scope.value)
|
||||
// Keep the curated order so the consent banner and the stored
|
||||
// consent compare stably across deploys. A leftover implicit scope is
|
||||
// not in the list, so it drops here rather than keep minting a token
|
||||
// for an app whose toggles all read off.
|
||||
const ordered = FRONTEND_SDK_SCOPES.map((s) => s.value).filter((s) =>
|
||||
next.includes(s)
|
||||
)
|
||||
policy.frontend_sdk_scopes = ordered.length > 0 ? ordered : undefined
|
||||
}}
|
||||
/>
|
||||
<div class="text-2xs text-secondary pl-9">{scope.description}</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{#if sdkScopesToConfirm(policy.frontend_sdk_scopes ?? []).length}
|
||||
<div class="mt-2">
|
||||
<Alert
|
||||
type="info"
|
||||
title="Redeploy to use the SDK from a sandboxed app"
|
||||
size="xs"
|
||||
>
|
||||
A sandboxed app calls the API cross-origin, which older <code
|
||||
>windmill-client</code
|
||||
>
|
||||
versions cannot do. An app bundled before this Windmill version fails with a
|
||||
CORS error until you deploy it again, which re-bundles it against a current client.
|
||||
</Alert>
|
||||
</div>
|
||||
{/if}
|
||||
</Label>
|
||||
{/if}
|
||||
</SettingToggle>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section label="Sharing">
|
||||
{#snippet labelExtra()}
|
||||
<SettingIcons badges={getAppSharingBadges(policy.execution_mode, customPath)} />
|
||||
{/snippet}
|
||||
<div class="flex flex-col gap-6">
|
||||
{#if sharingChanged}
|
||||
<Alert type="info" size="xs" title="Deploy the app to apply these changes." />
|
||||
{/if}
|
||||
<div data-setting="access">
|
||||
<Label label="Access">
|
||||
{#if rulesetsLoaded && !canSetAnonymous && policy.execution_mode != 'anonymous'}
|
||||
<Alert type="warning" title="Restricted by a workspace protection rule" size="xs">
|
||||
Opening this app to anyone with the link is restricted to workspace admins and
|
||||
bypass users by a workspace protection rule
|
||||
</Alert>
|
||||
{/if}
|
||||
{#if rulesetsLoaded && !canSetGuest && policy.execution_mode != 'guest' && guestsAvailable}
|
||||
<Alert type="warning" title="Restricted by a workspace protection rule" size="xs">
|
||||
Opening this app to guests is restricted to workspace admins and bypass users by
|
||||
a workspace protection rule
|
||||
</Alert>
|
||||
{/if}
|
||||
<div>
|
||||
<!-- Bound through accessors: given `selected` one way, the group keeps the
|
||||
choice it was clicked to, and a refused change would stay shown. -->
|
||||
<ToggleButtonGroup
|
||||
bind:selected={() => accessMode, (mode) => onAccessModeChange(mode)}
|
||||
disabled={accessModePending || accessModeLocked}
|
||||
>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton
|
||||
label="Members"
|
||||
value="publisher"
|
||||
tooltip="Workspace members with read access on this app."
|
||||
{item}
|
||||
/>
|
||||
<ToggleButton
|
||||
label="Guests"
|
||||
value="guest"
|
||||
disabled={policy.execution_mode != 'guest' &&
|
||||
(!guestsAvailable || !canSetGuest)}
|
||||
tooltip={!guestsAvailable
|
||||
? 'Not available on Windmill Cloud. Guests require a self-hosted instance or a dedicated Windmill Cloud deployment.'
|
||||
: "Anyone your identity provider authenticates who has no Windmill account, plus workspace members. No membership, no seat up to the instance's allowance."}
|
||||
{item}
|
||||
/>
|
||||
<ToggleButton
|
||||
label="Public"
|
||||
value="anonymous"
|
||||
disabled={!canSetAnonymous && policy.execution_mode != 'anonymous'}
|
||||
tooltip="Anyone with the secret URL. No login."
|
||||
{item}
|
||||
/>
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
</div>
|
||||
{#if accessModeLocked}
|
||||
<div class="text-xs text-secondary">
|
||||
{#if runsAsAnotherForCaller}
|
||||
This app runs on behalf of <strong>{deployedRunsAs}</strong>. Deploy it so it
|
||||
runs on behalf of you, then change who can open it.
|
||||
{#if !composeOnlyApps}
|
||||
An admin or a member of <code>wm_deployers</code> can change it without taking
|
||||
the app over.
|
||||
{/if}
|
||||
{:else}
|
||||
This app is not sandboxed yet. Deploy it so it is sandboxed, then change who
|
||||
can open it.
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="text-xs text-secondary">
|
||||
{#if policy.execution_mode == 'anonymous'}
|
||||
Anyone holding the secret URL below can open this app without signing in.
|
||||
{:else if policy.execution_mode == 'guest'}
|
||||
{#if !guestsAvailable}
|
||||
Guests are not available on Windmill Cloud, so this app still admits members
|
||||
only. They require a self-hosted instance or a dedicated Windmill Cloud
|
||||
deployment.
|
||||
{:else}
|
||||
Anyone your identity provider authenticates can open this app without a
|
||||
Windmill account. They join no workspace. Members of this workspace can open
|
||||
it too.
|
||||
{#if guestUsage}
|
||||
{guestUsage.guest_count} of {guestUsage.free_allowance} free guests used across
|
||||
this instance in the last {guestUsage.window_days} days; beyond that,
|
||||
{guestUsage.metered
|
||||
? 'every four guests count as one seat'
|
||||
: 'new guests are refused until the count drops'}.
|
||||
{/if}
|
||||
{/if}
|
||||
{:else}
|
||||
Only workspace members with read access on this app can open it.
|
||||
{/if}
|
||||
</div>
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
<Label
|
||||
label="Secret URL"
|
||||
tooltip="An unguessable link to the app. Who it lets in depends on the access above."
|
||||
>
|
||||
{#snippet action()}
|
||||
{#if savedApp && !newApp && secretUrlHref}
|
||||
<Toggle
|
||||
size="xs"
|
||||
checked={embedMode}
|
||||
on:change={(e) => (embedMode = e.detail)}
|
||||
options={{ left: 'URL', right: 'Embed' }}
|
||||
/>
|
||||
{/if}
|
||||
{/snippet}
|
||||
{#if !savedApp || newApp}
|
||||
<ClipboardPanel
|
||||
content={`Deploy this app once to get the public secret URL`}
|
||||
size="md"
|
||||
/>
|
||||
{:else if secretUrlHref}
|
||||
<ClipboardPanel
|
||||
content={embedMode ? toEmbedSnippet(secretUrlHref) : secretUrlHref}
|
||||
size="md"
|
||||
/>
|
||||
{:else}<Loader2 size={16} class="animate-spin" />
|
||||
{/if}
|
||||
<div class="text-2xs text-secondary">
|
||||
{#if embedMode}
|
||||
Paste this iframe snippet into another app.
|
||||
{#if rawApp}
|
||||
To embed it in a cross-origin isolated page, add <code>wm_coep=on</code>
|
||||
<Tooltip
|
||||
>Sets the cross-origin isolation headers (COEP) on the app, which such a page
|
||||
requires of its iframes. The app then only loads cross-origin resources that
|
||||
send CORS or a Cross-Origin-Resource-Policy header.</Tooltip
|
||||
> to the URL.
|
||||
{/if}
|
||||
(if requiring login, top-level domain of embedding app must be the same as the one
|
||||
of Windmill)
|
||||
{:else}
|
||||
Share this URL directly, or switch to <b>Embed</b> to get an iframe snippet. Only the
|
||||
latest deployed version is served.
|
||||
{/if}
|
||||
</div>
|
||||
</Label>
|
||||
|
||||
{#if embedMode && policy.execution_mode == 'guest' && guestJwtBase && guestsAvailable}
|
||||
<Label label="Embed for your own authenticated users (guest JWT)">
|
||||
<div class="text-xs text-secondary">
|
||||
To open this app for a user your own product already authenticates, mint a
|
||||
short-lived JWT in your backend and append it to the app URL as <code
|
||||
>guest.<jwt></code
|
||||
>. Each token is its own seatless guest, confined to this app. Unlike the plain
|
||||
secret URL above, there is no shared secret and no Windmill account.
|
||||
</div>
|
||||
<div class="text-xs text-secondary">
|
||||
Windmill verifies the token against the workspace's guest JWT key (Workspace
|
||||
settings → Guests): a PEM public key or a JWKS URL{#if !isCloudHosted()}, or the
|
||||
instance's configured issuer (<code>JWT_EXT_JWKS_URL</code>) when no workspace
|
||||
key is set{/if}. Set the <b>public</b> half there; in your backend, sign each
|
||||
token with the matching
|
||||
<b>private</b> key using RS256/384/512, PS256/384/512 or ES256/384 (symmetric HS*
|
||||
is refused), carrying <code>email</code>,
|
||||
<code>workspace_id</code>
|
||||
=
|
||||
<code>{opWs}</code>, <code>app_path</code> = <code>{appPath}</code> and
|
||||
<code>exp</code> (at most 24h ahead).
|
||||
</div>
|
||||
<ClipboardPanel
|
||||
content={toEmbedSnippet(`${guestJwtBase}/guest.YOUR_GUEST_JWT`)}
|
||||
size="md"
|
||||
/>
|
||||
<div class="text-2xs text-secondary">
|
||||
Replace <code>YOUR_GUEST_JWT</code> with the token your backend signs per user. Past
|
||||
the instance's free guest allowance a new guest email is refused (see the count above);
|
||||
guests already seen in the window keep working.
|
||||
</div>
|
||||
</Label>
|
||||
{/if}
|
||||
|
||||
<SettingToggle
|
||||
setting="custom-url"
|
||||
label="Custom URL"
|
||||
tooltip="Serve the app at a path you pick, on top of its secret URL."
|
||||
eeOnly
|
||||
disabled={!$enterpriseLicense || !isAdmin}
|
||||
checked={customPath !== undefined}
|
||||
hint={!isAdmin ? adminOnlyHint : undefined}
|
||||
onchange={(on) => {
|
||||
customPath = on ? '' : undefined
|
||||
if (!on) {
|
||||
customPathError = ''
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Label label="Custom path" for="customPath">
|
||||
<TextInput
|
||||
inputProps={{
|
||||
id: 'customPath',
|
||||
autocomplete: 'off',
|
||||
disabled: !isAdmin,
|
||||
oninput: () => {
|
||||
dirtyCustomPath = true
|
||||
}
|
||||
}}
|
||||
bind:value={customPath}
|
||||
error={dirtyCustomPath || showErrors ? customPathError : undefined}
|
||||
/>
|
||||
{#if (dirtyCustomPath || showErrors) && customPathError}
|
||||
<div class="text-2xs text-red-600 dark:text-red-400">{customPathError}</div>
|
||||
{/if}
|
||||
</Label>
|
||||
<Label label="Custom public URL">
|
||||
<ClipboardPanel
|
||||
content={embedMode ? toEmbedSnippet(fullCustomUrl) : fullCustomUrl}
|
||||
size="md"
|
||||
/>
|
||||
</Label>
|
||||
</SettingToggle>
|
||||
|
||||
<a
|
||||
href="https://www.windmill.dev/docs/advanced/external_auth_with_jwt#embed-public-apps-using-your-own-authentification"
|
||||
class="text-2xs">Embed this app in your own product to be used by your own users</a
|
||||
>
|
||||
</div>
|
||||
</Section>
|
||||
</div>
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
@@ -1,6 +1,54 @@
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { get } from 'svelte/store'
|
||||
import { AppService, type Policy } from '$lib/gen'
|
||||
import { deployedPermissionedAs } from '$lib/components/itemSettings/onBehalfOf'
|
||||
|
||||
export function computeSecretUrl(secretUrl: string) {
|
||||
return `${window.location.origin}/public/${get(workspaceStore)}/${secretUrl}`
|
||||
type RunAs = { on_behalf_of?: string; on_behalf_of_email?: string }
|
||||
type DeployingUser = Parameters<typeof deployedPermissionedAs>[0]
|
||||
|
||||
export function computeSecretUrl(secretUrl: string, workspace: string | undefined) {
|
||||
return `${window.location.origin}/public/${workspace}/${secretUrl}`
|
||||
}
|
||||
|
||||
/** The user the app at `path` runs on behalf of right now, read from its row: the editor's copy
|
||||
* is the one it loaded, which another deploy may have replaced since. Undefined when the read
|
||||
* fails. */
|
||||
export async function fetchDeployedRunAs(
|
||||
workspace: string,
|
||||
path: string
|
||||
): Promise<RunAs | undefined> {
|
||||
try {
|
||||
const { on_behalf_of, on_behalf_of_email } = (
|
||||
await AppService.getAppLiteByPath({ workspace, path })
|
||||
).policy
|
||||
return { on_behalf_of, on_behalf_of_email }
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** Who can open the app at `path` right now. An update deploy states no mode, so the server keeps
|
||||
* the deployed one, which someone may have changed since the editor loaded the app. Undefined
|
||||
* when the read fails. */
|
||||
export async function fetchDeployedAccessMode(
|
||||
workspace: string,
|
||||
path: string
|
||||
): Promise<Policy['execution_mode'] | undefined> {
|
||||
try {
|
||||
return (await AppService.getAppLiteByPath({ workspace, path })).policy.execution_mode
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes into an app's policy the user its deploy will run on behalf of, so the request names
|
||||
* it. The editor keeps the policy it sent as the deployed one, so it has to say what the backend
|
||||
* stores, or the next deploy would see a change that already happened. */
|
||||
export function setDeployedOnBehalfOf(
|
||||
policy: RunAs,
|
||||
user: DeployingUser,
|
||||
folderDefault?: string
|
||||
): void {
|
||||
const runsAs = deployedPermissionedAs(user, policy.on_behalf_of, folderDefault)
|
||||
if (!runsAs || runsAs === policy.on_behalf_of) return
|
||||
policy.on_behalf_of = runsAs
|
||||
policy.on_behalf_of_email = runsAs === `u/${user?.username}` ? user?.email : undefined
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { setDeployedOnBehalfOf } from './appDeploy.svelte'
|
||||
|
||||
// The app editors keep the policy they sent as the deployed one.
|
||||
describe('setDeployedOnBehalfOf', () => {
|
||||
const admin = { username: 'admin', email: 'admin@x.dev', is_admin: true }
|
||||
const member = { username: 'alice', email: 'alice@x.dev' }
|
||||
|
||||
it('writes the stored user into the policy, with the email only for the deployer', () => {
|
||||
const forMember = { on_behalf_of: 'u/bot', on_behalf_of_email: 'bot@x.dev' }
|
||||
setDeployedOnBehalfOf(forMember, member)
|
||||
expect(forMember).toEqual({ on_behalf_of: 'u/alice', on_behalf_of_email: 'alice@x.dev' })
|
||||
|
||||
const newInFolder: { on_behalf_of?: string; on_behalf_of_email?: string } = {}
|
||||
setDeployedOnBehalfOf(newInFolder, admin, 'u/folder')
|
||||
expect(newInFolder).toEqual({ on_behalf_of: 'u/folder', on_behalf_of_email: undefined })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { Policy } from '$lib/gen'
|
||||
import { withDraftPolicySettings } from './appDraftSettings'
|
||||
|
||||
describe('withDraftPolicySettings', () => {
|
||||
it('keeps a setting the draft turned off, and the undrafted fields from the deployed policy', () => {
|
||||
const deployed = {
|
||||
execution_mode: 'anonymous',
|
||||
sandbox: true,
|
||||
frontend_sdk_scopes: ['resources:read'],
|
||||
triggerables_v2: { 'a:rawscript/x': {} }
|
||||
} as unknown as Policy
|
||||
// Sandbox off drops the key, and the scopes with it; a stale drafted access mode is ignored.
|
||||
const draft = { execution_mode: 'publisher' } as Partial<Policy>
|
||||
expect(withDraftPolicySettings(deployed, draft)).toEqual({
|
||||
execution_mode: 'anonymous',
|
||||
triggerables_v2: { 'a:rawscript/x': {} }
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { Policy } from '$lib/gen'
|
||||
|
||||
/** Policy fields a draft leaves to the deployed row: the ones `updatePolicy` rebuilds from the
|
||||
* app value on every deploy, and who can open the app, which the editor holds until Deploy. */
|
||||
const UNDRAFTED_POLICY_KEYS = [
|
||||
'triggerables',
|
||||
'triggerables_v2',
|
||||
's3_inputs',
|
||||
'allowed_s3_keys',
|
||||
'execution_mode'
|
||||
]
|
||||
|
||||
/** The part of a policy an app draft carries (sandbox, on-behalf-of, SDK scopes). The derived
|
||||
* part describes the deployed value, and a draft holding it would differ from the deployed row
|
||||
* after every runnable edit. */
|
||||
export function policySettings(policy: Policy | Partial<Policy> | undefined): Partial<Policy> {
|
||||
const settings: Record<string, unknown> = { ...(policy ?? {}) }
|
||||
for (const k of UNDRAFTED_POLICY_KEYS) delete settings[k]
|
||||
return settings as Partial<Policy>
|
||||
}
|
||||
|
||||
export type AppDraftSettings = {
|
||||
policy: Partial<Policy>
|
||||
labels: string[]
|
||||
}
|
||||
|
||||
/** The settings an app draft mirrors onto the App value, normalized so the editor's mirror and
|
||||
* the deployed baseline it is compared against agree on "unchanged". */
|
||||
export function appDraftSettings(s: {
|
||||
policy?: Policy | Partial<Policy>
|
||||
labels?: string[] | null
|
||||
}): AppDraftSettings {
|
||||
return {
|
||||
policy: policySettings(s.policy),
|
||||
labels: s.labels ?? []
|
||||
}
|
||||
}
|
||||
|
||||
/** A drafted policy's settings over the deployed policy's undrafted fields. Every setting comes
|
||||
* from the draft, absent ones included: a setting turned off is absent from the draft's JSON,
|
||||
* and spreading the draft over the deployed policy would turn it back on. */
|
||||
export function withDraftPolicySettings(
|
||||
deployed: Policy | undefined,
|
||||
draftSettings: Partial<Policy>
|
||||
): Policy {
|
||||
const d = (deployed ?? {}) as Record<string, unknown>
|
||||
const undrafted = Object.fromEntries(
|
||||
UNDRAFTED_POLICY_KEYS.filter((k) => d[k] !== undefined).map((k) => [k, d[k]])
|
||||
)
|
||||
return { ...policySettings(draftSettings), ...undrafted } as Policy
|
||||
}
|
||||
|
||||
/** A classic app's settings as the draft states them, falling back field by field to the
|
||||
* deployed row for a draft that predates mirroring them. */
|
||||
export function draftOrDeployedSettings(
|
||||
parts: {
|
||||
policy?: Record<string, unknown>
|
||||
labels?: string[]
|
||||
},
|
||||
row: { policy?: Policy; labels?: string[] | null }
|
||||
): AppDraftSettings {
|
||||
const deployed = appDraftSettings(row)
|
||||
return {
|
||||
policy: parts.policy ? policySettings(parts.policy as Partial<Policy>) : deployed.policy,
|
||||
labels: parts.labels ?? deployed.labels
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { Globe, Link, PlugZap, ShieldCheck, Tag, UserCog, Users } from 'lucide-svelte'
|
||||
import type { Policy } from '$lib/gen'
|
||||
import type { ScriptSettingsBadge } from '$lib/components/scriptSettings'
|
||||
|
||||
/** The badges of an app's Metadata section. */
|
||||
export function getAppMetadataBadges(labels: string[] | undefined): ScriptSettingsBadge[] {
|
||||
return labels?.length
|
||||
? [
|
||||
{
|
||||
key: 'labels',
|
||||
short: 'Labels',
|
||||
setting: 'labels',
|
||||
label: 'Labels',
|
||||
icon: Tag,
|
||||
detail: labels.join(', ')
|
||||
}
|
||||
]
|
||||
: []
|
||||
}
|
||||
|
||||
/** The badges of an app's Permissions section. `sandboxed` also holds when the role forces it. */
|
||||
export function getAppPermissionBadges(
|
||||
policy: Pick<Policy, 'on_behalf_of' | 'on_behalf_of_email' | 'frontend_sdk_scopes'>,
|
||||
sandboxed: boolean
|
||||
): ScriptSettingsBadge[] {
|
||||
const badges: ScriptSettingsBadge[] = []
|
||||
const runsAs = policy.on_behalf_of ?? policy.on_behalf_of_email
|
||||
if (runsAs) {
|
||||
badges.push({
|
||||
key: 'on_behalf_of',
|
||||
short: 'On behalf',
|
||||
setting: 'on-behalf-of',
|
||||
label: 'Run on behalf of',
|
||||
icon: UserCog,
|
||||
detail: runsAs
|
||||
})
|
||||
}
|
||||
if (sandboxed) {
|
||||
badges.push({
|
||||
key: 'sandbox',
|
||||
short: 'Sandbox',
|
||||
setting: 'sandbox',
|
||||
label: 'Sandbox isolation',
|
||||
icon: ShieldCheck,
|
||||
detail: "The app's browser-side code gets a narrowly scoped token"
|
||||
})
|
||||
if (policy.frontend_sdk_scopes?.length) {
|
||||
badges.push({
|
||||
key: 'frontend_sdk_scopes',
|
||||
short: 'API access',
|
||||
setting: 'sandbox',
|
||||
label: 'Frontend API access',
|
||||
icon: PlugZap,
|
||||
detail: policy.frontend_sdk_scopes.join(', ')
|
||||
})
|
||||
}
|
||||
}
|
||||
return badges
|
||||
}
|
||||
|
||||
/** The badges of an app's Sharing section: who beyond members can open it, and its custom URL. */
|
||||
export function getAppSharingBadges(
|
||||
executionMode: Policy['execution_mode'],
|
||||
customPath: string | undefined
|
||||
): ScriptSettingsBadge[] {
|
||||
const badges: ScriptSettingsBadge[] = []
|
||||
if (executionMode === 'anonymous') {
|
||||
badges.push({
|
||||
key: 'access',
|
||||
short: 'Public',
|
||||
setting: 'access',
|
||||
label: 'Public',
|
||||
icon: Globe,
|
||||
detail: 'Anyone with the secret URL, no login'
|
||||
})
|
||||
} else if (executionMode === 'guest') {
|
||||
badges.push({
|
||||
key: 'access',
|
||||
short: 'Guests',
|
||||
setting: 'access',
|
||||
label: 'Guests',
|
||||
icon: Users,
|
||||
detail: 'Guests your identity provider authenticates, plus members'
|
||||
})
|
||||
}
|
||||
if (customPath) {
|
||||
badges.push({
|
||||
key: 'custom_path',
|
||||
short: 'Custom URL',
|
||||
setting: 'custom-url',
|
||||
label: 'Custom URL',
|
||||
icon: Link,
|
||||
detail: customPath
|
||||
})
|
||||
}
|
||||
return badges
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { AppService, type Policy } from '$lib/gen'
|
||||
|
||||
/** Writes who can open the app to the deployed app at once. The server applies the mode alone to
|
||||
* the deployed policy under the deploy's row lock: sandbox, SDK scopes and the run-as user wait
|
||||
* for a deploy, and a concurrent deploy neither reverts the mode nor is reverted by it. */
|
||||
export async function publishAccessMode(
|
||||
workspace: string,
|
||||
path: string,
|
||||
mode: NonNullable<Policy['execution_mode']>
|
||||
): Promise<void> {
|
||||
await AppService.updateApp({
|
||||
workspace,
|
||||
path,
|
||||
requestBody: {
|
||||
execution_mode: mode,
|
||||
// The clicker's draft holds edits this write does not deploy.
|
||||
skip_draft_deletion: true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** The policy an update deploy sends. The mode changes only through `publishAccessMode`, so an
|
||||
* update states none and the server keeps the deployed one, read under the row lock: a policy read
|
||||
* earlier would otherwise put back a mode changed since. */
|
||||
export function policyForUpdate<P extends Partial<Policy>>(policy: P): P {
|
||||
const sent = { ...policy }
|
||||
delete sent.execution_mode
|
||||
return sent
|
||||
}
|
||||
@@ -237,6 +237,14 @@ export type App = {
|
||||
* sends it as the summary on deploy.
|
||||
*/
|
||||
summary?: string
|
||||
/**
|
||||
* The app settings, persisted on the autosaved App like `summary` so an undeployed settings
|
||||
* change survives a reload and Review & Deploy deploys it. Draft-only: stripped from the
|
||||
* deployed value (`classicAppDraftParts`). `policy` holds only `policySettings`; deploy
|
||||
* recomputes the runnable whitelist and keeps the deployed access mode.
|
||||
*/
|
||||
policy?: Partial<Policy>
|
||||
labels?: string[]
|
||||
}
|
||||
|
||||
export type ConnectingInput = {
|
||||
|
||||
@@ -233,6 +233,9 @@ vi.mock('$lib/gen', async () => {
|
||||
getAppByVersion: vi.fn(async () => {
|
||||
throw new Error('getAppByVersion mock not configured')
|
||||
}),
|
||||
getAppLiteByPath: vi.fn(async () => {
|
||||
throw new Error('getAppLiteByPath mock not configured')
|
||||
}),
|
||||
listApps: vi.fn(async () => [])
|
||||
}),
|
||||
ResourceService: wrapService(actual.ResourceService, {
|
||||
@@ -4676,7 +4679,8 @@ describe('global AI tools', () => {
|
||||
data: { tables: ['orders'] }
|
||||
},
|
||||
summary: 'Updated report',
|
||||
policy: expect.objectContaining({ execution_mode: 'anonymous' }),
|
||||
// An update leaves the mode to the deployed row, so a stale draft can't revert it.
|
||||
policy: expect.not.objectContaining({ execution_mode: expect.anything() }),
|
||||
deployment_message: undefined
|
||||
},
|
||||
js: 'bundled js',
|
||||
@@ -4690,9 +4694,16 @@ describe('global AI tools', () => {
|
||||
// Deploying is what makes an app's runnables reachable, so it is the one moment the
|
||||
// exposure is both true and known.
|
||||
it('discloses who can open an app after a deploy', async () => {
|
||||
const deployApp = async (path: string, policy: Record<string, unknown>) => {
|
||||
const deployApp = async (
|
||||
path: string,
|
||||
policy: Record<string, unknown>,
|
||||
storedMode = policy.execution_mode
|
||||
) => {
|
||||
vi.mocked(AppService.existsApp).mockResolvedValueOnce(true)
|
||||
vi.mocked(AppService.getAppByPath).mockResolvedValueOnce({} as any)
|
||||
vi.mocked(AppService.getAppLiteByPath).mockResolvedValueOnce({
|
||||
policy: { execution_mode: storedMode }
|
||||
} as any)
|
||||
seedBackendDraft(
|
||||
'raw_app',
|
||||
path,
|
||||
@@ -4718,6 +4729,10 @@ describe('global AI tools', () => {
|
||||
// anyone outside the deployers group — so the note must not name an identity.
|
||||
expect(open.message).not.toContain('u/alice')
|
||||
|
||||
// An update keeps the deployed mode, so the note follows the stored row, not a stale draft.
|
||||
const keptPublic = await deployApp('f/apps/kept', { execution_mode: 'publisher' }, 'anonymous')
|
||||
expect(keptPublic.message).toContain('anyone with the URL, without logging in')
|
||||
|
||||
// Guest is a real widening only where the deployment admits guests; stored on one
|
||||
// that does not, it is inert and the note would announce an exposure that does not
|
||||
// exist.
|
||||
|
||||
@@ -90,6 +90,7 @@ import {
|
||||
formatDataTableRef
|
||||
} from '$lib/components/raw_apps/dataTableRefUtils'
|
||||
import { appSourceToDraftValue } from '$lib/components/raw_apps/rawAppDraftValue'
|
||||
import { policyForUpdate } from '$lib/components/apps/editor/publishAccessMode'
|
||||
import { conformBuilderAppPolicy } from '$lib/components/raw_apps/builderAppPolicy'
|
||||
import { capabilitiesInWorkspace } from '$lib/operatorWriteRights'
|
||||
import { capabilitiesIn, withoutBuilding } from '$lib/roleCapabilities'
|
||||
@@ -9623,27 +9624,6 @@ async function deployDraft(
|
||||
`not working until they are.`
|
||||
}
|
||||
|
||||
// `policy` is the mode being written, so the exposure is stated from the value in
|
||||
// hand. What a runnable runs as is the server's to decide, so the note names who
|
||||
// can reach the app and never an identity.
|
||||
if (policy.execution_mode === 'anonymous') {
|
||||
deployNote =
|
||||
`${deployNote ? `${deployNote} ` : ''}This app is deployed as anonymous: its ` +
|
||||
`backend runnables are now reachable by anyone with the URL, without logging in. ` +
|
||||
`Tell the user plainly what is now reachable and by whom.`
|
||||
} else if (policy.execution_mode === 'guest') {
|
||||
// Only where the guest door actually opens: below that, silence — a false note
|
||||
// is worse than none. The standing cap is a live count no read settles, so the
|
||||
// note says the door is open, not that every newcomer gets in.
|
||||
if (await guestAccessIsLive(workspace)) {
|
||||
deployNote =
|
||||
`${deployNote ? `${deployNote} ` : ''}This app is deployed as guest: anyone ` +
|
||||
`the instance's identity provider authenticates can now open it and run its ` +
|
||||
`backend runnables, member of this workspace or not. Tell the user plainly ` +
|
||||
`what is now reachable and by whom.`
|
||||
}
|
||||
}
|
||||
|
||||
toolCallbacks.setToolStatus(toolId, {
|
||||
content: `Bundling app "${path}"...`
|
||||
})
|
||||
@@ -9707,7 +9687,8 @@ async function deployDraft(
|
||||
}
|
||||
}
|
||||
deployedPath = targetPath
|
||||
if (await AppService.existsApp({ workspace, path: targetPath })) {
|
||||
const isUpdate = await AppService.existsApp({ workspace, path: targetPath })
|
||||
if (isUpdate) {
|
||||
// Omit custom_path on update for now. The backend preserves it when absent, while
|
||||
// sending it requires admin privileges; this chat deploy path does not yet mirror
|
||||
// the raw app editor's user/admin-specific custom_path handling.
|
||||
@@ -9719,7 +9700,8 @@ async function deployDraft(
|
||||
path: targetPath,
|
||||
value: rawAppValue,
|
||||
summary,
|
||||
policy,
|
||||
policy: policyForUpdate(policy),
|
||||
labels: appValue.labels,
|
||||
deployment_message: deploymentMessage,
|
||||
// Preserve the policy's on_behalf_of: this chat deploy path has no
|
||||
// on-behalf-of selector, so without the flag the backend resets it to
|
||||
@@ -9741,6 +9723,7 @@ async function deployDraft(
|
||||
policy,
|
||||
deployment_message: deploymentMessage,
|
||||
custom_path: appValue.custom_path,
|
||||
labels: appValue.labels,
|
||||
// Preserve the policy's on_behalf_of (see update branch above).
|
||||
preserve_on_behalf_of: policy.on_behalf_of ? true : undefined
|
||||
},
|
||||
@@ -9749,6 +9732,38 @@ async function deployDraft(
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// An update keeps the deployed mode, so the exposure is stated from the stored row,
|
||||
// never from the draft. What a runnable runs as is the server's to decide, so the
|
||||
// note names who can reach the app and never an identity.
|
||||
const storedMode = isUpdate
|
||||
? (
|
||||
await AppService.getAppLiteByPath({ workspace, path: targetPath }).catch(
|
||||
() => undefined
|
||||
)
|
||||
)?.policy?.execution_mode
|
||||
: policy.execution_mode
|
||||
if (storedMode === 'anonymous') {
|
||||
deployNote =
|
||||
`${deployNote ? `${deployNote} ` : ''}This app is deployed as anonymous: its ` +
|
||||
`backend runnables are now reachable by anyone with the URL, without logging in. ` +
|
||||
`Tell the user plainly what is now reachable and by whom.`
|
||||
} else if (storedMode === 'guest') {
|
||||
// Only where the guest door actually opens: below that, silence — a false note
|
||||
// is worse than none. The standing cap is a live count no read settles, so the
|
||||
// note says the door is open, not that every newcomer gets in.
|
||||
if (await guestAccessIsLive(workspace)) {
|
||||
deployNote =
|
||||
`${deployNote ? `${deployNote} ` : ''}This app is deployed as guest: anyone ` +
|
||||
`the instance's identity provider authenticates can now open it and run its ` +
|
||||
`backend runnables, member of this workspace or not. Tell the user plainly ` +
|
||||
`what is now reachable and by whom.`
|
||||
}
|
||||
} else if (storedMode === undefined) {
|
||||
deployNote =
|
||||
`${deployNote ? `${deployNote} ` : ''}Its access mode could not be read back ` +
|
||||
`after the deploy, so tell the user to check who can open the app.`
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,6 +68,7 @@ function normalizeAppDraftValue(value: AppDraftValue): AppDraftValue {
|
||||
data: value.data ?? { ...DEFAULT_RAW_APP_DATA },
|
||||
policy: value.policy === undefined ? undefined : clone(value.policy),
|
||||
custom_path: value.custom_path,
|
||||
labels: value.labels,
|
||||
// Carry the fork-base version through the whitelist — it is dropped on every
|
||||
// save otherwise, which would defeat the stale-draft check.
|
||||
parent_version: value.parent_version,
|
||||
|
||||
@@ -78,6 +78,7 @@ export type AppDraftValue = {
|
||||
data?: any
|
||||
policy?: Policy
|
||||
custom_path?: string
|
||||
labels?: string[]
|
||||
// Fork base: the deployed app version this draft was started from, pinned at
|
||||
// fork. The app analog of a script's parent_hash / a flow's version_id.
|
||||
parent_version?: number
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
type OnBehalfOfChoice
|
||||
} from '$lib/components/OnBehalfOfSelector.svelte'
|
||||
import { useOperatingUser } from '$lib/components/operatingWorkspace.svelte'
|
||||
import { useRoleCapabilities } from '$lib/operatorWriteRights'
|
||||
import { AlertTriangle } from 'lucide-svelte'
|
||||
import SettingToggle from './SettingToggle.svelte'
|
||||
import { canPreserveOnBehalfOf, deployedPermissionedAs, WM_DEPLOYERS_GROUP } from './onBehalfOf'
|
||||
@@ -60,7 +61,11 @@
|
||||
|
||||
const operatingUser = useOperatingUser()
|
||||
const actingUser = $derived(operatingUser.current)
|
||||
let canPreserve = $derived(canPreserveOnBehalfOf(actingUser))
|
||||
const roleCaps = useRoleCapabilities()
|
||||
// A builder's app draft may name no other user (docs/operator-builder-rights.md), so their editor
|
||||
// drops the deployed one and the deploy stores them, `wm_deployers` or not.
|
||||
let composesApp = $derived(kind === 'app' && $roleCaps.apps === 'compose')
|
||||
let canPreserve = $derived(canPreserveOnBehalfOf(actingUser) && !composesApp)
|
||||
// "Me" is the acting user in the target workspace, its username and its email alike: usernames
|
||||
// are per-workspace, and the backend rejects a pair that names two accounts.
|
||||
let myPermissionedAs = $derived(actingUser?.username ? `u/${actingUser.username}` : undefined)
|
||||
@@ -69,9 +74,9 @@
|
||||
// opens, and a choice that restarts empty lets the selector reselect the deployed user over
|
||||
// the one picked.
|
||||
let choice: OnBehalfOfChoice = $derived.by(() => {
|
||||
// No user picked deploys the folder default, even over a deployed user: a script renamed
|
||||
// into the folder is created at its new path.
|
||||
if (!permissionedAs && !email && folderDefault) return 'custom'
|
||||
// No user held deploys the folder default, even over a deployed user: a script renamed
|
||||
// into the folder is created at its new path. Outside one, it deploys the deployer.
|
||||
if (!permissionedAs && !email) return folderDefault ? 'custom' : 'me'
|
||||
const keepsSaved = savedPermissionedAs
|
||||
? (permissionedAs ?? savedPermissionedAs) === savedPermissionedAs
|
||||
: !!savedEmail && (email ?? savedEmail) === savedEmail
|
||||
@@ -140,7 +145,11 @@
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
{#if !canPreserve}
|
||||
{#if composesApp}
|
||||
<div class="text-2xs text-secondary">
|
||||
Apps you build run on behalf of you once you deploy them.
|
||||
</div>
|
||||
{:else if !canPreserve}
|
||||
<div class="text-2xs text-secondary">
|
||||
Only workspace admins and members of {WM_DEPLOYERS_GROUP} can pick another user.
|
||||
</div>
|
||||
|
||||
@@ -15,7 +15,7 @@ describe('onBehalfOf', () => {
|
||||
expect(deployedPermissionedAs(member, 'u/bot', 'u/folder')).toBe('u/alice')
|
||||
})
|
||||
|
||||
it('asks on every app deploy, and on flow or script deploys that change the run-as user', () => {
|
||||
it('asks on a first deploy, and on deploys that change the run-as user', () => {
|
||||
const none = {
|
||||
email: undefined,
|
||||
permissionedAs: undefined,
|
||||
@@ -25,8 +25,11 @@ describe('onBehalfOf', () => {
|
||||
const bot = { email: 'bot@x.dev', permissionedAs: 'u/bot' }
|
||||
const deployedAsBot = { savedEmail: 'bot@x.dev', savedPermissionedAs: 'u/bot' }
|
||||
|
||||
expect(deployAsksOnBehalfOf('app', { user: admin, ...none })).toBe(true)
|
||||
expect(deployAsksOnBehalfOf('flow', { user: admin, ...none })).toBe(false)
|
||||
// An app runs on behalf of someone from its first deploy.
|
||||
expect(deployAsksOnBehalfOf('app', { user: admin, ...none })).toBe(true)
|
||||
expect(deployAsksOnBehalfOf('app', { user: admin, ...bot, ...deployedAsBot })).toBe(false)
|
||||
expect(deployAsksOnBehalfOf('app', { user: member, ...bot, ...deployedAsBot })).toBe(true)
|
||||
// A first deploy, or one that turns it on.
|
||||
expect(deployAsksOnBehalfOf('script', { user: admin, ...none, ...bot })).toBe(true)
|
||||
expect(deployAsksOnBehalfOf('flow', { user: admin, ...none, folderDefault: 'u/f' })).toBe(true)
|
||||
|
||||
@@ -34,10 +34,10 @@ export function deployedPermissionedAs(
|
||||
return user?.username ? `u/${user.username}` : undefined
|
||||
}
|
||||
|
||||
/** Whether a deploy asks first whose access the item will run with. Every app deploy asks, since
|
||||
* all its viewers use that access. A flow or script deploy asks when it starts running on behalf
|
||||
* of someone, changes who, or stops: a deploy that keeps the deployed user has nothing new to
|
||||
* confirm. `saved*` are the deployed version's, unset before the first deploy. */
|
||||
/** Whether a deploy asks first whose access the item will run with. A deploy asks when the item
|
||||
* starts running on behalf of someone, changes who, or stops: a deploy that keeps the deployed
|
||||
* user has nothing new to confirm. An app always runs on behalf of someone, so its first deploy
|
||||
* always asks. `saved*` are the deployed version's, unset before the first deploy. */
|
||||
export function deployAsksOnBehalfOf(
|
||||
kind: 'flow' | 'script' | 'app',
|
||||
deploy: {
|
||||
@@ -49,9 +49,8 @@ export function deployAsksOnBehalfOf(
|
||||
folderDefault?: string
|
||||
}
|
||||
): boolean {
|
||||
if (kind === 'app') return true
|
||||
const deployedHoldsUser = !!(deploy.savedPermissionedAs ?? deploy.savedEmail)
|
||||
if (!deploy.email && !deploy.folderDefault) return deployedHoldsUser
|
||||
if (kind !== 'app' && !deploy.email && !deploy.folderDefault) return deployedHoldsUser
|
||||
if (!deployedHoldsUser) return true
|
||||
return (
|
||||
deployedPermissionedAs(deploy.user, deploy.permissionedAs, deploy.folderDefault) !==
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { AppService, FlowService, ScriptService, type UserDraftItemKind } from '$lib/gen'
|
||||
import type { Value } from '$lib/utils'
|
||||
import { DEFAULT_DATA, extractDataConfig } from '$lib/components/raw_apps/dataTableRefUtils'
|
||||
import { appDraftSettings } from '$lib/components/apps/editor/appDraftSettings'
|
||||
|
||||
/**
|
||||
* Fetch the currently-deployed value for an item, in the same shape its draft
|
||||
* is stored — so it can be the "original" side of a draft-vs-deployed diff.
|
||||
* App drafts hold the bare `App` value (unwrap `.value`); raw-app drafts hold a
|
||||
* App drafts hold the bare `App` value with the row's metadata mirrored on; raw-app drafts hold a
|
||||
* flat bundle (`files`/`runnables`/`data`/`summary`/`policy`/`custom_path`),
|
||||
* with `summary`/`policy`/`custom_path` living OUTSIDE `.value` on the deployed
|
||||
* row — so we project the deployed app into that bundle (via the same
|
||||
@@ -26,9 +27,15 @@ export async function fetchDeployedValueForDiff(
|
||||
})) as unknown as Value
|
||||
case 'flow':
|
||||
return (await FlowService.getFlowByPath({ workspace, path })) as unknown as Value
|
||||
case 'app':
|
||||
return (await AppService.getAppByPath({ workspace, path, getDraft: false }))
|
||||
.value as unknown as Value
|
||||
case 'app': {
|
||||
// The editor mirrors the summary and settings onto the bare App it drafts.
|
||||
const app = await AppService.getAppByPath({ workspace, path, getDraft: false })
|
||||
return {
|
||||
...(app.value as object),
|
||||
summary: app.summary,
|
||||
...appDraftSettings(app)
|
||||
} as unknown as Value
|
||||
}
|
||||
case 'raw_app': {
|
||||
const app = await AppService.getAppByPath({ workspace, path, getDraft: false })
|
||||
const v = (app.value ?? {}) as any
|
||||
|
||||
@@ -170,6 +170,8 @@
|
||||
/** User-typed path when it differs from `savedApp.path`. The route injects
|
||||
* it as `draft_path` so the home row shows the friendly name, not `draft_{uuid}`. */
|
||||
pendingDraftPath?: string | undefined
|
||||
/** The labels being edited, for the route's autosaved draft. */
|
||||
pendingDraftSettings?: { labels: string[] } | undefined
|
||||
// Threaded to the AutosaveIndicator's "Reset to deployed" button.
|
||||
/** `Exit & see details`: see RawAppEditorHeader. */
|
||||
onDetails?: (e: { path: string }) => void
|
||||
@@ -228,7 +230,7 @@
|
||||
runnables = $bindable({}),
|
||||
data = $bindable(DEFAULT_DATA),
|
||||
newApp,
|
||||
policy,
|
||||
policy = $bindable(),
|
||||
summary = $bindable(''),
|
||||
path,
|
||||
newPath = undefined,
|
||||
@@ -245,6 +247,7 @@
|
||||
defaultSplitWithPreview = true,
|
||||
compact = false,
|
||||
pendingDraftPath = $bindable(undefined),
|
||||
pendingDraftSettings = $bindable(),
|
||||
onDetails,
|
||||
onOpenFork,
|
||||
onResetToDeployed,
|
||||
@@ -2696,6 +2699,7 @@ addEventListener('message', function (e) {
|
||||
bind:savedApp
|
||||
bind:summary
|
||||
bind:pendingDraftPath
|
||||
bind:pendingDraftSettings
|
||||
{version}
|
||||
{onTakeLatest}
|
||||
{draftBaseVersion}
|
||||
@@ -2706,7 +2710,7 @@ addEventListener('message', function (e) {
|
||||
}
|
||||
onSavedNewAppPath?.(newAppPath)
|
||||
}}
|
||||
{policy}
|
||||
bind:policy
|
||||
{diffDrawer}
|
||||
{newApp}
|
||||
{newPath}
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
<script lang="ts">
|
||||
import { deployAsksOnBehalfOf } from '$lib/components/itemSettings/onBehalfOf'
|
||||
import {
|
||||
fetchDeployedAccessMode,
|
||||
fetchDeployedRunAs,
|
||||
setDeployedOnBehalfOf
|
||||
} from '$lib/components/apps/editor/appDeploy.svelte'
|
||||
import DeployOnBehalfOfDialog from '$lib/components/itemSettings/DeployOnBehalfOfDialog.svelte'
|
||||
import { useFolderDefaultPermissionedAs } from '$lib/components/useFolderDefaultPermissionedAs.svelte'
|
||||
import { Drawer, DrawerContent } from '$lib/components/common'
|
||||
import RawAppRecordSession from '$lib/components/workspaceSettings/RawAppRecordSession.svelte'
|
||||
import Button from '$lib/components/common/button/Button.svelte'
|
||||
@@ -19,11 +27,12 @@
|
||||
EllipsisVertical,
|
||||
FileJson,
|
||||
Circle,
|
||||
Globe,
|
||||
History,
|
||||
PanelLeft,
|
||||
PanelLeftClose,
|
||||
Redo,
|
||||
Save,
|
||||
Settings,
|
||||
Undo,
|
||||
WandSparkles
|
||||
} from 'lucide-svelte'
|
||||
@@ -48,9 +57,11 @@
|
||||
import AppJobsDrawer from '../apps/editor/AppJobsDrawer.svelte'
|
||||
import DropdownV2 from '../DropdownV2.svelte'
|
||||
import { stateSnapshot } from '$lib/svelte5Utils.svelte'
|
||||
import AppEditorHeaderDeploy from '../apps/editor/AppEditorHeaderDeploy.svelte'
|
||||
import AppSettingsDrawer from '../apps/editor/AppSettingsDrawer.svelte'
|
||||
import DeployButton from '$lib/components/DeployButton.svelte'
|
||||
import type { Runnable } from './RawAppInlineScriptRunnable.svelte'
|
||||
import { updateRawAppPolicy } from './rawAppPolicy'
|
||||
import { policyForUpdate, publishAccessMode } from '$lib/components/apps/editor/publishAccessMode'
|
||||
import { saveRawAppFork } from './forkRawApp.svelte'
|
||||
import { aiChatManager } from '../copilot/chat/AIChatManager.svelte'
|
||||
import { getContext } from 'svelte'
|
||||
@@ -184,6 +195,8 @@
|
||||
* draft as `draft_path` so the home-page row can render the
|
||||
* friendly name instead of the URL's autogenerated draft slot. */
|
||||
pendingDraftPath?: string | undefined
|
||||
/** The labels being edited, which the route writes into the autosaved draft. */
|
||||
pendingDraftSettings?: { labels: string[] } | undefined
|
||||
// Threaded to the `AutosaveIndicator` popover so its "Reset to
|
||||
// deployed" button can do the same thing the load-time toast offers.
|
||||
/** `Exit & see details`: leaves the editor for the app's deployed page. A session hosts that
|
||||
@@ -210,7 +223,7 @@
|
||||
|
||||
let {
|
||||
summary = $bindable(),
|
||||
policy,
|
||||
policy = $bindable(),
|
||||
diffDrawer = undefined,
|
||||
savedApp = $bindable(undefined),
|
||||
version = $bindable(undefined),
|
||||
@@ -242,6 +255,7 @@
|
||||
autosavePath = undefined,
|
||||
onDeploy = undefined,
|
||||
pendingDraftPath = $bindable(undefined),
|
||||
pendingDraftSettings = $bindable(),
|
||||
onDetails,
|
||||
onOpenFork,
|
||||
onResetToDeployed,
|
||||
@@ -252,10 +266,15 @@
|
||||
onSavedNewAppPath
|
||||
}: Props = $props()
|
||||
|
||||
// Set by the on-behalf-of selector when the publisher picks a user other than
|
||||
// themselves. Forwarded as `preserve_on_behalf_of` so the backend keeps the
|
||||
// policy's on_behalf_of instead of resetting it to the deploying user.
|
||||
let preserveOnBehalfOf = $state(false)
|
||||
const isNewApp = $derived(newApp || appPath == '')
|
||||
// Only the app's first deploy takes the folder's default user.
|
||||
const folderDefault = useFolderDefaultPermissionedAs(
|
||||
() => (isNewApp ? newEditedPath : undefined),
|
||||
() => opWorkspace
|
||||
)
|
||||
let deployDialogOpen = $state(false)
|
||||
let deployButton: DeployButton | undefined = $state(undefined)
|
||||
let deployedRunAs: Awaited<ReturnType<typeof fetchDeployedRunAs>> = $state()
|
||||
|
||||
// The AutosaveIndicator watches these; in the sessions preview they're the
|
||||
// session's (workspace, path), else the full-page editor's own values.
|
||||
@@ -280,8 +299,10 @@
|
||||
$effect(() => {
|
||||
const typed = newEditedPath
|
||||
const baseline = savedApp?.path ?? ''
|
||||
const settings = { labels: $state.snapshot(labels) ?? [] }
|
||||
untrack(() => {
|
||||
pendingDraftPath = typed && typed !== baseline ? typed : undefined
|
||||
pendingDraftSettings = settings
|
||||
})
|
||||
})
|
||||
|
||||
@@ -331,7 +352,9 @@
|
||||
let pathError: string = $state('')
|
||||
let appExport = $state() as AppExportButton | undefined
|
||||
|
||||
let saveDrawerOpen = $state(false)
|
||||
let settingsOpen = $state(false)
|
||||
let settingsDrawer: AppSettingsDrawer | undefined = $state()
|
||||
let deployRefused = $state(false)
|
||||
let historyBrowserDrawerOpen = $state(false)
|
||||
let recordDrawer = $state<Drawer | undefined>(undefined)
|
||||
let deploymentMsg: string | undefined = $state(undefined)
|
||||
@@ -371,18 +394,24 @@
|
||||
// workspace in, so it has to travel with them: OpenInSessionButton asks who the acting user is.
|
||||
const headerContexts = new Map<any, any>([operatingWorkspaceContextEntry()])
|
||||
|
||||
function closeSaveDrawer() {
|
||||
saveDrawerOpen = false
|
||||
}
|
||||
|
||||
// Returns a copy: `policy` is the editor's own object, which the Deploy panel's
|
||||
// instant toggles mutate in place. Reassigning it would detach the panel from the
|
||||
// Returns a copy: `policy` is the editor's own object, which the settings drawer's
|
||||
// toggles mutate in place. Reassigning it would detach the drawer from the
|
||||
// editor, so later toggles would never reach the preview. After a successful save,
|
||||
// copy only `triggerables_v2` back so the editor's value matches what was deployed.
|
||||
function policyWithTriggerables() {
|
||||
return updateRawAppPolicy(runnables, policy)
|
||||
}
|
||||
|
||||
async function setAccessMode(mode: NonNullable<Policy['execution_mode']>) {
|
||||
await publishAccessMode(opWorkspace!, appPath, mode)
|
||||
if (savedApp) savedApp.policy = { ...savedApp.policy, execution_mode: mode }
|
||||
sendUserToast(
|
||||
mode == 'anonymous'
|
||||
? 'App require no login to be accessed'
|
||||
: 'App require login and read-access'
|
||||
)
|
||||
}
|
||||
|
||||
async function createApp(path: string) {
|
||||
if (!app) {
|
||||
sendUserToast(`App hasn't been loaded yet`, true)
|
||||
@@ -391,6 +420,7 @@
|
||||
if (!policy.execution_mode) {
|
||||
policy.execution_mode = 'publisher'
|
||||
}
|
||||
setDeployedOnBehalfOf(policy, actingUser, folderDefault.value)
|
||||
try {
|
||||
const { js, css } = await getBundle()
|
||||
const deployedPolicy = await policyWithTriggerables()
|
||||
@@ -404,7 +434,9 @@
|
||||
policy: deployedPolicy,
|
||||
deployment_message: deploymentMsg,
|
||||
custom_path: customPath,
|
||||
preserve_on_behalf_of: preserveOnBehalfOf || undefined,
|
||||
// The user the deploy dialog confirmed, which the backend keeps only for a
|
||||
// deployer who may preserve one.
|
||||
preserve_on_behalf_of: true,
|
||||
labels
|
||||
},
|
||||
js,
|
||||
@@ -423,8 +455,8 @@
|
||||
custom_path: customPath,
|
||||
labels: $state.snapshot(labels)
|
||||
}
|
||||
closeSaveDrawer()
|
||||
sendUserToast('App deployed successfully')
|
||||
deployButton?.clearMessage()
|
||||
// Canonical autosave key (the URL slot `appPath`), NOT the
|
||||
// just-typed deploy `path` — for a draft-only app they differ
|
||||
// (`u/{user}/draft_{uuid}` vs the chosen path), so removing at
|
||||
@@ -622,6 +654,7 @@
|
||||
if (!policy.execution_mode) {
|
||||
policy.execution_mode = 'publisher'
|
||||
}
|
||||
setDeployedOnBehalfOf(policy, actingUser)
|
||||
const deployedPolicy = await policyWithTriggerables()
|
||||
const deployed = await AppService.updateAppRaw({
|
||||
workspace: opWorkspace!,
|
||||
@@ -630,10 +663,10 @@
|
||||
app: {
|
||||
value: app!,
|
||||
summary: summary,
|
||||
policy: deployedPolicy,
|
||||
policy: policyForUpdate(deployedPolicy),
|
||||
path: npath,
|
||||
deployment_message: deploymentMsg,
|
||||
preserve_on_behalf_of: preserveOnBehalfOf || undefined,
|
||||
preserve_on_behalf_of: true,
|
||||
// custom_path requires admin so to accept update without it, we need to send as undefined when non-admin (when undefined, it will be ignored)
|
||||
// it also means that customPath needs to be set to '' instead of undefined to unset it (when admin)
|
||||
custom_path:
|
||||
@@ -646,6 +679,8 @@
|
||||
})
|
||||
policy.triggerables_v2 = deployedPolicy.triggerables_v2
|
||||
invalidateWorkspacePaths(opWorkspace!)
|
||||
const accessMode = await fetchDeployedAccessMode(opWorkspace!, npath)
|
||||
if (accessMode) policy.execution_mode = deployedPolicy.execution_mode = accessMode
|
||||
savedApp = {
|
||||
summary: summary,
|
||||
value: structuredClone(stateSnapshot(app)),
|
||||
@@ -663,8 +698,8 @@
|
||||
// owns this prop and re-pushes `parentVersion ?? head` as soon as `onDeploy` returns.
|
||||
version = head?.version
|
||||
|
||||
closeSaveDrawer()
|
||||
sendUserToast('App deployed successfully')
|
||||
deployButton?.clearMessage()
|
||||
// Bracketed + flushed (see createApp).
|
||||
if (!inSessionPane && $operatingWorkspace) {
|
||||
discardDraftAfterDeploy({
|
||||
@@ -685,26 +720,46 @@
|
||||
})
|
||||
}
|
||||
|
||||
async function setPublishState(message?: string) {
|
||||
const nextPolicy = await policyWithTriggerables()
|
||||
await AppService.updateApp({
|
||||
workspace: opWorkspace!,
|
||||
path: appPath,
|
||||
requestBody: { policy: nextPolicy }
|
||||
})
|
||||
policy.triggerables_v2 = nextPolicy.triggerables_v2
|
||||
if (message) {
|
||||
sendUserToast(message)
|
||||
} else if (policy.execution_mode == 'anonymous') {
|
||||
sendUserToast('App require no login to be accessed')
|
||||
} else {
|
||||
sendUserToast('App require login and read-access')
|
||||
}
|
||||
function openSettings(setting?: string) {
|
||||
settingsDrawer?.openAt(setting)
|
||||
}
|
||||
|
||||
async function save() {
|
||||
saveDrawerOpen = true
|
||||
return
|
||||
async function deploy(message?: string) {
|
||||
if (app == undefined) return
|
||||
if (pathError != '' || customPathError != '') {
|
||||
deployRefused = true
|
||||
openSettings(pathError != '' ? undefined : 'custom-url')
|
||||
return
|
||||
}
|
||||
deploymentMsg = message
|
||||
// Compares against the user deployed right now; a failed lookup asks rather than trusting
|
||||
// the loaded one.
|
||||
deployedRunAs = isNewApp ? undefined : await fetchDeployedRunAs(opWorkspace!, appPath)
|
||||
if (
|
||||
(!isNewApp && !deployedRunAs) ||
|
||||
// Asks while the folder default is loading: the backend would apply it unconfirmed.
|
||||
folderDefault.loading ||
|
||||
deployAsksOnBehalfOf('app', {
|
||||
user: actingUser,
|
||||
email: policy.on_behalf_of_email,
|
||||
permissionedAs: policy.on_behalf_of,
|
||||
savedEmail: deployedRunAs?.on_behalf_of_email,
|
||||
savedPermissionedAs: deployedRunAs?.on_behalf_of,
|
||||
folderDefault: folderDefault.value
|
||||
})
|
||||
) {
|
||||
deployDialogOpen = true
|
||||
return
|
||||
}
|
||||
await deployNow()
|
||||
}
|
||||
|
||||
async function deployNow() {
|
||||
if (isNewApp) {
|
||||
await createApp(newEditedPath)
|
||||
} else {
|
||||
await handleUpdateApp(newEditedPath)
|
||||
}
|
||||
}
|
||||
|
||||
let onLatest = $state(true)
|
||||
@@ -788,6 +843,16 @@
|
||||
},
|
||||
disabled: !savedApp
|
||||
},
|
||||
{
|
||||
displayName: 'Settings',
|
||||
icon: Settings,
|
||||
action: () => openSettings()
|
||||
},
|
||||
{
|
||||
displayName: 'Public URL',
|
||||
icon: Globe,
|
||||
action: () => openSettings('access')
|
||||
},
|
||||
{
|
||||
displayName: 'Export',
|
||||
icon: FileJson,
|
||||
@@ -810,9 +875,11 @@
|
||||
}
|
||||
])
|
||||
|
||||
// Derived, so a draft synced in from another session reaches the header; an edit here overrides
|
||||
// the value until the next one arrives.
|
||||
let customPath = $state(savedApp?.custom_path)
|
||||
let customPathError = $state('')
|
||||
let labels = $state(untrack(() => initialLabels))
|
||||
let labels = $derived(initialLabels)
|
||||
|
||||
let jobsDrawerOpen = $state(false)
|
||||
|
||||
@@ -831,11 +898,26 @@
|
||||
})
|
||||
)
|
||||
|
||||
$effect(() => {
|
||||
saveDrawerOpen && compareVersions()
|
||||
})
|
||||
let settingsHaveErrors = $derived(pathError != '' || customPathError != '')
|
||||
</script>
|
||||
|
||||
<DeployOnBehalfOfDialog
|
||||
kind="app"
|
||||
bind:open={deployDialogOpen}
|
||||
bind:message={() => deploymentMsg ?? '', (v) => (deploymentMsg = v)}
|
||||
bind:email={policy.on_behalf_of_email}
|
||||
bind:permissionedAs={policy.on_behalf_of}
|
||||
savedEmail={isNewApp ? undefined : deployedRunAs?.on_behalf_of_email}
|
||||
savedPermissionedAs={isNewApp ? undefined : deployedRunAs?.on_behalf_of}
|
||||
isNew={isNewApp}
|
||||
folderDefault={folderDefault.value}
|
||||
folderDefaultLoading={folderDefault.loading}
|
||||
executionMode={policy.execution_mode}
|
||||
targetWorkspace={opWorkspace ?? ''}
|
||||
rawApp
|
||||
onConfirmed={deployNow}
|
||||
/>
|
||||
|
||||
<DeployOverrideConfirmationModal
|
||||
{deployedBy}
|
||||
{confirmCallback}
|
||||
@@ -847,95 +929,25 @@
|
||||
currentValue={currentDiffValue}
|
||||
/>
|
||||
|
||||
<Drawer bind:open={saveDrawerOpen} size="800px">
|
||||
<DrawerContent title="Deploy" on:close={() => closeSaveDrawer()}>
|
||||
{#snippet actions()}
|
||||
<div class="flex flex-row gap-2">
|
||||
<Button
|
||||
variant="default"
|
||||
disabled={!savedApp || newApp}
|
||||
on:click={async () => {
|
||||
if (!savedApp || newApp) {
|
||||
return
|
||||
}
|
||||
// The other entry point into the same drawer, so it takes an opening too.
|
||||
const opening = diffDrawer?.beginOpening()
|
||||
lastOpening = opening
|
||||
if (opening == null) return
|
||||
// deployedValue should be syncronized when we open Diff
|
||||
await syncWithDeployed(opening)
|
||||
|
||||
if (!diffDrawer?.ownsOpening(opening)) return
|
||||
saveDrawerOpen = false
|
||||
diffDrawer.openDrawer(opening)
|
||||
diffDrawer.setDiff(
|
||||
{
|
||||
mode: 'normal',
|
||||
deployed: deployedValue ?? stripRawAppDiffNoise(savedApp),
|
||||
current: currentDiffValue,
|
||||
aiReview: opWorkspace
|
||||
? { workspaceId: opWorkspace, kind: 'raw_app', path: appPath }
|
||||
: undefined,
|
||||
button: {
|
||||
text: 'Looks good, deploy',
|
||||
onClick: () => {
|
||||
if (newApp || appPath == '') {
|
||||
createApp(newEditedPath)
|
||||
} else {
|
||||
handleUpdateApp(newEditedPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
opening
|
||||
)
|
||||
}}
|
||||
>
|
||||
<div class="flex flex-row gap-2 items-center">
|
||||
<DiffIcon size={14} />
|
||||
Diff
|
||||
</div>
|
||||
</Button>
|
||||
<Button
|
||||
variant="accent"
|
||||
unifiedSize="md"
|
||||
startIcon={{ icon: Save }}
|
||||
disabled={pathError != '' || customPathError != '' || app == undefined}
|
||||
on:click={() => {
|
||||
if (newApp || appPath == '') {
|
||||
createApp(newEditedPath)
|
||||
} else {
|
||||
handleUpdateApp(newEditedPath)
|
||||
}
|
||||
}}
|
||||
>
|
||||
Deploy
|
||||
</Button>
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
<AppEditorHeaderDeploy
|
||||
{newPath}
|
||||
{newApp}
|
||||
{policy}
|
||||
{setPublishState}
|
||||
{appPath}
|
||||
{onLatest}
|
||||
{headUnknown}
|
||||
{savedApp}
|
||||
rawApp
|
||||
operatingWorkspace={opWorkspace}
|
||||
bind:summary
|
||||
bind:customPath
|
||||
bind:deploymentMsg
|
||||
bind:customPathError
|
||||
bind:pathError
|
||||
bind:newEditedPath
|
||||
bind:preserveOnBehalfOf
|
||||
bind:labels
|
||||
/>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
<AppSettingsDrawer
|
||||
bind:this={settingsDrawer}
|
||||
bind:open={settingsOpen}
|
||||
{newPath}
|
||||
{newApp}
|
||||
bind:policy
|
||||
{appPath}
|
||||
{savedApp}
|
||||
rawApp
|
||||
operatingWorkspace={opWorkspace}
|
||||
bind:summary
|
||||
bind:customPath
|
||||
bind:customPathError
|
||||
bind:pathError
|
||||
bind:newEditedPath
|
||||
bind:labels
|
||||
showErrors={deployRefused}
|
||||
{setAccessMode}
|
||||
/>
|
||||
|
||||
<Drawer bind:open={historyBrowserDrawerOpen} size="1200px">
|
||||
<DrawerContent title="Deployment History" on:close={() => (historyBrowserDrawerOpen = false)}>
|
||||
@@ -1183,6 +1195,25 @@
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{#if !phoneTopbar}
|
||||
<div class="relative shrink-0">
|
||||
{#if settingsHaveErrors}
|
||||
<span class="absolute inline-flex rounded-full bg-red-600 h-2 w-2 z-50 -right-0.5 -top-0.5"
|
||||
></span>
|
||||
{/if}
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize={headerBtnSize}
|
||||
startIcon={{ icon: Settings }}
|
||||
iconOnly={compactTopbar}
|
||||
title="Settings"
|
||||
on:click={() => openSettings()}
|
||||
>
|
||||
Settings
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="{compactTopbar ? 'hidden' : 'hidden md:inline'} relative overflow-visible">
|
||||
<Button
|
||||
on:click={() => {
|
||||
@@ -1222,12 +1253,12 @@
|
||||
{/if}
|
||||
{/snippet}
|
||||
</OpenInSessionButton>
|
||||
<Button
|
||||
loading={loading.save}
|
||||
startIcon={{ icon: Save }}
|
||||
on:click={save}
|
||||
<DeployButton
|
||||
bind:this={deployButton}
|
||||
loadingSave={loading.save}
|
||||
loading={app == undefined}
|
||||
on:save={({ detail }) => deploy(detail)}
|
||||
unifiedSize={headerBtnSize}
|
||||
variant="accent"
|
||||
dropdownItems={appPath != ''
|
||||
? () => [
|
||||
// `appPath`, not the live edited path: a rename that has not been deployed yet
|
||||
@@ -1256,7 +1287,5 @@
|
||||
: [])
|
||||
]
|
||||
: undefined}
|
||||
>
|
||||
Deploy
|
||||
</Button>
|
||||
/>
|
||||
{/snippet}
|
||||
|
||||
@@ -293,11 +293,8 @@
|
||||
)
|
||||
|
||||
function appPolicy(): Policy {
|
||||
// No run-as user: the deploy dialog resolves it, the folder's default first.
|
||||
const policy: Policy = {
|
||||
on_behalf_of: $userStore?.username.includes('@')
|
||||
? $userStore?.username
|
||||
: `u/${$userStore?.username}`,
|
||||
on_behalf_of_email: $userStore?.email,
|
||||
execution_mode: 'publisher',
|
||||
sandbox: true
|
||||
}
|
||||
|
||||
@@ -48,6 +48,7 @@ export function appSourceToDraftValue(app: any, fallback?: any): AppDraftValue {
|
||||
data: normalizeRawAppData(value),
|
||||
policy: app.policy ?? fallback?.policy,
|
||||
custom_path: app.custom_path ?? fallback?.custom_path,
|
||||
labels: app.labels ?? fallback?.labels,
|
||||
// Pin the fork base: a deployed app exposes `versions` (head = last); an
|
||||
// existing draft already carries `parent_version` — preserve it.
|
||||
parent_version:
|
||||
|
||||
@@ -375,11 +375,21 @@
|
||||
bind:data={cell.store.val.data}
|
||||
bind:summary={cell.store.val.summary}
|
||||
bind:pendingDraftPath
|
||||
bind:pendingDraftSettings={
|
||||
() => undefined,
|
||||
(s: { labels: string[] } | undefined) => {
|
||||
// The header reports its labels on mount too: only a change reaches the draft.
|
||||
const v = cell.store.val
|
||||
if (!s || !v) return
|
||||
if ((v.labels ?? []).join('\n') !== s.labels.join('\n')) v.labels = s.labels
|
||||
}
|
||||
}
|
||||
labels={cell.store.val.labels}
|
||||
newPath={cell.store.val.draft_path ?? cell.store.val.path}
|
||||
{path}
|
||||
autosaveWorkspace={workspaceId}
|
||||
autosavePath={path}
|
||||
policy={cell.store.val.policy}
|
||||
bind:policy={cell.store.val.policy}
|
||||
bind:savedApp={cell.saved.val}
|
||||
version={cell.store.val?.parent_version ?? cell.saved.val?.deployed_version}
|
||||
draftBaseVersion={cell.store.val?.parent_version != null
|
||||
|
||||
@@ -11,6 +11,7 @@ export type RawAppDraft = {
|
||||
summary: string
|
||||
policy?: any
|
||||
custom_path?: string
|
||||
labels?: string[]
|
||||
// User-typed path while the app is parked at a `…/draft_<uuid>` storage path.
|
||||
// Must round-trip through the draft so the home/review/Drafts lists render the
|
||||
// friendly name (they read `value->>'draft_path'`) — and so editing the path
|
||||
@@ -32,6 +33,7 @@ export type RuntimeRawApp = {
|
||||
data: RawAppData
|
||||
policy: any
|
||||
custom_path?: string
|
||||
labels?: string[]
|
||||
draft_path?: string
|
||||
parent_version?: number
|
||||
}
|
||||
@@ -47,6 +49,7 @@ export function runtimeRawAppToDraft(raw: RuntimeRawApp): RawAppDraft {
|
||||
data: raw.data,
|
||||
policy: raw.policy,
|
||||
custom_path: raw.custom_path,
|
||||
labels: raw.labels,
|
||||
draft_path: raw.draft_path,
|
||||
parent_version: raw.parent_version
|
||||
}
|
||||
@@ -63,6 +66,7 @@ export function applyDraftToRuntimeRawApp(raw: RuntimeRawApp, dv: RawAppDraft):
|
||||
data: dv.data,
|
||||
policy: dv.policy ?? raw.policy,
|
||||
custom_path: dv.custom_path ?? raw.custom_path,
|
||||
labels: dv.labels ?? raw.labels,
|
||||
draft_path: dv.draft_path ?? raw.draft_path,
|
||||
// The incoming draft's own fork base, absence included: this round-trips into the
|
||||
// next save, so falling back to the runtime's version would give that content a
|
||||
|
||||
@@ -166,6 +166,7 @@ export interface RawAppRuntimeValue {
|
||||
summary: string
|
||||
path: string
|
||||
custom_path?: string
|
||||
labels?: string[]
|
||||
draft_path?: string
|
||||
/** The app_version this cell's content forked from, carried so the editor's deploy
|
||||
* guard and diff drawer compare the same pair the full-page editor does. */
|
||||
@@ -1157,6 +1158,7 @@ function createRuntime(session: Session): SessionRuntime {
|
||||
summary: draftValue?.summary ?? result.summary ?? '',
|
||||
path: result.path,
|
||||
custom_path: draftValue?.custom_path ?? result.custom_path,
|
||||
labels: draftValue?.labels ?? result.labels,
|
||||
draft_path: draftValue?.draft_path,
|
||||
// Only a fresh checkout forks from the head; a draft keeps its own base,
|
||||
// unknown included, or it would read as up to date. See loadScript.
|
||||
@@ -1189,9 +1191,8 @@ function createRuntime(session: Session): SessionRuntime {
|
||||
files: { ...(builder ? BUILDER_FRAMEWORK_TEMPLATES.react19 : react19Template) },
|
||||
runnables: builder ? {} : structuredClone(STARTER_RUNNABLES),
|
||||
data: { ...DEFAULT_DATA },
|
||||
// No run-as user: the deploy dialog resolves it, the folder's default first.
|
||||
policy: {
|
||||
on_behalf_of: user?.username.includes('@') ? user.username : `u/${user?.username}`,
|
||||
on_behalf_of_email: user?.email,
|
||||
execution_mode: 'publisher',
|
||||
sandbox: true
|
||||
},
|
||||
|
||||
@@ -16,6 +16,7 @@ import { isAdminIn } from '$lib/user'
|
||||
import { bundleRawAppDraft } from '$lib/components/copilot/chat/global/rawAppBundlerBridge'
|
||||
import type { AppDraftValue } from '$lib/components/copilot/chat/global/workspaceItems'
|
||||
import { updateRawAppPolicy } from '$lib/components/raw_apps/rawAppPolicy'
|
||||
import { policyForUpdate } from '$lib/components/apps/editor/publishAccessMode'
|
||||
import { DEFAULT_DATA as DEFAULT_RAW_APP_DATA } from '$lib/components/raw_apps/dataTableRefUtils'
|
||||
import {
|
||||
appSourceToDraftValue,
|
||||
@@ -56,9 +57,6 @@ export async function deployRawAppValue({
|
||||
// The value carries the runnables, so the policy's triggerables have to be
|
||||
// recomputed from it or the deployed app can't call what it now contains.
|
||||
const policy = (await updateRawAppPolicy(runnables, currentPolicy)) as Policy
|
||||
if (!policy.execution_mode) {
|
||||
policy.execution_mode = 'publisher'
|
||||
}
|
||||
|
||||
const bundle = await bundleRawAppDraft({ workspace, files })
|
||||
|
||||
@@ -72,7 +70,7 @@ export async function deployRawAppValue({
|
||||
// version can still carry the pre-`data` datatable shapes.
|
||||
value: { files, runnables, data: normalizeRawAppData(plainValue) },
|
||||
summary: summary ?? '',
|
||||
policy,
|
||||
policy: policyForUpdate(policy),
|
||||
deployment_message: deploymentMessage,
|
||||
// custom_path changes require admin (see deployRawAppDraft).
|
||||
custom_path: isAdmin ? (customPath ?? '') : undefined,
|
||||
@@ -139,9 +137,10 @@ export async function deployRawAppDraft(
|
||||
path: targetPath,
|
||||
value: rawAppValue,
|
||||
summary,
|
||||
policy,
|
||||
policy: policyForUpdate(policy),
|
||||
deployment_message: deploymentMessage,
|
||||
custom_path: isAdmin ? (value.custom_path ?? '') : undefined,
|
||||
labels: value.labels,
|
||||
// Preserve the policy's on_behalf_of: this draft-deploy path has no
|
||||
// on-behalf-of selector, so without the flag the backend resets it to
|
||||
// the deploying user (gated server-side by can_preserve_on_behalf_of).
|
||||
@@ -162,6 +161,7 @@ export async function deployRawAppDraft(
|
||||
policy,
|
||||
deployment_message: deploymentMessage,
|
||||
custom_path: value.custom_path,
|
||||
labels: value.labels,
|
||||
// Preserve the policy's on_behalf_of (see update branch above).
|
||||
preserve_on_behalf_of: policy.on_behalf_of ? true : undefined
|
||||
},
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { draftBaseIsStale, deployDraft } from './utils_draft_deploy'
|
||||
import { draftBaseIsStale, deployDraft, getDraftDiffValues } from './utils_draft_deploy'
|
||||
|
||||
vi.mock('$lib/gen', () => ({
|
||||
ScriptService: { getScriptByPath: vi.fn(), createScript: vi.fn() },
|
||||
FlowService: { getFlowByPath: vi.fn(), createFlow: vi.fn(), updateFlow: vi.fn() },
|
||||
DraftService: { deleteDraft: vi.fn() },
|
||||
AppService: {},
|
||||
AppService: { getAppByPath: vi.fn(), createApp: vi.fn() },
|
||||
VariableService: { getVariable: vi.fn(), createVariable: vi.fn(), updateVariable: vi.fn() },
|
||||
ResourceService: { getResource: vi.fn(), updateResource: vi.fn(), createResource: vi.fn() },
|
||||
ScheduleService: {},
|
||||
@@ -31,9 +31,13 @@ vi.mock('$lib/rawAppDeploy', () => ({ deployRawAppDraft: vi.fn() }))
|
||||
vi.mock('$lib/components/raw_apps/utils', () => ({ canonicalRawAppDiffValue: vi.fn() }))
|
||||
vi.mock('$lib/appDiffSides', () => ({ classicAppDraftParts: vi.fn() }))
|
||||
vi.mock('$lib/utils_deployable', () => ({ TRIGGER_RUNTIME_IGNORE: [] }))
|
||||
vi.mock('$lib/components/apps/editor/appPolicy', () => ({
|
||||
updatePolicy: vi.fn(async (_app: unknown, policy: unknown) => policy)
|
||||
}))
|
||||
|
||||
import { ScriptService, FlowService, VariableService, ResourceService } from '$lib/gen'
|
||||
import { ScriptService, FlowService, VariableService, ResourceService, AppService } from '$lib/gen'
|
||||
import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte'
|
||||
import { classicAppDraftParts } from '$lib/appDiffSides'
|
||||
|
||||
// draftBaseIsStale compares a draft's base pointer against the deployed head
|
||||
// of the item it was fetched with (`get_draft=true`). Shared by CompareDrafts
|
||||
@@ -143,6 +147,38 @@ describe('deployDraft preserves on_behalf_of', () => {
|
||||
})
|
||||
})
|
||||
|
||||
// The backend runs an app without `sandbox` same-origin with each viewer's session, and a draft
|
||||
// saved before drafts carried the policy has none to give.
|
||||
describe('deployDraft: draft-only classic app', () => {
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it('creates the app sandboxed when its draft carries no policy', async () => {
|
||||
vi.mocked(AppService.getAppByPath).mockResolvedValueOnce({ draft: { grid: [] } } as any)
|
||||
vi.mocked(classicAppDraftParts).mockReturnValueOnce({ value: { grid: [] } } as any)
|
||||
|
||||
expect(await deployDraft('app', 'u/alice/dash', 'ws', { draftOnly: true })).toEqual({
|
||||
success: true
|
||||
})
|
||||
expect(AppService.createApp).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
requestBody: expect.objectContaining({
|
||||
policy: expect.objectContaining({ execution_mode: 'publisher', sandbox: true })
|
||||
})
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('shows the sandboxed policy it deploys in the diff', async () => {
|
||||
vi.mocked(AppService.getAppByPath).mockResolvedValueOnce({ draft: { grid: [] } } as any)
|
||||
vi.mocked(classicAppDraftParts)
|
||||
.mockReturnValueOnce({ value: {} } as any)
|
||||
.mockReturnValueOnce({ value: { grid: [] } } as any)
|
||||
|
||||
const { draft } = await getDraftDiffValues('app', 'u/alice/dash', 'ws', true)
|
||||
expect(draft.policy).toEqual({ sandbox: true })
|
||||
})
|
||||
})
|
||||
|
||||
// Muting writes to the deployed row at once, so a draft saved before it holds a stale copy, and
|
||||
// the backend unmutes on a deploy that sends `false`.
|
||||
describe('deployDraft keeps the deployed mute flag', () => {
|
||||
|
||||
@@ -32,14 +32,23 @@ import {
|
||||
GcpTriggerService,
|
||||
AzureTriggerService,
|
||||
EmailTriggerService,
|
||||
type Policy,
|
||||
type UserDraftItemKind
|
||||
} from '$lib/gen'
|
||||
import type { App } from '$lib/components/apps/types'
|
||||
import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte'
|
||||
import type { DeployResult } from '$lib/utils_workspace_deploy'
|
||||
import { TRIGGER_RUNTIME_IGNORE } from '$lib/utils_deployable'
|
||||
import { deployRawAppDraft } from '$lib/rawAppDeploy'
|
||||
import { canonicalRawAppDiffValue } from '$lib/components/raw_apps/utils'
|
||||
import { classicAppDraftParts } from '$lib/appDiffSides'
|
||||
import {
|
||||
appDraftSettings,
|
||||
draftOrDeployedSettings,
|
||||
policySettings,
|
||||
withDraftPolicySettings
|
||||
} from '$lib/components/apps/editor/appDraftSettings'
|
||||
import { policyForUpdate } from '$lib/components/apps/editor/publishAccessMode'
|
||||
import { invalidateWorkspaceDrafts } from '$lib/workspaceDrafts.svelte'
|
||||
import { invalidateWorkspaceComparison } from '$lib/workspaceComparison'
|
||||
import { setLocalDraftHint } from '$lib/localDraftHints.svelte'
|
||||
@@ -188,7 +197,12 @@ export function canonicalDraftSideValue(kind: DraftKind, value: unknown): unknow
|
||||
if (kind === 'raw_app') return canonicalRawAppDiffValue((value ?? {}) as Record<string, any>)
|
||||
if (kind === 'app') {
|
||||
const parts = classicAppDraftParts(value)
|
||||
return { summary: parts.summary ?? '', value: parts.value }
|
||||
return {
|
||||
summary: parts.summary ?? '',
|
||||
value: parts.value,
|
||||
...(parts.policy ? { policy: policySettings(parts.policy) } : {}),
|
||||
...(parts.labels ? { labels: parts.labels } : {})
|
||||
}
|
||||
}
|
||||
if (kind === 'flow' && value !== null && typeof value === 'object') {
|
||||
const { version_id: _v, ...rest } = value as Record<string, unknown>
|
||||
@@ -254,6 +268,11 @@ function canonicalizeDraftDiffValue(kind: DraftKind, raw: any, isDraft: boolean)
|
||||
return stripScheduleTriggerRuntime(raw)
|
||||
}
|
||||
|
||||
/** What a draft-only app deploys with when its draft carries no policy, as a draft saved before
|
||||
* drafts carried one does: a new app's sandboxed policy, since an empty one deploys it
|
||||
* unsandboxed. The diff shows the same, or it would show a policy the deploy does not store. */
|
||||
const DRAFT_ONLY_APP_POLICY: Policy = { execution_mode: 'publisher', sandbox: true }
|
||||
|
||||
/**
|
||||
* Fetch the deployed value and the draft value for an item, for the DiffDrawer
|
||||
* (`mode: 'simple'`, original = deployed, current = draft). For a `draft_only`
|
||||
@@ -345,15 +364,23 @@ export async function getDraftDiffValues(
|
||||
// `value`. Both sides reduce to `{ summary, value }` with the metadata
|
||||
// extracted from the grid, so a summary edit diffs as a summary edit and
|
||||
// the grid never diffs against draft-only markers.
|
||||
// The settings are compared too, or a settings-only draft reads as equal to the deployed
|
||||
// app and the auto-prune drops it.
|
||||
const deployedParts = classicAppDraftParts(r.value)
|
||||
const draftParts = r.draft != null ? classicAppDraftParts(r.draft) : deployedParts
|
||||
const deployed = { summary: r.summary ?? '', value: deployedParts.value, path: r.path }
|
||||
const deployed = {
|
||||
summary: r.summary ?? '',
|
||||
value: deployedParts.value,
|
||||
path: r.path,
|
||||
...appDraftSettings(r)
|
||||
}
|
||||
return {
|
||||
deployed: draftOnly ? EMPTY_DEPLOYED.app!(undefined) : deployed,
|
||||
draft: {
|
||||
summary: draftParts.summary ?? r.summary ?? '',
|
||||
value: draftParts.value,
|
||||
path: draftParts.draftPath ?? r.path
|
||||
path: draftParts.draftPath ?? r.path,
|
||||
...draftOrDeployedSettings(draftParts, draftOnly ? { policy: DRAFT_ONLY_APP_POLICY } : r)
|
||||
},
|
||||
hasDraft: r.draft != null,
|
||||
noDeployed: r.no_deployed === true
|
||||
@@ -571,35 +598,37 @@ export async function deployDraft(
|
||||
// plus a `draft_path` when the path was renamed) — NOT wrapped in
|
||||
// { value, summary, policy } like script/flow drafts. So the deploy value
|
||||
// is the draft object itself; fall back to the deployed value when there's
|
||||
// no draft. `draft_path` and `summary` are draft-only fields mirrored onto
|
||||
// the App value (the editor drops them on deploy), so strip them from the
|
||||
// value and apply them as the deploy path / summary column.
|
||||
// `parent_version` is the draft's stale-check base, never deployed.
|
||||
const draft = r.draft as Record<string, any> | undefined
|
||||
const {
|
||||
draft_path: draftPath,
|
||||
summary: draftSummary,
|
||||
parent_version: _pv,
|
||||
...appValue
|
||||
} = draft ?? r.value ?? {}
|
||||
// Policy isn't carried in the app draft, so it comes from the deployed app
|
||||
// (or a default). custom_path requires admin on update; non-admins send
|
||||
// undefined so the backend preserves the existing route. The draft has no
|
||||
// custom_path, so admins fall back to the deployed route (`''` when none).
|
||||
// no draft. The draft-only fields mirrored onto the App value (staged path,
|
||||
// summary, settings, fork base) are stripped from it and applied as the
|
||||
// app row's columns.
|
||||
const parts = classicAppDraftParts(r.draft ?? r.value ?? {})
|
||||
const appValue = parts.value as App
|
||||
const deployedPolicy = draftOnly ? DRAFT_ONLY_APP_POLICY : (r.policy as Policy)
|
||||
const settings = draftOrDeployedSettings(parts, draftOnly ? { policy: deployedPolicy } : r)
|
||||
// The runnable whitelist is rebuilt from the value being deployed: the deployed
|
||||
// policy's whitelist describes the previous value. Loaded lazily, as it pulls in the
|
||||
// app component tree.
|
||||
const { updatePolicy } = await import('$lib/components/apps/editor/appPolicy')
|
||||
const policy = await updatePolicy(
|
||||
appValue,
|
||||
withDraftPolicySettings(deployedPolicy, settings.policy)
|
||||
)
|
||||
// custom_path requires admin on update; non-admins send undefined so the
|
||||
// backend preserves the existing route. The draft has no custom_path, so
|
||||
// admins fall back to the deployed route (`''` when none).
|
||||
const isAdmin = await isAdminIn(workspace)
|
||||
const policy = r.policy ?? { execution_mode: 'publisher', sandbox: true }
|
||||
const requestBody = {
|
||||
value: appValue,
|
||||
summary: draftSummary ?? r.summary ?? '',
|
||||
policy,
|
||||
summary: parts.summary ?? r.summary ?? '',
|
||||
policy: draftOnly ? policy : policyForUpdate(policy),
|
||||
// Honor the draft's intended path; `draft_path` holds the user-typed path
|
||||
// for a never-deployed app parked at a `u/{user}/draft_{uuid}` storage key.
|
||||
path: draftPath ?? r.path ?? path,
|
||||
path: parts.draftPath ?? r.path ?? path,
|
||||
custom_path: isAdmin ? (r.custom_path ?? '') : undefined,
|
||||
labels: settings.labels,
|
||||
deployment_message: deploymentMessage,
|
||||
// The draft carries no on-behalf-of selector — the policy comes straight
|
||||
// from the deployed app. Preserve its on_behalf_of (the backend resets it
|
||||
// to the deploying user without this flag, gated by can_preserve_on_behalf_of).
|
||||
// Preserve the drafted on_behalf_of (the backend resets it to the deploying
|
||||
// user without this flag, gated by can_preserve_on_behalf_of).
|
||||
preserve_on_behalf_of: policy?.on_behalf_of ? true : undefined
|
||||
}
|
||||
// Same as flows: draft-only apps have no app row → create;
|
||||
|
||||
@@ -22,6 +22,11 @@
|
||||
import { stripNewDraftFlag, stripNewDraftFlagOnSave, shouldSeedNewDraft } from '$lib/newDraftFlag'
|
||||
import { OtherUserDraftLoad } from '$lib/components/otherUserDraftLoad.svelte'
|
||||
import { runResetToDeployed } from '$lib/userDraftToast'
|
||||
import { classicAppDraftParts } from '$lib/appDiffSides'
|
||||
import {
|
||||
appDraftSettings,
|
||||
withDraftPolicySettings
|
||||
} from '$lib/components/apps/editor/appDraftSettings'
|
||||
|
||||
let app = $state(undefined as (AppWithLastVersion & { value: any }) | undefined)
|
||||
/** Seeded from a hub app this load; AppEditor relaxes a few authoring affordances. */
|
||||
@@ -227,7 +232,8 @@
|
||||
// never compares equal (and a summary-only edit still counts as a change).
|
||||
({
|
||||
...(structuredClone(stateSnapshot(backendApp.value)) as App),
|
||||
summary: backendApp.summary
|
||||
summary: backendApp.summary,
|
||||
...appDraftSettings(structuredClone(stateSnapshot(backendApp)))
|
||||
} as App)
|
||||
// `other_drafts_users` only computed when `getDraft`; don't clobber the
|
||||
// known list on a `getDraft:false` reload. See /scripts/edit's loader.
|
||||
@@ -359,6 +365,16 @@
|
||||
// `app = undefined` first, unmounting AppEditor and releasing the UserDraft
|
||||
// entry, so the remount starts fresh — no local discard is needed here
|
||||
// (and `UserDraft.discard` would POST `value: null`, a spurious autosave).
|
||||
// The draft's settings win over the deployed ones here; `savedApp` keeps the deployed ones,
|
||||
// which the settings drawer compares against.
|
||||
const draftParts = classicAppDraftParts(backendApp.value)
|
||||
backendApp = {
|
||||
...backendApp,
|
||||
policy: draftParts.policy
|
||||
? withDraftPolicySettings(backendApp.policy, draftParts.policy)
|
||||
: backendApp.policy,
|
||||
labels: draftParts.labels ?? backendApp.labels
|
||||
} as typeof backendApp
|
||||
app = backendApp
|
||||
}
|
||||
|
||||
@@ -495,7 +511,7 @@
|
||||
{deployedBaseline}
|
||||
newPath={app.value?.draft_path ?? app.path}
|
||||
path={page.params.path ?? ''}
|
||||
policy={app.policy}
|
||||
bind:policy={app.policy}
|
||||
bind:savedApp
|
||||
{diffDrawer}
|
||||
version={app.versions ? app.versions[app.versions.length - 1] : undefined}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { stripNewDraftFlag, stripNewDraftFlagOnSave, shouldSeedNewDraft } from '$lib/newDraftFlag'
|
||||
|
||||
import { AppService } from '$lib/gen'
|
||||
import { userStore, workspaceStore } from '$lib/stores'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { useRoleCapabilities, workspaceListLoaded } from '$lib/operatorWriteRights'
|
||||
import { readFieldsRecursively } from '$lib/utils'
|
||||
import { goto } from '$lib/navigation'
|
||||
@@ -51,6 +51,7 @@
|
||||
summary: string
|
||||
policy?: any
|
||||
custom_path?: string
|
||||
labels?: string[]
|
||||
/** User-typed path the home list renders, set only when it differs
|
||||
* from the deployed/seeded `savedApp.path`. */
|
||||
draft_path?: string
|
||||
@@ -72,6 +73,8 @@
|
||||
* `savedApp.path`; mirrored into the draft below as `draft_path` for the
|
||||
* home list's friendly name. */
|
||||
let pendingDraftPath = $state<string | undefined>(undefined)
|
||||
/** The labels the header is editing, mirrored into the draft. */
|
||||
let pendingDraftSettings = $state<{ labels: string[] } | undefined>(undefined)
|
||||
|
||||
let savedApp:
|
||||
| {
|
||||
@@ -128,6 +131,7 @@
|
||||
readFieldsRecursively(policy)
|
||||
void summary
|
||||
void pendingDraftPath
|
||||
void pendingDraftSettings
|
||||
draftSync.draft = {
|
||||
files: currentFiles,
|
||||
runnables,
|
||||
@@ -135,6 +139,7 @@
|
||||
summary,
|
||||
policy,
|
||||
custom_path: savedApp?.custom_path,
|
||||
labels: pendingDraftSettings ? pendingDraftSettings.labels : (labels ?? []),
|
||||
parent_version: parentVersion,
|
||||
// Persist the typed path as `draft_path` only when it actually differs
|
||||
// from the current path — a `draft_path` equal to the baseline is a
|
||||
@@ -235,11 +240,8 @@
|
||||
path
|
||||
})
|
||||
}
|
||||
// No run-as user: the deploy dialog resolves it, the folder's default first.
|
||||
const defaultPolicy = {
|
||||
on_behalf_of: $userStore?.username.includes('@')
|
||||
? $userStore?.username
|
||||
: `u/${$userStore?.username}`,
|
||||
on_behalf_of_email: $userStore?.email,
|
||||
execution_mode: 'publisher',
|
||||
sandbox: true
|
||||
} as any
|
||||
@@ -373,6 +375,7 @@
|
||||
summary: backendApp.summary ?? '',
|
||||
policy: backendApp.policy,
|
||||
custom_path: backendApp.custom_path,
|
||||
labels: backendApp.labels ?? [],
|
||||
parent_version: parentVersion
|
||||
})
|
||||
) as RawAppDraft)
|
||||
@@ -389,6 +392,7 @@
|
||||
summary?: string
|
||||
policy?: any
|
||||
custom_path?: string
|
||||
labels?: string[]
|
||||
draft_path?: string
|
||||
}
|
||||
| undefined
|
||||
@@ -406,6 +410,7 @@
|
||||
backendApp.summary = savedRawAppDraft?.summary ?? ''
|
||||
backendApp.policy = savedRawAppDraft?.policy ?? { execution_mode: 'publisher', sandbox: true }
|
||||
backendApp.custom_path = savedRawAppDraft?.custom_path
|
||||
backendApp.labels = savedRawAppDraft?.labels
|
||||
backendApp.path = page.params.path ?? ''
|
||||
} else if (savedRawAppDraft) {
|
||||
backendApp.value = {
|
||||
@@ -418,13 +423,18 @@
|
||||
if (savedRawAppDraft.policy !== undefined) backendApp.policy = savedRawAppDraft.policy
|
||||
if (savedRawAppDraft.custom_path !== undefined)
|
||||
backendApp.custom_path = savedRawAppDraft.custom_path
|
||||
if (savedRawAppDraft.labels !== undefined) backendApp.labels = savedRawAppDraft.labels
|
||||
}
|
||||
const backendApp_ = structuredClone(stateSnapshot(backendApp))
|
||||
savedApp = {
|
||||
summary: backendApp_.summary,
|
||||
value: backendApp_.value as any,
|
||||
path: backendApp_.path,
|
||||
policy: backendApp_.policy,
|
||||
// The deployed policy, not the draft's swapped in above: the header and the settings
|
||||
// measure what a deploy changes against it.
|
||||
policy: deployedBaseline
|
||||
? structuredClone(stateSnapshot(deployedBaseline.policy))
|
||||
: backendApp_.policy,
|
||||
custom_path: backendApp_.custom_path,
|
||||
labels: backendApp_.labels,
|
||||
no_deployed: backendApp_.no_deployed
|
||||
@@ -452,6 +462,7 @@
|
||||
data = v.data ?? { ...DEFAULT_DATA }
|
||||
summary = v.summary ?? ''
|
||||
policy = v.policy ?? {}
|
||||
labels = v.labels ?? labels
|
||||
// Their draft's own fork base: the bundle is rebuilt from these pieces, so
|
||||
// leaving `parentVersion` on ours would deploy their content claiming a base
|
||||
// it never had.
|
||||
@@ -473,6 +484,7 @@
|
||||
summary,
|
||||
policy,
|
||||
custom_path: savedApp?.custom_path,
|
||||
labels: labels ?? [],
|
||||
parent_version: parentVersion,
|
||||
...(pendingDraftPath ? { draft_path: pendingDraftPath } : {})
|
||||
} as RawAppDraft,
|
||||
@@ -692,11 +704,12 @@
|
||||
bind:data
|
||||
bind:summary
|
||||
bind:pendingDraftPath
|
||||
bind:pendingDraftSettings
|
||||
{newPath}
|
||||
{labels}
|
||||
path={page.params.path ?? ''}
|
||||
liveEditorDraftStoragePath={path}
|
||||
{policy}
|
||||
bind:policy
|
||||
bind:savedApp
|
||||
{diffDrawer}
|
||||
newApp={isNewApp}
|
||||
|
||||
Reference in New Issue
Block a user