Multiplayer agent harness for work.
Turn off external app sharing unless an org admin enables it (#1781)
Regan Bell27501bfec55a
diff --git a/plugins/admin/ui/settings-flags.ts b/plugins/admin/ui/settings-flags.tsindex ebe9572ae..70e6b4558 100644--- a/plugins/admin/ui/settings-flags.ts+++ b/plugins/admin/ui/settings-flags.ts@@ -136,6 +136,7 @@ function template() {<option value="persistent_subagents">Persistent subagents</option><option value="inbox_loops">Inbox Loops</option><option value="slack_loading_indicator">Slack loading indicator (experimental)</option>+ <option value="external_app_sharing">External app sharing (public links, outside emails)</option></select></label><div>diff --git a/plugins/web-ui/src/deploy-permissions.ts b/plugins/web-ui/src/deploy-permissions.tsindex 594eceeb5..d393c6355 100644--- a/plugins/web-ui/src/deploy-permissions.ts+++ b/plugins/web-ui/src/deploy-permissions.ts@@ -21,6 +21,7 @@ export async function openDeploymentPermissions(id: string, title: string, ownerdocument.body.append(dialog);let grantees: Grant[] = [];let publicAccess = false;+ let externalSharing = true;let matches: DirectoryMatch[] = [];let query = "";let access = "view";@@ -132,8 +133,14 @@ export async function openDeploymentPermissions(id: string, title: string, owner}}};+ 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 emailCandidate = (): string | null => {const email = query.trim().toLowerCase();+ if (!externalSharing) return null;if (email.length > 254 || !/^[^@\s,;<>"]+@[^@\s,;<>"]+\.[^@\s,;<>"]+$/.test(email)) return null;if (owner.toLowerCase() === `personal:${email}` ||@@ -296,16 +303,15 @@ export async function openDeploymentPermissions(id: string, title: string, owner<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- >${publicAccess ? "No sign-in required" : "Only people with access can open"}</small- ></span+ >${publicAccess ? "Anyone with the link" : "Restricted"}<small>${generalAccessNote()}</small></span+ ><fieldset class="permission-control" ?disabled=${busy}>${menuSelect({value: publicAccess ? "public" : "restricted",ariaLabel: "General access",options: [{ value: "restricted", label: "Restricted" },- { value: "public", label: "Anyone with the link" },+ ...(externalSharing ? [{ value: "public", label: "Anyone with the link" }] : []),],onSelect: (next) => {if (next) void changePublic(next);@@ -328,8 +334,9 @@ export async function openDeploymentPermissions(id: string, title: string, ownerdraw();dialog.showModal();try {- const response = await api<{ public: boolean; grantees: Grant[] }>(endpoint);+ const response = await api<{ public: boolean; externalSharing?: boolean; grantees: Grant[] }>(endpoint);publicAccess = response.public;+ externalSharing = response.externalSharing !== false;grantees = response.grantees;loaded = true;} catch (e) {diff --git a/plugins/web-ui/test/deploy-permissions-source.test.ts b/plugins/web-ui/test/deploy-permissions-source.test.tsindex b63ae81a4..68a1d2606 100644--- a/plugins/web-ui/test/deploy-permissions-source.test.ts+++ b/plugins/web-ui/test/deploy-permissions-source.test.ts@@ -22,3 +22,10 @@ test("app permissions offer explicit view-only email grants outside the directorassert.match(source.replace(/\s+/g, " "), /This does not add them to your organization/);assert.match(source, /Access granted, but no invitation email was sent/);});++test("app permissions hide public links and outside emails when external sharing is off", () => {+ 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/);+});diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.tsindex f4c36fda3..dfad9812b 100644--- a/src/api/agent-api-catalog.ts+++ b/src/api/agent-api-catalog.ts@@ -482,7 +482,7 @@ const FAMILIES: AgentApiFamily[] = [(m === "POST" &&/^\/v1\/deployments\/[^/]+\/(share|archive|restore|name|display-name|always-on|embed-ancestors)$/.test(p)),guidance:- 'To see the published apps you can reach across scopes, GET /v1/deployments (each row carries your permission and a clone/push gitUrl). Read what an app renders as the asking person with GET /v1/deployments/:id/fetch. A published app (`apps` action `publish`) is reachable only by its owner plus whoever the owner shares it with. For authenticated access, POST /v1/deployments/:id/share with `scope:"org"`, `recipient:"<name>"`, or an exact `email:"[email protected]"` with `access:"view"`; external email grants are view-only and send an invitation with the app link. Check `invitation.emailSent` and surface `emailProblem` if delivery fails. This does not make the recipient an instance member. To make the app reachable without sign-in, POST the same endpoint with `{public:true}`; `{public:false}` restricts it again. Public access is never the default and only the owner may change it. POST /v1/deployments/:id/embed-ancestors with `{embedAncestors:["https://tools.example.com", ...]}` lets those sites embed the app; pass `[]` to forbid embedding again. To rename, archive, restore, or change always-on behavior, use the corresponding endpoint.',+ 'To see the published apps you can reach across scopes, GET /v1/deployments (each row carries your permission and a clone/push gitUrl). Read what an app renders as the asking person with GET /v1/deployments/:id/fetch. A published app (`apps` action `publish`) is reachable only by its owner plus whoever the owner shares it with. For authenticated access, POST /v1/deployments/:id/share with `scope:"org"`, `recipient:"<name>"`, or an exact `email:"[email protected]"` with `access:"view"`; email grants to people outside the organization are view-only, send an invitation with the app link, and are refused unless an org admin has enabled external app sharing (off by default). Check `invitation.emailSent` and surface `emailProblem` if delivery fails. This does not make the recipient an instance member. To make the app reachable without sign-in, POST the same endpoint with `{public:true}`; `{public:false}` restricts it again. Public access is never the default, only the owner may change it, and it is refused (and existing public links require sign-in) unless an org admin has enabled external app sharing. POST /v1/deployments/:id/embed-ancestors with `{embedAncestors:["https://tools.example.com", ...]}` lets those sites embed the app; pass `[]` to forbid embedding again. To rename, archive, restore, or change always-on behavior, use the corresponding endpoint.',routes: [{method: "GET",diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.tsindex bc61026db..538804d60 100644--- a/src/api/app-sessions.ts+++ b/src/api/app-sessions.ts@@ -1045,6 +1045,7 @@ export function createSessionMethods((await h.directoryMember(email))?.type === "internal",),};+ await deps.deploy.assertShareAllowed(g.ownerScopeId, g.granteeScopeId, g.permission);}await deps.acl.grant(g, await artifactAuthor(g.ownerScopeId, g.ref));deps.auditLog.record({diff --git a/src/api/routes/auth-broker.ts b/src/api/routes/auth-broker.tsindex 7dc7a6ff9..0438c0f34 100644--- a/src/api/routes/auth-broker.ts+++ b/src/api/routes/auth-broker.ts@@ -1,3 +1,4 @@+import { externalAppSharingAllowed } from "../../feature-flags.ts";import { createHash } from "node:crypto";import { verifySignedPayload } from "../../auth/signed-token.ts";import { AdminError } from "../../admin/admin-service.ts";@@ -68,7 +69,7 @@ async function emailAllowed(ctx: ApiCtx): Promise<void> {if (allowed) return sendJson(res, 200, { allowed: true, expiresAt: member?.expiresAt });const grants = (await deps.acl?.list()) ?? [];const deployments = await app.listDeployments();- const appOnly = deployments.some(+ const granted = deployments.filter((d) =>d.status !== "archived" &&grants.some(@@ -79,6 +80,10 @@ async function emailAllowed(ctx: ApiCtx): Promise<void> {g.permission === "read",),);+ const allowedOwners = await Promise.all(+ granted.map((d) => externalAppSharingAllowed(deps.featureFlags, d.ownerScopeId)),+ );+ const appOnly = allowedOwners.some(Boolean);return sendJson(res, 200, appOnly ? { allowed: true, appOnly: true } : { allowed: false });}diff --git a/src/api/routes/deployments.ts b/src/api/routes/deployments.tsindex eca420722..6b39f0ad6 100644--- a/src/api/routes/deployments.ts+++ b/src/api/routes/deployments.ts@@ -1,3 +1,4 @@+import { EXTERNAL_APP_SHARING_OFF, externalAppSharingAllowed } from "../../feature-flags.ts";import { SocksProxyAgent } from "socks-proxy-agent";import { request as httpRequest } from "node:http";import { request as httpsRequest } from "node:https";@@ -835,7 +836,10 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {return true;}const deployment = await app.getDeployment(slug).catch(() => null);- const isPublic = deployment?.public === true;+ const externalAllowed = deployment+ ? await externalAppSharingAllowed(deps.featureFlags, deployment.ownerScopeId)+ : false;+ const isPublic = deployment?.public === true && externalAllowed;const sessionSecret = deps.deployAppsSessionSecret;const loginUrl = deps.deployAppsLoginUrl;const wantsHtml = ctx.method === "GET" && String(req.headers.accept ?? "").includes("text/html");@@ -882,6 +886,7 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {if (session?.appOnly) {await deps.identity?.refresh();if (+ externalAllowed &&deps.identity?.deactivationSource(sub) !== "manual" &&(await app.deploymentGrantees(deployment.id)).some((grant) => grant.scope === scopeId("personal", sub.trim().toLowerCase()) && grant.permission === "read",@@ -1531,8 +1536,10 @@ export async function getDeploymentShares(ctx: ApiCtx): Promise<void> {if (!deployment) return sendJson(res, 404, { error: "not_found" });if (deployment.ownerScopeId !== `personal:${capability.actorId}`)return sendJson(res, 403, { error: "forbidden", message: "Only the owner can edit app permissions." });+ const externalSharing = await externalAppSharingAllowed(ctx.deps.featureFlags, deployment.ownerScopeId);return sendJson(res, 200, {- public: deployment.public === true,+ public: deployment.public === true && externalSharing,+ externalSharing,grantees: await app.deploymentGrantees(deployment.id),});}@@ -1574,6 +1581,9 @@ export async function shareDeployment(ctx: ApiCtx): Promise<void> {} else if (/only the owner/.test(msg)) {status = 403;error = "forbidden";+ } else if (msg === EXTERNAL_APP_SHARING_OFF) {+ status = 403;+ error = "external_sharing_disabled";}return sendJson(res, status, { error, message: msg });}@@ -1632,9 +1642,10 @@ export async function shareDeployment(ctx: ApiCtx): Promise<void> {const msg = errMessage(e);let status = 400;if (/no such app/.test(msg)) status = 404;- else if (/only the owner/.test(msg)) status = 403;+ else if (/only the owner/.test(msg) || msg === EXTERNAL_APP_SHARING_OFF) status = 403;let error = "share_failed";if (status === 404) error = "not_found";+ else if (msg === EXTERNAL_APP_SHARING_OFF) error = "external_sharing_disabled";else if (status === 403) error = "forbidden";return sendJson(res, status, { error, message: msg });}diff --git a/src/deploy/deploy-service.ts b/src/deploy/deploy-service.tsindex 364772af8..6e0d66cda 100644--- a/src/deploy/deploy-service.ts+++ b/src/deploy/deploy-service.ts@@ -1,3 +1,4 @@+import { EXTERNAL_APP_SHARING_OFF } from "../feature-flags.ts";import { notifyDeploymentShared } from "./share-notice.ts";import type { DeliveryStore } from "../delivery/delivery-store.ts";import { EMBED_ANCESTORS_HINT, parseEmbedAncestors } from "./embed-ancestors.ts";@@ -104,6 +105,7 @@ export interface DeployService {permission: Permission | null,actor: { createdBy: string },): Promise<DeploymentGrantee[]>;+ assertShareAllowed(ownerScopeId: ScopeId, grantee: ScopeId, permission: Permission | null): Promise<void>;transferDeploymentOwner(idOrName: string,toScope: ScopeId,@@ -131,6 +133,7 @@ export interface DeployServiceDeps {canReadScope?: (principalId: string, scopeId: ScopeId) => Promise<boolean>;canWriteScope?: (principalId: string, scopeId: ScopeId) => Promise<boolean>;canManageEmail?: (email: string) => Promise<boolean>;+ externalSharingAllowed?: (ownerScopeId: ScopeId) => Promise<boolean>;managesArtifactHome?: (homeScopeId: ScopeId, createdBy: string, principalId: string) => Promise<boolean>;deploymentEnv?: (deployment: Deployment) => Promise<Record<string, string>>;}@@ -167,6 +170,14 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {const leaderLease = deps.leaderLease ?? createNoopLeaderLease();const advisoryLock = deps.advisoryLock ?? createNoopAdvisoryLock();const deployQueue = createKeyedQueue();+ const externalSharingAllowed = (ownerScopeId: ScopeId): Promise<boolean> =>+ deps.externalSharingAllowed?.(ownerScopeId) ?? Promise.resolve(false);+ async function assertShareAllowed(ownerScopeId: ScopeId, grantee: ScopeId, permission: Permission | null) {+ const { kind, ref } = parseScopeId(grantee);+ if (permission === null || kind !== "personal" || !ref?.includes("@")) return;+ if ((await deps.canManageEmail?.(ref)) || (await externalSharingAllowed(ownerScopeId))) return;+ throw new Error(EXTERNAL_APP_SHARING_OFF);+ }function withDeployLock<T>(id: string, fn: () => Promise<T>): Promise<T> {return deployQueue(id, () => advisoryLock.withLock(`deploy:${id}`, fn));}@@ -344,10 +355,12 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {share: NonNullable<DeployOrUpdateInput["share"]>,): Promise<void> {for (const s of share) {+ const granteeScopeId = await deploymentShareScope(s.scope, s.permission, deps.canManageEmail);+ await assertShareAllowed(d.ownerScopeId, granteeScopeId, s.permission);const grant: Grant = {ownerScopeId: d.ownerScopeId,ref: deploymentRef(d.id),- granteeScopeId: await deploymentShareScope(s.scope, s.permission, deps.canManageEmail),+ granteeScopeId,permission: s.permission,grantedBy: createdBy,};@@ -365,6 +378,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {return {providerProfile: deps.provider.profile,+ assertShareAllowed,async deploy(input) {if (input.name !== undefined) {@@ -578,6 +592,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {if (d.ownerScopeId !== scopeId("personal", actor.createdBy)) {throw new Error(`only the owner can change who can reach "${d.name ?? d.id}"`);}+ if (isPublic && !(await externalSharingAllowed(d.ownerScopeId))) throw new Error(EXTERNAL_APP_SHARING_OFF);await deps.deployStore.setPublic(d.id, isPublic);deps.auditLog.record({at: Date.now(),@@ -692,6 +707,14 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {async deployOrUpdate(input) {const { ownerScopeId, createdBy } = input;+ if (input.public === true && !(await externalSharingAllowed(ownerScopeId)))+ throw new Error(EXTERNAL_APP_SHARING_OFF);+ for (const s of input.share ?? [])+ await assertShareAllowed(+ ownerScopeId,+ await deploymentShareScope(s.scope, s.permission, deps.canManageEmail),+ s.permission,+ );if (input.embedAncestors !== undefined && !parseEmbedAncestors(input.embedAncestors))throw new Error(`embedAncestors must be an ${EMBED_ANCESTORS_HINT}`);@@ -824,6 +847,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {throw new Error(`only the owner can change who can reach "${d.name ?? d.id}"`);}grantee = await deploymentShareScope(grantee, permission, deps.canManageEmail);+ await assertShareAllowed(d.ownerScopeId, grantee, permission);const ref = deploymentRef(d.id);await deps.acl.revoke(d.ownerScopeId, ref, grantee, actor.createdBy);if (permission === null) {diff --git a/src/feature-flags.ts b/src/feature-flags.tsindex 2a91fd85e..ac12ae516 100644--- a/src/feature-flags.ts+++ b/src/feature-flags.ts@@ -7,6 +7,7 @@ export const FEATURE_NAMES = ["responsive_spine","inbox_loops","slack_loading_indicator",+ "external_app_sharing",] as const;export type FeatureName = (typeof FEATURE_NAMES)[number];@@ -55,3 +56,13 @@ export function createFeatureFlagStore(},};}++export const EXTERNAL_APP_SHARING_OFF =+ "sharing apps outside the organization is turned off; an org admin can enable the external_app_sharing flag";++export function externalAppSharingAllowed(+ flags: FeatureFlagStore | undefined,+ ownerScopeId: ScopeId,+): Promise<boolean> {+ return flags ? flags.enabled("external_app_sharing", ownerScopeId) : Promise.resolve(false);+}diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.tsindex 9784b290b..09f239507 100644--- a/src/harness/agent-tools.ts+++ b/src/harness/agent-tools.ts@@ -1143,7 +1143,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):"the app must listen on the PORT env var. `dir` is workspace-relative: use `app`, never a path " +"beginning with `/` or a redundant `workspace/app`. `renameFrom` takes an existing " +"deployment name, not its ID. Set audience to [] to suppress default audience grants, or supply " +- "publication-time grants. `public: true` makes the app reachable without sign-in; it is never the default. " ++ "publication-time grants. `public: true` makes the app reachable without sign-in; it is never the default and is refused unless an org admin has enabled external app sharing. " +"Use apps action share for subsequent grants. Share the full absolute URL " +"returned by apps action publish so it works in Slack and other surfaces. Use `name` for a friendly, " +"stable link /d/<name>/; `renameFrom` to rename; `rollbackTo` to flip back to an earlier version. " +diff --git a/src/wiring.ts b/src/wiring.tsindex e46a22146..5e95d36be 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -274,7 +274,12 @@ import {type DeviceFlowCutoverReset,type DeviceFlowCutoverStore,} from "./credentials/device-flow-cutover.ts";-import { createFeatureFlagStore, type FeatureFlagRecord, type FeatureFlagStore } from "./feature-flags.ts";+import {+ createFeatureFlagStore,+ externalAppSharingAllowed,+ type FeatureFlagRecord,+ type FeatureFlagStore,+} from "./feature-flags.ts";import { makeRefresh, type OAuthClientResolver, type OAuthState } from "./connectors/oauth.ts";import {createConnectorClientResolver,@@ -1740,12 +1745,14 @@ export function buildApp(advisoryLock,canReadScope,canWriteScope,+ externalSharingAllowed: (ownerScopeId) => externalAppSharingAllowed(featureFlags, ownerScopeId),canManageEmail: async (email) => {await identity.refresh();return (identity.isInternal(identity.classify(email)) &&((await directory.get(email))?.type === "internal" ||config.emailAuthPrincipals?.includes(email) ||+ Boolean(config.emailAuthDomain && email.endsWith(`@${config.emailAuthDomain}`)) ||identity.externalMember(email) !== undefined));},diff --git a/test/deploy-app-only.test.ts b/test/deploy-app-only.test.tsindex 0fc5e6c44..28517046f 100644--- a/test/deploy-app-only.test.ts+++ b/test/deploy-app-only.test.ts@@ -17,6 +17,9 @@ import { portalSession } from "../src/deploy/viewer-session.ts";import { deriveKey, seal } from "../plugins/portal/src/session.ts";import { scopeId } from "../src/types.ts";import { deployRef, encodeRef } from "../src/acl/resource-ref.ts";+import type { FeatureFlagStore } from "../src/feature-flags.ts";++const externalSharingOn = { enabled: async () => true } as unknown as FeatureFlagStore;const secret = "app-only-gateway-test-secret-long-enough";const guest = "[email protected]";@@ -42,6 +45,7 @@ test("app-only gateway checks exact current personal read grants without inheritawait new Promise<void>((resolve) => upstream.listen(0, "127.0.0.1", resolve));const acl = createAclStore();const deploy = createDeployService({+ externalSharingAllowed: async () => true,deployStore: createDeployStore({ git: { repoRoot: join(dir, "repos") } }),provider: {profile: { managedScaleToZero: false },@@ -82,6 +86,7 @@ test("app-only gateway checks exact current personal read grants without inheritthrow new Error("app-only must not consult inherited permission");};const server = createApiServer(app, {+ featureFlags: externalSharingOn,identity,signingSecret: secret,deployAppsDomain: "apps.example.test",diff --git a/test/deploy-subdomain-signin.test.ts b/test/deploy-subdomain-signin.test.tsindex 536007262..1b2839895 100644--- a/test/deploy-subdomain-signin.test.ts+++ b/test/deploy-subdomain-signin.test.ts@@ -17,6 +17,10 @@ import { createMemorySessionStore } from "../src/sessions/memory-session-store.timport { PORTAL_IDENTITY_HEADER } from "../src/auth/portal-identity.ts";import { portalSession } from "../src/deploy/viewer-session.ts";import { scopeId } from "../src/types.ts";+import type { FeatureFlagStore } from "../src/feature-flags.ts";++let externalSharing = true;+const externalSharingOn = { enabled: async () => externalSharing } as unknown as FeatureFlagStore;const auditLog = { record() {}, events: async () => [], tail: async () => [] };const SESSION_SECRET = "portal-session-secret";@@ -162,6 +166,7 @@ test("subdomain ingress: portal sign-in admits the owner, denies strangers, bounconst deployStore = createDeployStore();const deploy = createDeployService({+ externalSharingAllowed: async () => true,deployStore,provider: {profile: { managedScaleToZero: false },@@ -191,6 +196,7 @@ test("subdomain ingress: portal sign-in admits the owner, denies strangers, boundeliveries.push(input);};const server = createInsecureTestServer(app, {+ featureFlags: externalSharingOn,deployAppsDomain: "apps.example.com",deployGateSecret: "gate-secret",deployAppsSessionSecret: SESSION_SECRET,@@ -238,6 +244,12 @@ test("subdomain ingress: portal sign-in admits the owner, denies strangers, bounundefined,"a link-only public visitor stays anonymous even when a portal session cookie is present",);+ externalSharing = false;+ const lockedDown = await httpGet(port, "/consultants?x=1", { Host: host, Accept: "text/html,*/*" });+ assert.equal(lockedDown.status, 302, "with external sharing off, a stored public link requires sign-in");+ const lockedXhr = await httpGet(port, "/api/data", { Host: host, Accept: "application/json" });+ assert.equal(lockedXhr.status, 401);+ externalSharing = true;await app.setDeploymentPublic("mysite", false, { createdBy: "[email protected]" });const backFromLogin = await httpGet(port, "/consultants?x=1&dpl_signin=1", {@@ -352,6 +364,7 @@ test("subdomain ingress: portal sign-in admits the owner, denies strangers, bountest("subdomain ingress: without the session config the domain has no door — a 503, not a bounce", async () => {const deployStore = createDeployStore();const deploy = createDeployService({+ externalSharingAllowed: async () => true,deployStore,provider: {profile: { managedScaleToZero: false },@@ -377,6 +390,7 @@ test("subdomain ingress: without the session config the domain has no door — aname: "mysite",});const server = createInsecureTestServer(app, {+ featureFlags: externalSharingOn,deployAppsDomain: "apps.example.com",deployGateSecret: "gate-secret",});diff --git a/test/share-deployment.test.ts b/test/share-deployment.test.tsindex e049c5f71..343e1dfe6 100644--- a/test/share-deployment.test.ts+++ b/test/share-deployment.test.ts@@ -27,10 +27,16 @@ import type { CapabilityClaims } from "../src/auth/capability-token.ts";import type { RecipientResolution } from "../src/directory/directory-store.ts";import type { Sandbox, SandboxHandle } from "../src/sandbox/sandbox.ts";import { scopeId } from "../src/types.ts";+import type { FeatureFlagStore } from "../src/feature-flags.ts";++const externalSharingOn = { enabled: async () => true } as unknown as FeatureFlagStore;type Dir = { resolve: (orgId: string, q: string) => Promise<RecipientResolution> };-function makeDeploy(canManageEmail?: (email: string) => Promise<boolean>): { deploy: DeployService; acl: AclStore } {+function makeDeploy(+ canManageEmail?: (email: string) => Promise<boolean>,+ externalSharing = true,+): { deploy: DeployService; acl: AclStore } {const acl: AclStore = createAclStore();const deploy = createDeployService({deployStore: createDeployStore(),@@ -42,6 +48,7 @@ function makeDeploy(canManageEmail?: (email: string) => Promise<boolean>): { depauditLog: { record() {}, events: async () => [], tail: async () => [] },acl,...(canManageEmail ? { canManageEmail } : {}),+ externalSharingAllowed: async () => externalSharing,deployDir: mkdtempSync(join(tmpdir(), "share-api-")),});return { deploy, acl };@@ -60,7 +67,13 @@ function apiHarness(directory?: Dir) {const cap = (actorId: string, orgId = "acme"): CapabilityClaims =>({ actorId, orgId, scopeId: scopeId("personal", actorId), exp: 9_999_999_999 }) as CapabilityClaims;-function callShare(app: ReturnType<typeof createApp>, capability: CapabilityClaims | null, id: string, body: unknown) {+function callShare(+ app: ReturnType<typeof createApp>,+ capability: CapabilityClaims | null,+ id: string,+ body: unknown,+ featureFlags = externalSharingOn,+) {const out: { status?: number; body?: any } = {};const res = {writeHead(s: number) {@@ -70,7 +83,7 @@ function callShare(app: ReturnType<typeof createApp>, capability: CapabilityClaiout.body = d ? JSON.parse(d) : undefined;},};- const ctx = { res, app, params: { id }, body, capability } as unknown as ApiCtx;+ const ctx = { res, app, deps: { featureFlags }, params: { id }, body, capability } as unknown as ApiCtx;return shareDeployment(ctx).then(() => out);}@@ -85,6 +98,7 @@ function callManage(capability: CapabilityClaims | null,id: string,body: unknown,+ featureFlags = externalSharingOn,) {const out: { status?: number; body?: any } = {};const res = {@@ -95,7 +109,7 @@ function callManage(out.body = d ? JSON.parse(d) : undefined;},};- const ctx = { res, app, params: { id }, body, capability } as unknown as ApiCtx;+ const ctx = { res, app, deps: { featureFlags }, params: { id }, body, capability } as unknown as ApiCtx;return handle(ctx).then(() => out);}@@ -559,6 +573,78 @@ test("deployment public access is explicit, owner-only, and reversible", async (assert.equal((await app.getDeployment("public-toggle"))?.public, undefined);});+test("with external app sharing off, public links and outside emails are refused while org sharing still works", async () => {+ const { deploy } = makeDeploy(async (email) => email.endsWith("@acme.test"), false);+ const app = createApp({ deploy, identity: createIdentityService() } as unknown as Parameters<typeof createApp>[0]);+ const off = { enabled: async () => false } as unknown as FeatureFlagStore;+ await app.deploy({+ ownerScopeId: scopeId("personal", "U1"),+ createdBy: "U1",+ entrypoint: "x",+ files: [],+ name: "locked",+ });++ const shares = await callManage(getDeploymentShares, app, cap("U1"), "locked", {}, off);+ assert.equal(shares.body.externalSharing, false);++ const makePublic = await callShare(app, cap("U1"), "locked", { public: true }, off);+ assert.equal(makePublic.status, 403);+ assert.equal(makePublic.body.error, "external_sharing_disabled");+ assert.equal((await app.getDeployment("locked"))?.public, undefined);+ assert.equal((await callShare(app, cap("U1"), "locked", { public: false }, off)).status, 200);++ const outside = await callShare(app, cap("U1"), "locked", { email: "[email protected]" }, off);+ assert.equal(outside.status, 403);+ assert.equal(outside.body.error, "external_sharing_disabled");++ const member = await callShare(app, cap("U1"), "locked", { email: "[email protected]" }, off);+ assert.equal(member.status, 200);+ const org = await callShare(app, cap("U1"), "locked", { scope: "org" }, off);+ assert.equal(org.status, 200);+ assert.deepEqual((await deploy.deploymentGrantees("locked")).map((g) => g.scope).sort(), [+ "org:default-org",+ "personal:[email protected]",+ ]);++ await assert.rejects(+ deploy.deployOrUpdate({+ ownerScopeId: scopeId("personal", "U1"),+ createdBy: "U1",+ entrypoint: "x",+ files: [],+ name: "fresh",+ public: true,+ }),+ /external_app_sharing/,+ );+ assert.equal(await deploy.getDeployment("fresh"), null);+ await assert.rejects(+ deploy.deployOrUpdate({+ ownerScopeId: scopeId("personal", "U1"),+ createdBy: "U1",+ entrypoint: "x",+ files: [],+ name: "fresh-share",+ share: [{ scope: scopeId("personal", "[email protected]"), permission: "read" }],+ }),+ /external_app_sharing/,+ );+ assert.equal(await deploy.getDeployment("fresh-share"), null, "publish refuses outside shares before deploying");+ const d = (await app.getDeployment("locked"))!;+ await assert.rejects(+ app.grant({+ ownerScopeId: d.ownerScopeId,+ ref: `deployment:${d.id}`,+ granteeScopeId: scopeId("personal", "[email protected]"),+ permission: "read",+ grantedBy: "U1",+ }),+ /external_app_sharing/,+ );+ assert.ok(!(await deploy.deploymentGrantees("locked")).some((g) => g.scope === "personal:[email protected]"));+});+test("deployment permissions are visible only to the owner, including for managers", async () => {const { app } = apiHarness();await app.deploy({@@ -637,13 +723,13 @@ test("exact email read grants admit app-only login and guest reach without membeconst email = "[email protected]";await identity.deactivate(email, "directory-sync");assert.equal(identity.classify(email).type, "guest");- const allowed = async (email: string) => {+ const allowed = async (email: string, featureFlags = externalSharingOn) => {let status: number | undefined;let body: unknown;const handle = authBrokerRoutes.find((r) => "path" in r && r.path.endsWith("email-allowed"))!.handle;await handle({app,- deps: { identity, acl },+ deps: { identity, acl, featureFlags },url: new URL(`http://core/v1/auth/broker/email-allowed?email=${encodeURIComponent(email)}`),res: {writeHead(s: number) {@@ -660,6 +746,11 @@ test("exact email read grants admit app-only login and guest reach without membeassert.deepEqual(await allowed(email), { allowed: false });await app.shareDeployment(d.id, `personal:${email}`, "read", { createdBy: "U1" });assert.deepEqual(await allowed(" [email protected] "), { allowed: true, appOnly: true });+ assert.deepEqual(+ await allowed(email, { enabled: async () => false } as unknown as FeatureFlagStore),+ { allowed: false },+ "existing outside grants stop admitting sign-in while external sharing is off",+ );assert.deepEqual(await allowed("[email protected]"), { allowed: false });assert.equal(await app.effectiveDeploymentPermission(d, "[email protected]"), "read");assert.equal(await app.effectiveDeploymentPermission(d, "[email protected]"), null);