Multiplayer agent harness for work.
App sharing: one General access menu (Restricted / org / Anyone with the link) (#1783)
Regan Bell75c83bc1b61a
diff --git a/plugins/web-ui/src/deploy-permissions.ts b/plugins/web-ui/src/deploy-permissions.tsindex d393c6355..8adac3c5e 100644--- a/plugins/web-ui/src/deploy-permissions.ts+++ b/plugins/web-ui/src/deploy-permissions.ts@@ -1,18 +1,23 @@import { html, render, nothing } from "lit";import { live } from "lit/directives/live.js";-import { Globe, Lock, Search, X } from "lucide";+import { Building2, Globe, Lock, Search, X } from "lucide";import { api } from "./core-bridge";import { closeFormMenus, icon, initials, menuSelect } from "./ui";import { scopeChip } from "./contexts";import { friendlyPrincipal } from "./deploy-view";import { errMessage } from "../../chassis/src/errors";import { peopleResults, type DirectoryMatch } from "./people-results";+import { appState } from "./shell-state";interface Grant {scope: string;permission: "read" | "write";}+type GeneralAccess = "restricted" | "org" | "public";++const isOrgGrant = (grant: Grant): boolean => grant.scope === "org" || grant.scope.startsWith("org:");+export async function openDeploymentPermissions(id: string, title: string, owner: string): Promise<void> {const opener = document.activeElement as HTMLElement | null;const dialog = document.createElement("dialog");@@ -78,21 +83,35 @@ export async function openDeploymentPermissions(id: string, title: string, ownerif (dialog.isConnected) draw();}};- const changePublic = async (value: string) => {- if (busy) return;+ const orgGrant = (): Grant | undefined => grantees.find(isOrgGrant);+ const generalAccess = (): GeneralAccess => {+ if (publicAccess) return "public";+ return orgGrant() ? "org" : "restricted";+ };+ const post = async (body: Record<string, unknown>) => {+ const response = await api<{ public: boolean; grantees: Grant[] }>(endpoint, {+ method: "POST",+ body: JSON.stringify(body),+ });+ publicAccess = response.public;+ grantees = response.grantees;+ };+ const changeGeneral = async (next: GeneralAccess) => {+ if (busy || next === generalAccess() || (next === "public" && !externalSharing)) return;closeFormMenus();busy = true;error = "";draw();try {- const response = await api<{ public: boolean; grantees: Grant[] }>(endpoint, {- method: "POST",- body: JSON.stringify({ public: value === "public" }),- });- publicAccess = response.public;- grantees = response.grantees;+ if (next === "public") await post({ public: true });+ else {+ if (publicAccess) await post({ public: false });+ const grant = orgGrant();+ if (next === "org" && !grant) await post({ scope: "org", access: "view" });+ if (next === "restricted" && grant) await post({ scope: grant.scope, access: "none" });+ }} catch (e) {- error = errMessage(e, "Could not update public access.");+ error = errMessage(e, "Could not update general access.");} finally {busy = false;if (dialog.isConnected) draw();@@ -133,10 +152,12 @@ export async function openDeploymentPermissions(id: string, title: string, owner}}};+ const orgName = (): string => appState.me?.companyName?.trim() || "Your organization";const generalAccessNote = (): string => {- if (publicAccess) return "No sign-in required";- if (externalSharing) return "Only people with access can open";- return "Sharing outside your organization is turned off by an admin";+ const level = generalAccess();+ if (level === "public") return "Anyone on the internet with the link can open. No sign-in required";+ if (level === "org") return `Anyone signed in to ${orgName()} can open`;+ return "Only people with access can open";};const emailCandidate = (): string | null => {const email = query.trim().toLowerCase();@@ -296,28 +317,48 @@ export async function openDeploymentPermissions(id: string, title: string, owner>${owner.startsWith("personal:") ? friendlyPrincipal(owner.slice(9)) : scopeChip(owner)}</span><span class="permission-owner">Owner</span></div>- ${grantees.map((grant) => html`<div class="permission-row"><span class="project-member-avatar" aria-hidden="true">${initials(grant.scope.replace("personal:", ""))}</span><span class="permission-person-label">${names.get(grant.scope) ?? (grant.scope.startsWith("personal:") ? grant.scope.slice(9) : scopeChip(grant.scope))}${names.has(grant.scope) ? html`<small>${grant.scope.replace("personal:", "")}</small>` : nothing}</span>${permissionMenu(grant.permission === "write" ? "manage" : "view", `Access for ${grant.scope}`, (value) => void change(grant.scope, value), true)}</div>`)}+ ${grantees.filter((grant) => generalAccess() !== "org" || !isOrgGrant(grant)).map((grant) => html`<div class="permission-row"><span class="project-member-avatar" aria-hidden="true">${initials(isOrgGrant(grant) ? orgName() : grant.scope.replace("personal:", ""))}</span><span class="permission-person-label">${isOrgGrant(grant) ? orgName() : (names.get(grant.scope) ?? (grant.scope.startsWith("personal:") ? grant.scope.slice(9) : scopeChip(grant.scope)))}${names.has(grant.scope) ? html`<small>${grant.scope.replace("personal:", "")}</small>` : nothing}</span>${permissionMenu(grant.permission === "write" ? "manage" : "view", `Access for ${grant.scope}`, (value) => void change(grant.scope, value), true)}</div>`)}</div><div class="permission-section-label permission-general-label">General access</div><div class="project-member-list"><div class="permission-row">- <span class="project-member-avatar" aria-hidden="true">${icon(publicAccess ? Globe : Lock, 16)}</span>- <span class="permission-person-label"- >${publicAccess ? "Anyone with the link" : "Restricted"}<small>${generalAccessNote()}</small></span+ <span class="project-member-avatar" aria-hidden="true"+ >${icon({ public: Globe, org: Building2, restricted: Lock }[generalAccess()], 16)}</span>- <fieldset class="permission-control" ?disabled=${busy}>- ${menuSelect({- value: publicAccess ? "public" : "restricted",- ariaLabel: "General access",- options: [- { value: "restricted", label: "Restricted" },- ...(externalSharing ? [{ value: "public", label: "Anyone with the link" }] : []),- ],- onSelect: (next) => {- if (next) void changePublic(next);- },- })}- </fieldset>+ <span class="permission-person-label">+ <fieldset class="permission-control general-access-control" ?disabled=${busy}>+ ${menuSelect({+ value: generalAccess(),+ ariaLabel: "General access",+ className: "general-access-menu",+ options: [+ { value: "restricted", label: "Restricted" },+ { value: "org", label: orgName() },+ {+ value: "public",+ label: "Anyone with the link",+ ...(externalSharing+ ? {}+ : { disabledHint: "An org admin must turn on external app sharing first." }),+ },+ ],+ onSelect: (next) => {+ if (next === "restricted" || next === "org" || next === "public") void changeGeneral(next);+ },+ })}+ </fieldset>+ <small>${generalAccessNote()}</small>+ </span>+ ${(() => {+ const grant = generalAccess() === "org" ? orgGrant() : undefined;+ return grant+ ? permissionMenu(+ grant.permission === "write" ? "manage" : "view",+ `Access for ${orgName()}`,+ (value) => void change(grant.scope, value),+ )+ : nothing;+ })()}</div></div>${diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.cssindex 572fb4c1e..6c98f6245 100644--- a/plugins/web-ui/src/shell.css+++ b/plugins/web-ui/src/shell.css@@ -12667,6 +12667,18 @@ body.app-edit-embed .custom-chat-shell.app-edit-chat > .chat-bottom-dock {left: auto;right: 0;}+.general-access-control .menu-button {+ margin-left: -8px;+ font-size: var(--font-13);+ font-weight: 500;+}+.menu-option[aria-disabled="true"] {+ opacity: 0.45;+ cursor: not-allowed;+}+.menu-option[aria-disabled="true"]:hover {+ background: transparent;+}.permission-control .menu-option {font-size: 12px;}@@ -12714,6 +12726,10 @@ body.app-edit-embed .custom-chat-shell.app-edit-chat > .chat-bottom-dock {.deployment-permissions-dialog .permission-invite .menu-popover {inset: calc(100% + 6px) auto auto 0 !important;}+.deployment-permissions-dialog .general-access-control .menu-popover {+ inset: calc(100% + 6px) auto auto -8px !important;+ width: 220px !important;+}.deployment-permissions-dialog .permission-control .menu-popover.drop-up {top: auto !important;bottom: calc(100% + 6px) !important;diff --git a/plugins/web-ui/src/ui.ts b/plugins/web-ui/src/ui.tsindex 9338488ac..35710f865 100644--- a/plugins/web-ui/src/ui.ts+++ b/plugins/web-ui/src/ui.ts@@ -1,6 +1,7 @@import { unsafeSVG } from "lit/directives/unsafe-svg.js";import { html, nothing, type TemplateResult } from "lit";import { live } from "lit/directives/live.js";+import { tip } from "./tooltip.ts";import { Check, ChevronDown, Download, createElement, type IconNode } from "lucide";export function brandName(): string {@@ -270,6 +271,7 @@ export interface MenuSelectOption {value: string | null;label: string;glyph?: IconNode;+ disabledHint?: string;}export function menuSelect(props: {@@ -290,8 +292,12 @@ export function menuSelect(props: {type="button"role="menuitemradio"aria-checked=${active ? "true" : "false"}+ aria-disabled=${o.disabledHint ? "true" : nothing}+ aria-description=${o.disabledHint || nothing}+ ${tip(o.disabledHint ?? "")}@click=${(e: Event) => {e.stopPropagation();+ if (o.disabledHint) return;closeFormMenus();props.onSelect(o.value ?? null);}}diff --git a/plugins/web-ui/test/deploy-permissions-source.test.ts b/plugins/web-ui/test/deploy-permissions-source.test.tsindex 68a1d2606..b972d6329 100644--- a/plugins/web-ui/test/deploy-permissions-source.test.ts+++ b/plugins/web-ui/test/deploy-permissions-source.test.ts@@ -9,7 +9,8 @@ test("app permissions expose explicit private and public general-access states",assert.match(source, /Restricted/);assert.match(source, /Anyone with the link/);assert.match(source, /No sign-in required/);- assert.match(source, /JSON\.stringify\(\{ public: value === "public" \}\)/);+ assert.match(source, /post\(\{ public: true \}\)/);+ assert.match(source, /post\(\{ public: false \}\)/);assert.match(source, /Public\. Anyone can open this app\./);});@@ -23,9 +24,8 @@ test("app permissions offer explicit view-only email grants outside the directorassert.match(source, /Access granted, but no invitation email was sent/);});-test("app permissions hide public links and outside emails when external sharing is off", () => {+test("general access is one menu: restricted, the org, or (admin permitting) anyone with the link", () => {assert.match(source, /externalSharing = response\.externalSharing !== false/);- assert.match(source, /if \(!externalSharing\) return null;/);- assert.match(source, /\.\.\.\(externalSharing \? \[\{ value: "public", label: "Anyone with the link" \}\] : \[\]\)/);- assert.match(source, /Sharing outside your organization is turned off by an admin/);+ assert.match(source, /disabledHint: "An org admin must turn on external app sharing first\."/);+ assert.match(source, /post\(\{ scope: "org", access: "view" \}\)/);});diff --git a/src/api/routes/deployments.ts b/src/api/routes/deployments.tsindex 6b39f0ad6..bc2f5be59 100644--- a/src/api/routes/deployments.ts+++ b/src/api/routes/deployments.ts@@ -1635,7 +1635,9 @@ export async function shareDeployment(ctx: ApiCtx): Promise<void> {access,reach,...(invite ? { invitation: invite.invitation } : {}),- public: deployment?.public === true,+ public:+ deployment?.public === true &&+ (await externalAppSharingAllowed(ctx.deps.featureFlags, deployment.ownerScopeId)),grantees,});} catch (e) {diff --git a/test/deploy-subdomain-signin.test.ts b/test/deploy-subdomain-signin.test.tsindex 1b2839895..193afd8e7 100644--- a/test/deploy-subdomain-signin.test.ts+++ b/test/deploy-subdomain-signin.test.ts@@ -26,11 +26,18 @@ const auditLog = { record() {}, events: async () => [], tail: async () => [] };const SESSION_SECRET = "portal-session-secret";const LOGIN_URL = "https://portal.example.com";-function mintPortalSession(sub: string, expInSeconds = 3600, secret = SESSION_SECRET): string {+function mintPortalSession(sub: string, expInSeconds = 3600, secret = SESSION_SECRET, appOnly?: true): string {const key = createHmac("sha256", secret).update("portal.session.v1").digest();const now = Math.floor(Date.now() / 1000);const body = Buffer.from(- JSON.stringify({ k: "session", sub, org: "acme", iat: now, exp: now + expInSeconds }),+ JSON.stringify({+ k: "session",+ sub,+ org: "acme",+ iat: now,+ exp: now + expInSeconds,+ ...(appOnly ? { appOnly } : {}),+ }),).toString("base64url");const sig = createHmac("sha256", key).update(body).digest("base64url");return `${body}.${sig}`;@@ -361,6 +368,69 @@ test("subdomain ingress: portal sign-in admits the owner, denies strangers, boun}});+test("org-wide app access admits only signed-in org members", async () => {+ const upstream = createHttpServer((_req, res) => res.end("UPSTREAM OK"));+ upstream.listen(0);+ const acl = createAclStore();+ const identity = createIdentityService();+ const deploy = createDeployService({+ externalSharingAllowed: async () => false,+ deployStore: createDeployStore(),+ provider: {+ profile: { managedScaleToZero: false },+ apply: async () => ({ host: "127.0.0.1", port: (upstream.address() as AddressInfo).port }),+ destroy: async () => {},+ },+ auditLog,+ acl,+ deployDir: mkdtempSync(join(tmpdir(), "org-access-")),+ });+ const app = createApp({+ deploy,+ acl,+ directory: createDirectoryStore(),+ sessions: createMemorySessionStore(),+ identity,+ } as unknown as Parameters<typeof createApp>[0]);+ const d = await app.deploy({+ ownerScopeId: scopeId("personal", "[email protected]"),+ createdBy: "[email protected]",+ entrypoint: "x",+ files: [],+ name: "teamsite",+ });+ const server = createInsecureTestServer(app, {+ featureFlags: { enabled: async () => false } as unknown as FeatureFlagStore,+ identity,+ deployAppsDomain: "apps.example.com",+ deployGateSecret: "gate-secret",+ deployAppsSessionSecret: SESSION_SECRET,+ deployAppsLoginUrl: LOGIN_URL,+ });+ server.listen(0);+ const port = (server.address() as AddressInfo).port;+ const visit = (cookieFor?: string, appOnly?: true) =>+ httpGet(port, "/", {+ Host: "teamsite.apps.example.com",+ Accept: "application/json",+ ...(cookieFor ? { Cookie: `portal_session=${mintPortalSession(cookieFor, 3600, SESSION_SECRET, appOnly)}` } : {}),+ });+ try {+ assert.equal((await visit("[email protected]")).status, 403, "restricted: a signed-in member without a grant");+ await app.shareDeployment(d.id, scopeId("org", "acme"), "read", { createdBy: "[email protected]" });+ assert.equal((await visit()).status, 401, "org access still requires sign-in");+ assert.equal((await visit("[email protected]")).status, 200, "any signed-in org member can open it");+ assert.equal((await visit("[email protected]", true)).status, 403, "an app-only outside session is not the org");+ await identity.deactivate("[email protected]", "directory-sync");+ assert.equal((await visit("[email protected]")).status, 403, "someone who left the org is not the org");+ await app.shareDeployment(d.id, scopeId("org", "acme"), null, { createdBy: "[email protected]" });+ assert.equal((await visit("[email protected]")).status, 403, "back to restricted closes it");+ } finally {+ await new Promise<void>((resolve) => server.close(() => resolve()));+ await new Promise<void>((resolve) => upstream.close(() => resolve()));+ }+});+test("subdomain ingress: without the session config the domain has no door — a 503, not a bounce", async () => {const deployStore = createDeployStore();const deploy = createDeployService({diff --git a/test/share-deployment.test.ts b/test/share-deployment.test.tsindex 343e1dfe6..6058e30a2 100644--- a/test/share-deployment.test.ts+++ b/test/share-deployment.test.ts@@ -566,6 +566,9 @@ test("deployment public access is explicit, owner-only, and reversible", async (access: "view",});assert.equal(sharedWhilePublic.body.public, true, "person changes preserve and return general access");+ const off = { enabled: async () => false } as unknown as FeatureFlagStore;+ const orgWhileOff = await callShare(app, cap("U1"), "public-toggle", { scope: "org" }, off);+ assert.equal(orgWhileOff.body.public, false, "with external sharing off, a stored public bit is reported as off");const disabled = await callShare(app, cap("U1"), "public-toggle", { public: false });assert.equal(disabled.status, 200);