Multiplayer agent harness for work.
Allow opt-in public app sharing (#1571)
Joshua France0edd2377c193
diff --git a/plugins/chassis/src/external-members.ts b/plugins/chassis/src/external-members.tsindex 0e9d399d9..9cfaf2272 100644--- a/plugins/chassis/src/external-members.ts+++ b/plugins/chassis/src/external-members.ts@@ -4,12 +4,17 @@ import { errMessage } from "./errors.ts";const EMAIL_ALLOWED_PATH = "/v1/auth/broker/email-allowed";const EMAIL_ALLOWED_TIMEOUT_MS = 4_000;-export async function coreEmailAllowed(+export interface EmailAdmission {+ allowed: boolean;+ appOnly?: true;+}++export async function coreEmailAdmission(coreApiUrl: string,signingSecret: string | undefined,email: string,label = "chassis",-): Promise<boolean> {+): Promise<EmailAdmission> {const path = withSourceAuthNonce(`${EMAIL_ALLOWED_PATH}?email=${encodeURIComponent(email)}`, signingSecret);try {const r = await fetch(`${coreApiUrl}${path}`, {@@ -18,12 +23,23 @@ export async function coreEmailAllowed(});if (!r.ok) {console.error(`[${label}] core refused an external-member lookup: HTTP ${r.status}`);- return false;+ return { allowed: false };}- const parsed = (await r.json()) as { allowed?: unknown };- return parsed.allowed === true;+ const parsed = (await r.json()) as { allowed?: unknown; appOnly?: unknown };+ if (parsed.allowed !== true || (parsed.appOnly !== undefined && typeof parsed.appOnly !== "boolean"))+ return { allowed: false };+ return { allowed: true, ...(parsed.appOnly === true ? { appOnly: true } : {}) };} catch (e) {console.error(`[${label}] core external-member lookup failed: ${errMessage(e)}`);- return false;+ return { allowed: false };}}++export async function coreEmailAllowed(+ coreApiUrl: string,+ signingSecret: string | undefined,+ email: string,+ label = "chassis",+): Promise<boolean> {+ return (await coreEmailAdmission(coreApiUrl, signingSecret, email, label)).allowed;+}diff --git a/plugins/portal/src/desktop-login.ts b/plugins/portal/src/desktop-login.tsindex 5baf7aea1..5e723eafa 100644--- a/plugins/portal/src/desktop-login.ts+++ b/plugins/portal/src/desktop-login.ts@@ -15,6 +15,7 @@ export function mintDesktopLogin(challenge: string,state: string,) {+ if (session.appOnly) throw new Error("app-only sessions cannot sign in to the desktop");const now = Math.floor(Date.now() / 1000);return seal({@@ -51,6 +52,7 @@ export function openDesktopLogin(if (!p ||p.k !== "desktop-login" ||+ p.appOnly !== undefined ||p.aud !== origin ||p.org !== org ||typeof p.sub !== "string" ||diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.tsindex 25a92f974..a1f41c1d9 100644--- a/plugins/portal/src/index.ts+++ b/plugins/portal/src/index.ts@@ -56,7 +56,7 @@ import {} from "./proxy.ts";import { signedHeaders, withSourceAuthNonce } from "../../chassis/src/core-client.ts";import { coreClaimStore, claimOnce, withinRateLimit, ClaimStoreUnavailableError } from "../../chassis/src/claims.ts";-import { coreEmailAllowed } from "../../chassis/src/external-members.ts";+import { coreEmailAdmission } from "../../chassis/src/external-members.ts";import { mintPortalIdentity, PORTAL_IDENTITY_HEADER } from "../../chassis/src/portal-identity.ts";import { errMessage } from "../../chassis/src/errors.ts";import {@@ -207,6 +207,7 @@ export function clientIpOf(req: IncomingMessage): string {}const PRINCIPAL_RULE: PrincipalRule = {+ requireCoreAdmission: Boolean(AUTH_BROKER_UPSTREAM),claim: (process.env.OIDC_PRINCIPAL_CLAIM ?? "email") as PrincipalRule["claim"],allowedEmailDomain: process.env.OIDC_ALLOWED_EMAIL_DOMAIN || undefined,allowedEmails: process.env.OIDC_ALLOWED_EMAILS?.split(",")@@ -947,6 +948,7 @@ function renewSessionCookie(req: IncomingMessage, res: ServerResponse): SessionCSESSION_MAX_TTL_S,);if (!session) return null;+ if (session.appOnly) return session;const now = Math.floor(Date.now() / 1000);if (now - session.iat < SESSION_RENEW_AFTER_S) return session;const authenticatedAt = session.auth ?? session.iat;@@ -988,6 +990,16 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>return proxyToAppHost(req, res, CORE);}+ const brokerPath = brokerRouteFor(method, pathname);+ const reauthentication =+ (method === "GET" &&+ ["/auth/login", "/auth/callback", "/auth/trusted/login", "/auth/trusted/callback"].includes(pathname)) ||+ (method === "POST" && pathname === "/auth/logout") ||+ brokerPath !== null;+ if (currentSession(req)?.appOnly && !reauthentication) {+ return json(res, 403, { error: "app_only_session", message: "this sign-in only permits access to shared apps" });+ }+void refreshSurfaceConfig();if (method === "GET" && pathname === "/healthz") return json(res, 200, { ok: true });@@ -1056,7 +1068,6 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>return json(res, 200, { ok: true });}- const brokerPath = brokerRouteFor(method, pathname);if (brokerPath) {if (method !== "GET" && !sameOriginRequest(req))return json(res, 403, { error: "forbidden", message: "cross-origin request refused" });@@ -1591,7 +1602,7 @@ async function trustedAuth(req: IncomingMessage, res: ServerResponse, url: URL):}}-function setAuthenticatedSession(res: ServerResponse, sub: string, name = ""): void {+function setAuthenticatedSession(res: ServerResponse, sub: string, name = "", appOnly = false): void {const now = Math.floor(Date.now() / 1000);const session: SessionClaims = {k: "session",@@ -1601,6 +1612,7 @@ function setAuthenticatedSession(res: ServerResponse, sub: string, name = ""): viat: now,exp: now + SESSION_TTL_S,...(name ? { name } : {}),+ ...(appOnly ? { appOnly: true } : {}),};setSession(res, [...sessionCookieSet(seal(session, sessionKey), session.sub),@@ -1664,7 +1676,7 @@ async function authCallback(req: IncomingMessage, res: ServerResponse, url: URL)if (!code || !stateParam || !safeEqual(stateParam, tmp.state)) return fail("invalid login state");if (!consumeState(tmp.state)) return fail("login already used, please try again");- let sub: string;+ let principal: { sub: string; appOnly?: true };let name = "";try {const { accessToken, idToken } = await exchangeCode(OIDC, { code, codeVerifier: tmp.pkceVerifier });@@ -1677,8 +1689,8 @@ async function authCallback(req: IncomingMessage, res: ServerResponse, url: URL)const infoSub = typeof info.sub === "string" ? info.sub : "";if (!infoSub) throw new Error("userinfo missing sub");if (typeof claims.sub === "string" && claims.sub !== infoSub) throw new Error("subject mismatch");- sub = await resolvePrincipal(PRINCIPAL_RULE, { sub: infoSub, claims, userinfo: info }, (email) =>- coreEmailAllowed(CORE, CORE_SIGNING_SECRET, email, "portal"),+ principal = await resolvePrincipal(PRINCIPAL_RULE, { sub: infoSub, claims, userinfo: info }, (email) =>+ coreEmailAdmission(CORE, CORE_SIGNING_SECRET, email, "portal"),);const rawName = info.name ?? claims.name;if (typeof rawName === "string") name = rawName.trim().slice(0, 200);@@ -1686,7 +1698,7 @@ async function authCallback(req: IncomingMessage, res: ServerResponse, url: URL)return fail(errMessage(e, "sign-in failed"));}- setAuthenticatedSession(res, sub, name);+ setAuthenticatedSession(res, principal.sub, name, principal.appOnly);res.writeHead(302, {location: sanitizeReturnTo(tmp.returnTo, PUBLIC_URL, APPS_DOMAIN),"cache-control": "no-store",diff --git a/plugins/portal/src/oidc.ts b/plugins/portal/src/oidc.tsindex dbd980f22..4739f84bb 100644--- a/plugins/portal/src/oidc.ts+++ b/plugins/portal/src/oidc.ts@@ -1,3 +1,4 @@+import type { EmailAdmission } from "../../chassis/src/external-members.ts";import { createHash, randomBytes } from "node:crypto";import { createRemoteJWKSet, customFetch, jwtVerify, type JWTPayload } from "jose";@@ -133,6 +134,7 @@ export interface PrincipalRule {claim: "sub" | "email";allowedEmailDomain?: string;allowedEmails?: readonly string[];+ requireCoreAdmission?: boolean;}type PrincipalArgs = { sub: string; claims: Record<string, unknown>; userinfo: Record<string, unknown> };@@ -156,17 +158,24 @@ function envRefusal(rule: PrincipalRule, email: string, args: PrincipalArgs): stexport async function resolvePrincipal(rule: PrincipalRule,args: PrincipalArgs,- invited: (email: string) => Promise<boolean> = async () => false,-): Promise<string> {- if (rule.claim === "sub") return args.sub;+ invited: (email: string) => Promise<EmailAdmission> = async () => ({ allowed: false }),+): Promise<{ sub: string; appOnly?: true }> {+ if (rule.claim === "sub" && !rule.requireCoreAdmission) return { sub: args.sub };const rawEmail = args.userinfo.email;if (typeof rawEmail !== "string" || !rawEmail.includes("@")) throw new Error("identity provider returned no email");const verified = args.userinfo.email_verified;if (verified !== true && verified !== "true") throw new Error("email is not verified by the identity provider");const email = rawEmail.trim().toLowerCase();const refusal = envRefusal(rule, email, args);- if (refusal && !(await invited(email))) throw new Error(refusal);- return email;+ if (refusal || rule.requireCoreAdmission) {+ const admission = await invited(email);+ if (!admission.allowed) throw new Error(refusal ?? "account is not permitted");+ return {+ sub: admission.appOnly || rule.claim === "email" ? email : args.sub,+ ...(admission.appOnly ? { appOnly: true } : {}),+ };+ }+ return { sub: email };}async function readJson(r: Response, what: string): Promise<Record<string, unknown>> {diff --git a/plugins/portal/src/session.ts b/plugins/portal/src/session.tsindex f85d7c958..19570ef1b 100644--- a/plugins/portal/src/session.ts+++ b/plugins/portal/src/session.ts@@ -33,6 +33,7 @@ export interface SessionClaims {name?: string;auth?: number;anon?: boolean;+ appOnly?: boolean;iat: number;exp: number;}@@ -74,6 +75,7 @@ export function openSession(typeof p.exp !== "number")return null;+ if (p.appOnly !== undefined && typeof p.appOnly !== "boolean") return null;if (expectedOrg !== undefined && p.org !== expectedOrg) return null;if (now >= p.exp * 1000) return null;const authenticatedAt = typeof p.auth === "number" ? p.auth : p.iat;diff --git a/plugins/portal/test/app-only.test.ts b/plugins/portal/test/app-only.test.tsnew file mode 100644index 000000000..c4708792f--- /dev/null+++ b/plugins/portal/test/app-only.test.ts@@ -0,0 +1,232 @@+import test from "node:test";+import assert from "node:assert/strict";+import { createServer, request } from "node:http";+import type { AddressInfo } from "node:net";+import { generateKeyPair, exportJWK, SignJWT } from "jose";+import { deriveKey, open, seal, readCookie } from "../src/session.ts";+import { coreEmailAdmission, coreEmailAllowed } from "../../chassis/src/external-members.ts";++const secret = "app-only-session-test-secret";+const origin = "http://portal.test";+const sessionKey = deriveKey(secret, "portal.session.v1");+const tmpKey = deriveKey(secret, "portal.tmp.v1");+const { publicKey, privateKey } = await generateKeyPair("EdDSA");+const jwk = { ...(await exportJWK(publicKey)), kid: "test-key" };+let admission: unknown = { allowed: true, appOnly: true };+let coreStatus = 200;+let nonce = "";+const email = "[email protected]";+const seen: Array<{ path: string; headers: Record<string, unknown> }> = [];+const upstream = createServer((req, res) => {+ void (async () => {+ const path = new URL(req.url!, origin).pathname;+ res.setHeader("content-type", "application/json");+ if (path === "/keys") return void res.end(JSON.stringify({ keys: [jwk] }));+ if (path === "/token") {+ const idToken = await new SignJWT({ nonce })+ .setProtectedHeader({ alg: "EdDSA", kid: "test-key" })+ .setIssuer(upstreamUrl)+ .setAudience("portal-client")+ .setSubject("idp-subject")+ .setIssuedAt()+ .setExpirationTime("2m")+ .sign(privateKey);+ return void res.end(JSON.stringify({ access_token: "test-access", id_token: idToken }));+ }+ if (path === "/userinfo") return void res.end(JSON.stringify({ sub: "idp-subject", email, email_verified: true }));+ if (path === "/v1/auth/broker/email-allowed") {+ res.statusCode = coreStatus;+ return void res.end(JSON.stringify(admission));+ }+ seen.push({ path, headers: req.headers });+ res.end(JSON.stringify({ path, headers: req.headers }));+ })().catch(() => {+ res.statusCode = 500;+ res.end();+ });+});+await new Promise<void>((resolve) => upstream.listen(0, "127.0.0.1", resolve));+const upstreamUrl = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`;+Object.assign(process.env, {+ NODE_ENV: "test",+ PORTAL_PUBLIC_URL: origin,+ PORTAL_SESSION_SECRET: secret,+ CORE_ORG_ID: "acme",+ CORE_SIGNING_SECRET: "app-only-core-secret",+ CORE_API_URL: upstreamUrl,+ WEB_UI_UPSTREAM: upstreamUrl,+ ADMIN_UPSTREAM: upstreamUrl,+ AUTH_BROKER_UPSTREAM: upstreamUrl,+ PORTAL_APPS_DOMAIN: "apps.example.test",+ OIDC_ISSUER: upstreamUrl,+ OIDC_AUTH_ENDPOINT: `${upstreamUrl}/authorize`,+ OIDC_TOKEN_ENDPOINT: `${upstreamUrl}/token`,+ OIDC_USERINFO_ENDPOINT: `${upstreamUrl}/userinfo`,+ OIDC_JWKS_URI: `${upstreamUrl}/keys`,+ OIDC_CLIENT_ID: "portal-client",+ OIDC_CLIENT_SECRET: "client-secret",+ OIDC_ALLOWED_EMAILS: "",+ OIDC_ALLOWED_EMAIL_DOMAIN: "",+ OIDC_PRINCIPAL_CLAIM: "email",+ PORTAL_LOCAL_AUTH_BYPASS: "0",+ PORTAL_PLAYGROUND: "0",+ PORTAL_SESSION_RENEW_AFTER_S: "1",+});+const { server } = await import("../src/index.ts");+await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+test.after(() => {+ server.close();+ upstream.close();+});++function appCookie() {+ const now = Math.floor(Date.now() / 1000);+ return `portal_session=${seal({ k: "session", sub: email, org: "acme", appOnly: true, iat: now - 7200, exp: now + 3600 }, sessionKey)}`;+}+async function signIn(cookie = "") {+ const login = await fetch(`${base}/auth/login?returnTo=${encodeURIComponent("https://demo.apps.example.test/")}`, {+ headers: { cookie },+ redirect: "manual",+ });+ assert.equal(login.status, 302);+ const tmpCookie = login.headers+ .getSetCookie()+ .find((c) => c.startsWith("portal_oidc_tmp="))!+ .split(";")[0]!;+ const tmp = open(readCookie(tmpCookie, "portal_oidc_tmp"), tmpKey)!;+ nonce = tmp.nonce as string;+ return fetch(`${base}/auth/callback?code=test&state=${tmp.state}`, {+ headers: { cookie: `${tmpCookie}; ${cookie}` },+ redirect: "manual",+ });+}++test("core lookup preserves app-only admission and boolean broker compatibility", async () => {+ admission = { allowed: true, appOnly: true };+ assert.deepEqual(await coreEmailAdmission(upstreamUrl, undefined, email), admission);+ assert.equal(await coreEmailAllowed(upstreamUrl, undefined, email), true);+ admission = { allowed: true };+ assert.deepEqual(await coreEmailAdmission(upstreamUrl, undefined, email), admission);+ for (const invalid of [{ allowed: false, appOnly: true }, { allowed: true, appOnly: "true" }, null]) {+ admission = invalid;+ assert.deepEqual(await coreEmailAdmission(upstreamUrl, undefined, email), { allowed: false });+ }+ coreStatus = 503;+ assert.deepEqual(await coreEmailAdmission(upstreamUrl, undefined, email), { allowed: false });+ coreStatus = 200;+});++test("OIDC callback seals core app-only authority; ordinary admission stays ordinary", async () => {+ for (const appOnly of [true, false]) {+ admission = { allowed: true, ...(appOnly ? { appOnly: true } : {}) };+ const response = await signIn();+ assert.equal(response.status, 302);+ assert.equal(response.headers.get("location"), "https://demo.apps.example.test/");+ const session = open(+ readCookie(+ response.headers.getSetCookie().find((c) => c.startsWith("portal_session=")),+ "portal_session",+ ),+ sessionKey,+ )!;+ assert.equal(session.sub, email);+ assert.equal(session.appOnly, appOnly || undefined);+ }+ admission = { allowed: false };+ const denied = await signIn(appCookie());+ assert.equal(denied.status, 400);+ assert.equal(+ denied.headers.getSetCookie().some((c) => c.startsWith("portal_session=")),+ false,+ );+});++test("app-only sessions cannot reach or renew on any ordinary portal surface", async () => {+ const paths = [+ "/",+ "/admin/",+ "/admin/api/whoami",+ "/api/whoami",+ "/api/sessions",+ "/api/deliveries/events",+ "/ws",+ "/v1/status",+ "/v1/deployments",+ "/d/demo/",+ "/app-edit/demo",+ "/auth/desktop",+ "/auth/desktop/redeem",+ "/auth/invite",+ "/auth/admin-login",+ "/auth/impersonate",+ "/auth/impersonate/stop",+ "/idp/token",+ ];+ for (const path of paths) {+ for (const method of ["GET", "POST"]) {+ const response = await fetch(`${base}${path}?appOnly=false`, {+ method,+ headers: { cookie: appCookie(), origin, "x-as-principal": "admin", "x-portal-identity": "forged" },+ redirect: "manual",+ });+ assert.equal(response.status, 403, `${method} ${path}`);+ assert.deepEqual(await response.json(), {+ error: "app_only_session",+ message: "this sign-in only permits access to shared apps",+ });+ assert.equal(response.headers.get("set-cookie"), null, "no renewal or broader session");+ }+ }+ assert.equal(+ seen.some((r) => paths.includes(r.path)),+ false,+ );+});++test("app-only websocket upgrades are refused before any upstream request", async () => {+ await new Promise<void>((resolve, reject) => {+ const req = request(+ `${base}/ws`,+ { headers: { cookie: appCookie(), connection: "Upgrade", upgrade: "websocket" } },+ (res) => {+ assert.equal(res.statusCode, 403);+ res.resume();+ res.on("end", resolve);+ },+ );+ req.on("upgrade", (_res, socket) => {+ socket.destroy();+ reject(new Error("unexpected upgrade"));+ });+ req.on("error", reject);+ req.end();+ });+});++test("app-only cookies reach only the app gateway and retain logout and reauthentication", async () => {+ const cookie = appCookie();+ const forwarded = await new Promise<{ headers: Record<string, string> }>((resolve, reject) => {+ const req = request(`${base}/api/private`, { headers: { host: "demo.apps.example.test", cookie } }, (res) => {+ assert.equal(res.statusCode, 200);+ let body = "";+ res.on("data", (chunk) => {+ body += chunk;+ });+ res.on("end", () => resolve(JSON.parse(body)));+ });+ req.on("error", reject);+ req.end();+ });+ assert.equal(forwarded.headers["x-qm-app-host"], "1");+ assert.equal(forwarded.headers.cookie, cookie);+ assert.equal(forwarded.headers["x-portal-identity"], undefined);+ for (const path of ["/idp/authorize", "/idp/verify"]) {+ assert.equal((await fetch(`${base}${path}`, { headers: { cookie: appCookie() } })).status, 200);+ }+ admission = { allowed: true, appOnly: true };+ assert.equal((await signIn(appCookie())).status, 302);+ const logout = await fetch(`${base}/auth/logout`, { method: "POST", headers: { cookie: appCookie(), origin } });+ assert.equal(logout.status, 200);+ assert.match(logout.headers.get("set-cookie")!, /portal_session=;/);+});diff --git a/plugins/portal/test/desktop-login.test.ts b/plugins/portal/test/desktop-login.test.tsindex 2abd1bd6f..cd6bc2887 100644--- a/plugins/portal/test/desktop-login.test.ts+++ b/plugins/portal/test/desktop-login.test.ts@@ -202,3 +202,13 @@ test("desktop handoff renews a browser session near expiry without resetting itsassert.equal(effective?.session.auth, oldBrowser.auth);assert.ok(effective && effective.session.exp >= testNow + 604_800);});++test("app-only sessions cannot mint desktop sessions", async () => {+ assert.throws(() => mintDesktopLogin({ ...browser, appOnly: true }, secret, origin, challenge, state), /app-only/);+ const appCookie = `portal_session=${seal({ ...browser, appOnly: true }, deriveKey(secret, "portal.session.v1"))}`;+ for (const method of ["GET", "POST"]) {+ const response = await fetch(`${base}${requestPath}`, { method, headers: { origin, cookie: appCookie } });+ assert.equal(response.status, 403);+ assert.equal(response.headers.get("set-cookie"), null);+ }+});diff --git a/plugins/portal/test/oidc.test.ts b/plugins/portal/test/oidc.test.tsindex 0239c7d8c..bb6e65ad6 100644--- a/plugins/portal/test/oidc.test.ts+++ b/plugins/portal/test/oidc.test.ts@@ -174,9 +174,9 @@ test("verifyIdToken requires a valid signature, issuer, audience, subject, nonce});test("resolvePrincipal claim=sub returns the subject untouched", async () => {- assert.equal(+ assert.deepEqual(await resolvePrincipal({ claim: "sub" }, { sub: "U1", claims: {}, userinfo: { email: "[email protected]" } }),- "U1",+ { sub: "U1" },);});@@ -185,7 +185,7 @@ test("resolvePrincipal claim=email returns the verified email, normalized", asyn{ claim: "email" },{ sub: "g-123", claims: {}, userinfo: { email: " [email protected] ", email_verified: true } },);- assert.equal(got, "[email protected]");+ assert.deepEqual(got, { sub: "[email protected]" });});test("resolvePrincipal claim=email requires the verified userinfo response", async () => {@@ -220,7 +220,7 @@ test("resolvePrincipal allowedEmailDomain gates the email suffix and the hd claiclaims: {},userinfo: { email: "[email protected]", email_verified: true, hd: "example.com" },});- assert.equal(ok, "[email protected]");+ assert.deepEqual(ok, { sub: "[email protected]" });await assert.rejects(resolvePrincipal(rule, { sub: "g", claims: {}, userinfo: { email: "[email protected]", email_verified: true } }),/permitted domain/,@@ -245,13 +245,13 @@ test("resolvePrincipal allowedEmailDomain gates the email suffix and the hd claitest("resolvePrincipal allowedEmails permits only the seeded verified addresses", async () => {const rule = { claim: "email" as const, allowedEmails: ["[email protected]"] };- assert.equal(+ assert.deepEqual(await resolvePrincipal(rule, {sub: "g",claims: {},userinfo: { email: "[email protected]", email_verified: true },}),- "[email protected]",+ { sub: "[email protected]" },);await assert.rejects(resolvePrincipal(rule, { sub: "g", claims: {}, userinfo: { email: "[email protected]", email_verified: true } }),@@ -262,9 +262,9 @@ test("resolvePrincipal allowedEmails permits only the seeded verified addresses"test("resolvePrincipal admits an invited external address that the env rules reject", async () => {const rule = { claim: "email" as const, allowedEmailDomain: "example.com", allowedEmails: ["[email protected]"] };const asked: string[] = [];- const invited = async (email: string): Promise<boolean> => {+ const invited = async (email: string): Promise<{ allowed: boolean }> => {asked.push(email);- return email === "[email protected]";+ return { allowed: email === "[email protected]" };};const verified = (email: string, extra: Record<string, unknown> = {}) => ({sub: "g",@@ -272,14 +272,16 @@ test("resolvePrincipal admits an invited external address that the env rules rejuserinfo: { email, email_verified: true, ...extra },});- assert.equal(await resolvePrincipal(rule, verified("[email protected]"), invited), "[email protected]");+ assert.deepEqual(await resolvePrincipal(rule, verified("[email protected]"), invited), { sub: "[email protected]" });assert.deepEqual(asked, [], "an address the env rules permit never consults core");- assert.equal(await resolvePrincipal(rule, verified(" [email protected] "), invited), "[email protected]");+ assert.deepEqual(await resolvePrincipal(rule, verified(" [email protected] "), invited), {+ sub: "[email protected]",+ });assert.deepEqual(asked, ["[email protected]"], "core is asked with the normalized address");- assert.equal(+ assert.deepEqual(await resolvePrincipal(rule, verified("[email protected]", { hd: "partner.test" }), invited),- "[email protected]",+ { sub: "[email protected]" },"a foreign hd claim does not block an invited address",);@@ -308,3 +310,34 @@ test("resolvePrincipal admits an invited external address that the env rules rej/core down/,);});++test("resolvePrincipal preserves deployment-only admission and fails closed for broker logins", async () => {+ const args = { sub: "idp-subject", claims: {}, userinfo: { email: " [email protected] ", email_verified: true } };+ for (const claim of ["email", "sub"] as const) {+ const rule = { claim, requireCoreAdmission: true };+ assert.deepEqual(await resolvePrincipal(rule, args, async () => ({ allowed: true, appOnly: true })), {+ sub: "[email protected]",+ appOnly: true,+ });+ assert.deepEqual(await resolvePrincipal(rule, args, async () => ({ allowed: true })), {+ sub: claim === "sub" ? "idp-subject" : "[email protected]",+ });+ await assert.rejects(+ resolvePrincipal(rule, args, async () => ({ allowed: false })),+ /not permitted/,+ );+ await assert.rejects(+ resolvePrincipal(rule, args, async () => {+ throw new Error("offline");+ }),+ /offline/,+ );+ }+ assert.deepEqual(+ await resolvePrincipal({ claim: "email", allowedEmailDomain: "example.com" }, args, async () => ({+ allowed: true,+ appOnly: true,+ })),+ { sub: "[email protected]", appOnly: true },+ );+});diff --git a/plugins/portal/test/session.test.ts b/plugins/portal/test/session.test.tsindex a29a928b9..059e0bb43 100644--- a/plugins/portal/test/session.test.ts+++ b/plugins/portal/test/session.test.ts@@ -282,3 +282,13 @@ for (const domain of [undefined, "example.test"]) {);});}++test("openSession preserves signed app-only authority and rejects malformed markers", () => {+ const now = Math.floor(Date.now() / 1000);+ const claims = { k: "session", sub: "[email protected]", org: "acme", iat: now, exp: now + 3600 };+ assert.equal(openSession(seal({ ...claims, appOnly: true }, sessionKey), sessionKey, Date.now())?.appOnly, true);+ assert.equal(openSession(seal(claims, sessionKey), sessionKey, Date.now())?.appOnly, undefined);+ for (const appOnly of ["true", "false", 1, 0, null, {}]) {+ assert.equal(openSession(seal({ ...claims, appOnly }, sessionKey), sessionKey, Date.now()), null);+ }+});diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex 509c3b5d6..e091f9a02 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -2227,13 +2227,25 @@ const apiRoutes: readonly WebRoute[] = [method: "POST",path: "/api/deployments/:id/share",handle: async ({ req, res, params }) => {- const body = await readJson<{ scope?: unknown; recipient?: unknown; access?: unknown }>(req, res, false);+ const body = await readJson<{+ scope?: unknown;+ recipient?: unknown;+ email?: unknown;+ access?: unknown;+ public?: unknown;+ }>(req, res, false);if (!body) return;return relayCap(res,"POST",`/v1/deployments/${encodeURIComponent(params.id!)}/share`,- JSON.stringify({ scope: body.scope, recipient: body.recipient, access: body.access }),+ JSON.stringify({+ scope: body.scope,+ recipient: body.recipient,+ email: body.email,+ access: body.access,+ public: body.public,+ }),);},},diff --git a/plugins/web-ui/src/deploy-permissions.ts b/plugins/web-ui/src/deploy-permissions.tsindex 532dc66af..594eceeb5 100644--- a/plugins/web-ui/src/deploy-permissions.ts+++ b/plugins/web-ui/src/deploy-permissions.ts@@ -1,6 +1,6 @@import { html, render, nothing } from "lit";import { live } from "lit/directives/live.js";-import { Search, X } from "lucide";+import { Globe, Lock, Search, X } from "lucide";import { api } from "./core-bridge";import { closeFormMenus, icon, initials, menuSelect } from "./ui";import { scopeChip } from "./contexts";@@ -20,10 +20,11 @@ export async function openDeploymentPermissions(id: string, title: string, ownerdialog.setAttribute("aria-labelledby", "deployment-permissions-heading");document.body.append(dialog);let grantees: Grant[] = [];+ let publicAccess = false;let matches: DirectoryMatch[] = [];let query = "";let access = "view";- let selected: DirectoryMatch | null = null;+ let selected: (DirectoryMatch & { email?: string }) | null = null;let searchSequence = 0;let timer: ReturnType<typeof setTimeout> | undefined;let searching = false;@@ -46,18 +47,24 @@ export async function openDeploymentPermissions(id: string, title: string, ownerif (closeFormMenus()) return;close();});- const change = async (scope: string, value: string) => {+ const change = async (scope: string, value: string, email?: string) => {if (busy) return;closeFormMenus();busy = true;error = "";draw();try {- const response = await api<{ grantees: Grant[] }>(endpoint, {- method: "POST",- body: JSON.stringify({ scope, access: value }),- });+ const response = await api<{ public: boolean; grantees: Grant[]; invitation?: { emailProblem?: string } }>(+ endpoint,+ {+ method: "POST",+ body: JSON.stringify({ ...(email ? { email } : { scope }), access: value }),+ },+ );+ publicAccess = response.public;grantees = response.grantees;+ if (response.invitation?.emailProblem)+ error = `Access granted, but no invitation email was sent: ${response.invitation.emailProblem}`;selected = null;query = "";searched = false;@@ -70,6 +77,26 @@ export async function openDeploymentPermissions(id: string, title: string, ownerif (dialog.isConnected) draw();}};+ const changePublic = async (value: string) => {+ if (busy) 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;+ } catch (e) {+ error = errMessage(e, "Could not update public access.");+ } finally {+ busy = false;+ if (dialog.isConnected) draw();+ }+ };const search = async () => {const sequence = ++searchSequence;const term = query.trim();@@ -105,6 +132,17 @@ export async function openDeploymentPermissions(id: string, title: string, owner}}};+ const emailCandidate = (): string | null => {+ const email = query.trim().toLowerCase();+ if (email.length > 254 || !/^[^@\s,;<>"]+@[^@\s,;<>"]+\.[^@\s,;<>"]+$/.test(email)) return null;+ if (+ owner.toLowerCase() === `personal:${email}` ||+ grantees.some((g) => g.scope.toLowerCase() === `personal:${email}`)+ )+ return null;+ if (matches.some((m) => m.principalId.toLowerCase() === email)) return null;+ return email;+ };const permissionMenu = (value: string, label: string, update: (value: string) => void, removable = false) =>html`<fieldset class="permission-control" ?disabled=${busy}>${menuSelect({@@ -154,16 +192,24 @@ export async function openDeploymentPermissions(id: string, title: string, owner${icon(X, 14)}</button><div class="permission-invite-actions">- ${permissionMenu(access, "New person's access", (value) => {- access = value;- draw();- })}<button+ ${+ selected.email+ ? html`<span class="permission-note">Can view</span>`+ : permissionMenu(access, "New person's access", (value) => {+ access = value;+ draw();+ })+ }<buttonclass="btn primary"?disabled=${busy}@click=${() => {if (selected) {names.set(`personal:${selected.principalId}`, selected.displayName);- void change(`personal:${selected.principalId}`, access);+ void change(+ `personal:${selected.principalId}`,+ selected.email ? "view" : access,+ selected.email,+ );}}}>@@ -182,10 +228,10 @@ export async function openDeploymentPermissions(id: string, title: string, owner${icon(Search, 16)}<inputid="app-people-query"aria-label="Add people"- placeholder="Add people by name or handle"+ placeholder="Add people by name or email"type="search"autocomplete="off"- maxlength="80"+ maxlength="254".value=${live(query)}?disabled=${busy}@input=${(event: Event) => {@@ -203,8 +249,33 @@ export async function openDeploymentPermissions(id: string, title: string, ownercloseFormMenus();draw();})}+ ${+ !searching && searched && emailCandidate()+ ? html`+ <button+ class="project-member-result"+ type="button"+ ?disabled=${busy}+ @click=${() => {+ const email = emailCandidate();+ if (!email) return;+ selected = { principalId: email, displayName: email, type: "guest", email };+ access = "view";+ closeFormMenus();+ draw();+ }}+ >+ Add ${emailCandidate()} with view access+ </button>+ <p class="permission-note">+ They receive an app link by email and sign in with this address. This does not add+ them to your organization.+ </p>+ `+ : nothing+ }${searching ? html`<p class="permission-note" role="status">Searching…</p>` : nothing}- ${!searching && searched && !matches.length ? html`<p class="permission-note">No additional people found.</p>` : nothing}+ ${!searching && searched && !matches.length && !emailCandidate() ? html`<p class="permission-note">No additional people found.</p>` : nothing}</form>`}</div>`@@ -220,6 +291,34 @@ export async function openDeploymentPermissions(id: string, title: string, owner</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>`)}</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+ >${publicAccess ? "No sign-in required" : "Only people with access can open"}</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" },+ ],+ onSelect: (next) => {+ if (next) void changePublic(next);+ },+ })}+ </fieldset>+ </div>+ </div>+ ${+ publicAccess+ ? html`<p class="share-external-warning" role="status">⚠️ Public. Anyone can open this app.</p>`+ : nothing+ }${busy ? html`<p role="status">Loading…</p>` : nothing}${error ? html`<p class="composer-error" role="alert">${error}</p>` : nothing}<div class="project-dialog-actions actions"><button class="btn" @click=${close}>Done</button></div>@@ -229,7 +328,9 @@ export async function openDeploymentPermissions(id: string, title: string, ownerdraw();dialog.showModal();try {- grantees = (await api<{ grantees: Grant[] }>(endpoint)).grantees;+ const response = await api<{ public: boolean; grantees: Grant[] }>(endpoint);+ publicAccess = response.public;+ grantees = response.grantees;loaded = true;} catch (e) {error = errMessage(e, "Could not load permissions.");diff --git a/plugins/web-ui/src/deploy-view.ts b/plugins/web-ui/src/deploy-view.tsindex 4e6dc2a10..4aaa36595 100644--- a/plugins/web-ui/src/deploy-view.ts+++ b/plugins/web-ui/src/deploy-view.ts@@ -19,6 +19,7 @@ export interface DeploymentView {displayName?: string;permission?: "read" | "write";embedAncestors?: string[];+ public?: boolean;createdAt?: number;updatedAt?: number;lastAccessAt?: number;diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.cssindex b193d5b48..9a4c8de74 100644--- a/plugins/web-ui/src/shell.css+++ b/plugins/web-ui/src/shell.css@@ -12269,6 +12269,9 @@ body.app-edit-embed .custom-chat-shell.app-edit-chat > .chat-bottom-dock {.permission-search .project-member-results:not(:has(button)) {display: none;}+.permission-general-label {+ margin-top: 20px;+}.permission-section-label {font-size: 11px;font-weight: 500;diff --git a/plugins/web-ui/test/deploy-permissions-source.test.ts b/plugins/web-ui/test/deploy-permissions-source.test.tsnew file mode 100644index 000000000..b63ae81a4--- /dev/null+++ b/plugins/web-ui/test/deploy-permissions-source.test.ts@@ -0,0 +1,24 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++const source = readFileSync(new URL("../src/deploy-permissions.ts", import.meta.url), "utf8");++test("app permissions expose explicit private and public general-access states", () => {+ assert.match(source, /General access/);+ 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, /Public\. Anyone can open this app\./);+});++test("app permissions offer explicit view-only email grants outside the directory", () => {+ assert.match(source, /Add people by name or email/);+ assert.match(source, /emailCandidate/);+ assert.match(source, /Add \$\{emailCandidate\(\)\} with view access/);+ assert.match(source, /selected\.email \? "view" : access/);+ assert.match(source, /email \? \{ email \} : \{ scope \}/);+ assert.match(source.replace(/\s+/g, " "), /This does not add them to your organization/);+ assert.match(source, /Access granted, but no invitation email was sent/);+});diff --git a/plugins/web-ui/test/deployments-server-route.test.ts b/plugins/web-ui/test/deployments-server-route.test.tsindex 03b4906b8..c379ae64d 100644--- a/plugins/web-ui/test/deployments-server-route.test.ts+++ b/plugins/web-ui/test/deployments-server-route.test.ts@@ -115,10 +115,21 @@ test("deployment sharing uses the signed-in capability and drops caller identity).status,200,);+ assert.equal(+ (+ await fetch(`${base}/api/deployments/d1/share`, {+ method: "POST",+ headers,+ body: JSON.stringify({ public: true, actorId: "mallory", principalId: "mallory" }),+ })+ ).status,+ 200,+ );const requests = calls.slice(before).filter((call) => call.url === "/v1/deployments/d1/share");- assert.equal(requests.length, 2);+ assert.equal(requests.length, 3);assert.ok(requests.every((call) => call.capability === "signed-in-user-capability"));assert.deepEqual(requests[1]?.body, { scope: "personal:bob", access: "view" });+ assert.deepEqual(requests[2]?.body, { public: true });});test("embed-ancestors relays the origin list and never invents one", async () => {@@ -161,3 +172,16 @@ test("embed-ancestors relays the origin list and never invents one", async () =>.find((call) => call.method === "POST" && isNoncedCoreCall(call.url, "/v1/deployments/d1/embed-ancestors"));assert.deepEqual(coercedCall?.body, { embedAncestors: [] });});++test("deployment share bridge forwards an exact email without caller identity", async () => {+ const before = calls.length;+ const r = await fetch(`${base}/api/deployments/d1/share`, {+ method: "POST",+ headers,+ body: JSON.stringify({ email: "[email protected]", access: "view", actorId: "mallory", principalId: "mallory" }),+ });+ assert.equal(r.status, 200);+ const request = calls.slice(before).find((call) => call.url === "/v1/deployments/d1/share");+ assert.deepEqual(request?.body, { email: "[email protected]", access: "view" });+ assert.equal(request?.capability, "signed-in-user-capability");+});diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.tsindex e6e078ce6..f66b768de 100644--- a/src/api/agent-api-catalog.ts+++ b/src/api/agent-api-catalog.ts@@ -381,7 +381,7 @@ const FAMILIES: AgentApiFamily[] = [method: "POST",path: "/v1/share",summary:- 'share or move one of YOUR artifacts to another context — body {type:"file"|"skill"|"deploy"|"cron", id, toScope:"org"|<scope id>|a teammate\'s name, permission?:"read"(default)|"write", move?:false}. Default (share) adds a grant — the artifact keeps its home and creator. move:true changes its home scope instead (skills only today). Frictionless into any context you belong to; allowed for anyone who manages the artifact\'s home (its owner, or a current member of its private-channel/group home), from any conversation; ceding a skill to the org is admin-gated (a live org admin only).',+ 'share or move one of YOUR artifacts to another context — body {type:"file"|"skill"|"deploy"|"cron", id, toScope:"org"|<scope id>|a teammate\'s name, permission?:"read"(default)|"write", move?:false}. For app sharing only, `email` may replace `toScope` to grant view access to an exact email outside the directory. Default (share) adds a grant — the artifact keeps its home and creator. move:true changes its home scope instead (skills only today). Frictionless into any context you belong to; allowed for anyone who manages the artifact\'s home (its owner, or a current member of its private-channel/group home), from any conversation; ceding a skill to the org is admin-gated (a live org admin only).',},],},@@ -463,7 +463,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. To widen or narrow that — "share it with everyone" or "share it with <teammate>" — POST /v1/deployments/:id/share with `scope:"org"` or `recipient:"<name>"`; no redeploy. To rename or take down an app, use name / display-name / archive. POST /v1/deployments/:id/always-on with `{alwaysOn:true|false}` keeps an app permanently warm (no idle cold starts) or returns it to sleep-when-idle. POST /v1/deployments/:id/embed-ancestors with `{embedAncestors:["https://tools.example.com", ...]}` lets those sites show the app inside their own page (an iframe); list every frame between the app and the browser tab, and pass `[]` to forbid embedding again. Anyone who manages the app can change these: its owner from any conversation, a current member of the channel/team it was published from, or someone granted "manage" access.',+ '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.',routes: [{method: "GET",@@ -498,13 +498,13 @@ const FAMILIES: AgentApiFamily[] = [{method: "GET",path: "/v1/deployments/:id/share",- summary: "list access grants for an app you own (:id is its name or id) — returns {grantees}; owner-only",+ summary: "inspect access for an app you own (:id is its name or id) — returns {public, grantees}; owner-only",},{method: "POST",path: "/v1/deployments/:id/share",summary:- 'change who can reach a published app you own (:id is its name or id). Target ONE of: `scope` — "org" (everyone in the org) or a scope id like personal:<id>; or `recipient` — a teammate\'s name (resolved in the directory). `access`: view (reach, default), manage (reach + redeploy/rollback), or none (stop sharing). Owner-only (from any conversation), no redeploy',+ 'change who can reach a published app you own (:id is its name or id). For anonymous link access, pass only `public` (boolean). Otherwise target ONE of: `scope` — "org" (everyone in the org) or a scope id like personal:<id>; or `recipient` — a teammate\'s name (resolved in the directory); or `email` — an exact email address, including someone outside the directory (view-only). `access`: view (reach, default), manage (reach + redeploy/rollback), or none (stop sharing). Owner-only (from any conversation), no redeploy',},{method: "POST",diff --git a/src/api/app-deployments.ts b/src/api/app-deployments.tsindex c0790fda8..9d0652b13 100644--- a/src/api/app-deployments.ts+++ b/src/api/app-deployments.ts@@ -1,3 +1,8 @@+import { validEmail } from "../identity/external-members.ts";+import { createMemoryAdvisoryLock } from "../persistence/advisory-lock.ts";+import { INVITE_EMAIL_NOT_CONFIGURED, renderInviteEmail } from "../admin/invite-email.ts";+import { deploymentShareScope } from "../deploy/email-access.ts";+import { errMessage } from "../util/errors.ts";import type { Reach } from "../deploy/deploy-service.ts";import { mintDeployGitAccess } from "../deploy/access-token.ts";@@ -15,6 +20,7 @@ export function createDeploymentMethods(| "listDeployments"| "getDeployment"| "shareDeployment"+ | "inviteToDeployment"| "deploymentGrantees"| "listDeploymentsForViewer"| "effectiveDeploymentPermission"@@ -27,6 +33,7 @@ export function createDeploymentMethods(| "setDeploymentDisplayName"| "setDeploymentAlwaysOn"| "setDeploymentEmbedAncestors"+ | "setDeploymentPublic"| "keepAlwaysOnWarm"| "reachDeployment"| "deploymentLogsFor"@@ -41,6 +48,7 @@ export function createDeploymentMethods(| "attachScope"> {const { effectiveDeploymentPermission, principalCanReadDeployment, principalGitPermission } = h;+ const invitationLock = deps.advisoryLock ?? createMemoryAdvisoryLock();return {deploy(input) {return deps.deploy.deploy(input);@@ -57,6 +65,54 @@ export function createDeploymentMethods(shareDeployment(idOrName, grantee, permission, actor) {return deps.deploy.shareDeployment(idOrName, grantee, permission, actor);},+ async inviteToDeployment(idOrName, rawEmail, actorId) {+ const email = rawEmail.trim().toLowerCase();+ if (!validEmail(email)) throw new Error("a valid email address is required");+ const grantee = await deploymentShareScope(`personal:${email}`, "read");+ const deployment = await deps.deploy.getDeployment(idOrName);+ if (!deployment) throw new Error(`no such app: ${idOrName}`);+ if (deployment.ownerScopeId !== `personal:${actorId}`)+ throw new Error(`only the owner can change who can reach "${deployment.name ?? deployment.id}"`);+ return invitationLock.withLock(`deployment-invite:${deployment.id}:${email}`, async () => {+ const previous = await deps.deploy.deploymentGrantees(deployment.id);+ const alreadyShared = previous.some((g) => g.scope === grantee);+ const grantees = previous.some((g) => g.scope === grantee && g.permission === "read")+ ? previous+ : await deps.deploy.shareDeployment(deployment.id, grantee, "read", { createdBy: actorId });+ const appUrl = deps.deployAppsDomain+ ? `https://${deployment.name ?? deployment.id}.${deps.deployAppsDomain}/`+ : undefined;+ if (alreadyShared)+ return { grantees, invitation: { emailSent: false, alreadyShared: true, ...(appUrl ? { appUrl } : {}) } };+ let emailSent = false;+ let emailProblem: string | undefined;+ if (!deps.inviteMailer) emailProblem = INVITE_EMAIL_NOT_CONFIGURED;+ else if (!appUrl)+ emailProblem = "app URLs are not configured (set DEPLOY_APPS_DOMAIN); share the app link manually";+ else {+ try {+ await deps.inviteMailer.send({+ to: email,+ ...renderInviteEmail({+ to: email,+ brandName: deployment.displayName ?? deployment.name ?? "a shared app",+ invitedBy: actorId,+ signInUrl: appUrl,+ expiresAt: null,+ magicLink: false,+ }),+ });+ emailSent = true;+ } catch (e) {+ emailProblem = errMessage(e);+ }+ }+ return {+ grantees,+ invitation: { emailSent, ...(emailProblem ? { emailProblem } : {}), ...(appUrl ? { appUrl } : {}) },+ };+ });+ },deploymentGrantees(idOrName) {return deps.deploy.deploymentGrantees(idOrName);},@@ -101,6 +157,9 @@ export function createDeploymentMethods(setDeploymentEmbedAncestors(id, embedAncestors) {return deps.deploy.setDeploymentEmbedAncestors(id, embedAncestors);},+ setDeploymentPublic(idOrName, isPublic, actor) {+ return deps.deploy.setDeploymentPublic(idOrName, isPublic, actor);+ },keepAlwaysOnWarm() {return deps.deploy.keepAlwaysOnWarm();},diff --git a/src/api/app-helpers.ts b/src/api/app-helpers.tsindex 27dc1e7a0..b1a394f4e 100644--- a/src/api/app-helpers.ts+++ b/src/api/app-helpers.ts@@ -499,12 +499,20 @@ export function createAppHelpers(deps: AppDeps, app: App) {}async function effectiveDeploymentPermission(d: Deployment, principalId: string): Promise<Permission | null> {- if (!principalId) return null;+ if (!principalId || deps.identity.deactivationSource?.(principalId) === "manual") return null;if (await principalCanWriteScope(principalId, d.ownerScopeId)) return "write";let best: Permission | null = (await principalCanAccessCurrentScope(principalId, d.ownerScopeId)) ? "read" : null;const grants = (await deps.acl?.grantsFor(d.ownerScopeId, encodeRef(deployRef(d.id))).catch(() => [])) ?? [];for (const g of grants) {if (g.permission !== "read" && g.permission !== "write") continue;+ if (+ g.permission === "read" &&+ principalId.includes("@") &&+ g.granteeScopeId === `personal:${principalId.trim().toLowerCase()}`+ ) {+ best = "read";+ continue;+ }if (!(await principalCanAccessCurrentScope(principalId, g.granteeScopeId))) continue;if (g.permission === "write" && (await principalCanUseWriteGrant(principalId, g.granteeScopeId))) return "write";best = "read";diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.tsindex e6a1ca3d8..3ff7ec56c 100644--- a/src/api/app-sessions.ts+++ b/src/api/app-sessions.ts@@ -1,4 +1,5 @@import { notifyDeploymentShared } from "../deploy/share-notice.ts";+import { deploymentShareScope } from "../deploy/email-access.ts";import { sessionTreeRoot, sessionTreeRunCount, SUBAGENT_TREE_RUN_CAP } from "../sessions/session-syscalls.ts";import { isSessionStatus } from "../sessions/session-status.ts";import type { PendingApprovalRecord } from "../types.ts";@@ -956,6 +957,18 @@ export function createSessionMethods(},async grant(g) {+ if (parseRef(g.ref).kind === "deploy") {+ g = {+ ...g,+ granteeScopeId: await deploymentShareScope(+ g.granteeScopeId,+ g.permission,+ async (email) =>+ deps.identity.isInternal(deps.identity.classify(email)) &&+ (await h.directoryMember(email))?.type === "internal",+ ),+ };+ }await deps.acl.grant(g, await artifactAuthor(g.ownerScopeId, g.ref));deps.auditLog.record({at: Date.now(),diff --git a/src/api/app-types.ts b/src/api/app-types.tsindex 3b25d2152..959f616fd 100644--- a/src/api/app-types.ts+++ b/src/api/app-types.ts@@ -1,3 +1,5 @@+import type { InviteMailer } from "../admin/invite-email.ts";+import type { DeploymentInvitation } from "../deploy/email-access.ts";import type { AdmittedWork } from "../util/admitted-work.ts";import type { EventBus } from "../util/event-bus.ts";import type { RunStreamEvent } from "../runs/run-stream-events.ts";@@ -130,6 +132,7 @@ export interface DeploymentView {status: Deployment["status"];alwaysOn?: boolean;embedAncestors?: string[];+ public: boolean;lastAccessAt?: number;createdAt?: number;updatedAt?: number;@@ -159,6 +162,7 @@ export function deploymentView(d: Deployment): DeploymentView {status: d.status,...(d.alwaysOn ? { alwaysOn: true } : {}),...(d.embedAncestors?.length ? { embedAncestors: d.embedAncestors } : {}),+ public: d.public === true,...(d.lastAccessAt !== undefined ? { lastAccessAt: d.lastAccessAt } : {}),...(versions[0] ? { createdAt: versions[0].createdAt } : {}),...(versions.at(-1) ? { updatedAt: versions.at(-1)!.createdAt } : {}),@@ -562,6 +566,7 @@ export interface App {setDeploymentDisplayName(id: string, displayName: string): Promise<Deployment>;setDeploymentAlwaysOn(id: string, alwaysOn: boolean): Promise<Deployment>;setDeploymentEmbedAncestors(id: string, embedAncestors: string[]): Promise<Deployment>;+ setDeploymentPublic(idOrName: string, isPublic: boolean, actor: { createdBy: string }): Promise<Deployment>;keepAlwaysOnWarm(): Promise<number>;reachDeployment(id: string, principalId: string, opts?: ReachOptions): Promise<Reach>;deploymentLogsFor(@@ -575,6 +580,14 @@ export interface App {permission: Permission | null,actor: { createdBy: string },): Promise<DeploymentGrantee[]>;+ inviteToDeployment(+ idOrName: string,+ email: string,+ actorId: string,+ ): Promise<{+ grantees: DeploymentGrantee[];+ invitation: DeploymentInvitation;+ }>;deploymentGrantees(idOrName: string): Promise<DeploymentGrantee[]>;deploymentGitRepoPath(id: string): Promise<string | null>;runDeploymentGitPush<T>(id: string, runReceivePack: () => Promise<{ result: T; ok: boolean }>): Promise<T>;@@ -597,6 +610,7 @@ export interface AppDeps {swarms?: SwarmService;identity: IdentityService;publicWebUrl?: string;+ inviteMailer?: InviteMailer;sessions: SessionStore;screenSecurity?: SecurityScreenProbe;orchestrator: Orchestrator;diff --git a/src/api/artifact-share.ts b/src/api/artifact-share.tsindex 370a3a364..fc8e322a9 100644--- a/src/api/artifact-share.ts+++ b/src/api/artifact-share.ts@@ -1,3 +1,5 @@+import type { DeploymentInvitation } from "../deploy/email-access.ts";+import { validEmail } from "../identity/external-members.ts";import { orgId as configOrgId } from "../config.ts";import { isSharedScope, parseScopeId, scopeId, type Permission, type ScopeId } from "../types.ts";import type { ResourceKind } from "../acl/resource-ref.ts";@@ -29,9 +31,17 @@ export type ResolvedShareTarget =export async function resolveShareTarget(app: { resolveRecipient(recipient: string): Promise<RecipientResolution> },- input: { scope?: string; recipient?: string },- hints: { invalidScope: (scope: string) => string; targetRequired: string },+ input: { scope?: string; recipient?: string; email?: string },+ hints: { invalidScope: (scope: string) => string; targetRequired: string; allowEmail?: boolean },): Promise<ResolvedShareTarget> {+ if (input.email !== undefined) {+ if (!hints.allowEmail) return { kind: "invalid", message: "email grants are only supported for app sharing" };+ if (input.scope !== undefined || input.recipient !== undefined)+ return { kind: "invalid", message: "pass only one of email, scope, or recipient" };+ const email = input.email.trim().toLowerCase();+ if (!validEmail(email)) return { kind: "invalid", message: "a valid email address is required" };+ return { kind: "ok", scope: scopeId("personal", email), label: email };+ }const scope = (input.scope ?? "").trim();const recipient = (input.recipient ?? "").trim();if (scope && recipient) return { kind: "invalid", message: "pass either scope or recipient, not both" };@@ -70,6 +80,7 @@ export interface ShareArtifactRequest {id: string;scope?: string;recipient?: string;+ email?: string;permission?: Permission;move?: boolean;}@@ -82,6 +93,7 @@ export type ShareArtifactResult =id: string;target: { scope: ScopeId; label: string };permission: Permission;+ invitation?: DeploymentInvitation;}| {ok: false;diff --git a/src/api/control-service.ts b/src/api/control-service.tsindex a5843d7e6..bd26a4822 100644--- a/src/api/control-service.ts+++ b/src/api/control-service.ts@@ -937,16 +937,22 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad};}- await app.grant({- ownerScopeId: home.ownerScopeId,- ref: home.grantRef,- granteeScopeId: toScope,- permission,- grantedBy: capability.actorId,- });+ const invite =+ req.type === "deploy" && req.email !== undefined && permission === "read"+ ? await app.inviteToDeployment(home.id, req.email, capability.actorId)+ : undefined;+ if (!invite)+ await app.grant({+ ownerScopeId: home.ownerScopeId,+ ref: home.grantRef,+ granteeScopeId: toScope,+ permission,+ grantedBy: capability.actorId,+ });return {ok: true,verb: "share",+ ...(invite ? { invitation: invite.invitation } : {}),type: req.type,id: home.id,target: { scope: toScope, label: target.label },@@ -971,8 +977,9 @@ type ArtifactTarget =async function resolveArtifactTarget(app: App, req: ShareArtifactRequest): Promise<ArtifactTarget> {const r = await resolveShareTarget(app,- { scope: req.scope, recipient: req.recipient },+ { scope: req.scope, recipient: req.recipient, email: req.email },{+ allowEmail: req.type === "deploy" && !req.move,invalidScope: (scope) => `invalid scope "${scope}" — use "org" or a scope id like personal:<id> or channel:<id>`,targetRequired: 'a target is required: pass `toScope` ("org", a scope id, or a teammate\'s name)',},diff --git a/src/api/routes/auth-broker.ts b/src/api/routes/auth-broker.tsindex 78020a80f..57078d393 100644--- a/src/api/routes/auth-broker.ts+++ b/src/api/routes/auth-broker.ts@@ -2,7 +2,8 @@ import { createHash } from "node:crypto";import { verifySignedPayload } from "../../auth/signed-token.ts";import { AdminError } from "../../admin/admin-service.ts";import { sendJson } from "../http.ts";-import { externalMemberActive } from "../../identity/external-members.ts";+import { deployRef, encodeRef } from "../../acl/resource-ref.ts";+import { externalMemberActive, validEmail } from "../../identity/external-members.ts";import { isObj, authorizeAdmin, orgScope, audit, activePrincipal } from "./shared.ts";import { type ApiCtx, type Route } from "./route.ts";@@ -52,15 +53,30 @@ async function claimBrokerNonce(ctx: ApiCtx): Promise<void> {}async function emailAllowed(ctx: ApiCtx): Promise<void> {- const { res, deps, url } = ctx;- const email = (url.searchParams.get("email") ?? "").trim();- if (!email) return sendJson(res, 400, { error: "bad_request", message: "email required" });+ const { res, deps, app, url } = ctx;+ const email = (url.searchParams.get("email") ?? "").trim().toLowerCase();+ if (!validEmail(email)) return sendJson(res, 400, { error: "bad_request", message: "email required" });if (!deps.identity) return sendJson(res, 200, { allowed: false });await deps.identity.refresh();const member = deps.identity.externalMember(email);const allowed =member !== undefined && externalMemberActive(member) && deps.identity.classify(email).type === "internal";- return sendJson(res, 200, { allowed, ...(allowed ? { expiresAt: member.expiresAt } : {}) });+ if (allowed) return sendJson(res, 200, { allowed: true, expiresAt: member.expiresAt });+ if (deps.identity.deactivationSource(email) === "manual") return sendJson(res, 200, { allowed: false });+ const grants = (await deps.acl?.list()) ?? [];+ const deployments = await app.listDeployments();+ const appOnly = deployments.some(+ (d) =>+ d.status !== "archived" &&+ grants.some(+ (g) =>+ g.ownerScopeId === d.ownerScopeId &&+ g.ref === encodeRef(deployRef(d.id)) &&+ g.granteeScopeId === `personal:${email}` &&+ g.permission === "read",+ ),+ );+ return sendJson(res, 200, appOnly ? { allowed: true, appOnly: true } : { allowed: false });}async function brokerSession(ctx: ApiCtx): Promise<void> {diff --git a/src/api/routes/deployments.ts b/src/api/routes/deployments.tsindex d06bc77d8..eca420722 100644--- a/src/api/routes/deployments.ts+++ b/src/api/routes/deployments.ts@@ -22,7 +22,7 @@ import { resolveShareTarget as resolveShareTargetGrammar } from "../artifact-shaimport { verifyDeployGitAccess, viewerIdentityKey } from "../../deploy/access-token.ts";import { APP_SHELL_PATH_PREFIX, appShellHtml } from "../../deploy/app-shell.ts";import { principalDestination } from "../../reach/reach.ts";-import { FRAME_SESSION_COOKIE, portalSessionSub, portalSessionSubFrom } from "../../deploy/viewer-session.ts";+import { FRAME_SESSION_COOKIE, portalSession, portalSessionFrom } from "../../deploy/viewer-session.ts";import { EMBED_ANCESTORS_HINT, parseEmbedAncestors } from "../../deploy/embed-ancestors.ts";import { proxyHeaders } from "../../util/http-proxy.ts";@@ -834,23 +834,26 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {cleanUrlRedirect();return true;}+ const deployment = await app.getDeployment(slug).catch(() => null);+ const isPublic = deployment?.public === true;const sessionSecret = deps.deployAppsSessionSecret;const loginUrl = deps.deployAppsLoginUrl;const wantsHtml = ctx.method === "GET" && String(req.headers.accept ?? "").includes("text/html");- let sub = sessionSecret ? portalSessionSub(req.headers.cookie, sessionSecret) : null;+ let session = sessionSecret ? portalSession(req.headers.cookie, sessionSecret) : null;const dest = req.headers["sec-fetch-dest"];const site = req.headers["sec-fetch-site"];const framed = dest === "iframe" || site === "same-origin";- const embedAncestors = framed ? ((await app.getDeployment(slug).catch(() => null))?.embedAncestors ?? []) : [];- if (!sub && sessionSecret && embedAncestors.length) {- sub = portalSessionSubFrom(req.headers.cookie, FRAME_SESSION_COOKIE, sessionSecret);+ const embedAncestors = framed ? (deployment?.embedAncestors ?? []) : [];+ if (!session && sessionSecret && embedAncestors.length) {+ session = portalSessionFrom(req.headers.cookie, FRAME_SESSION_COOKIE, sessionSecret);}+ const sub = session?.sub;if (embedAncestors.length) res.setHeader("content-security-policy", frameAncestorsDirective(embedAncestors));- if (!sessionSecret || !loginUrl) {+ if (!isPublic && (!sessionSecret || !loginUrl)) {sendJson(res, 503, { error: "unavailable", message: "sign-in is not configured for deployment subdomains" });return true;}- if (!sub) {+ if (!sub && !isPublic) {const qs = url.searchParams.toString();const returnTo = `https://${rawHost}${safePathname}?${qs ? `${qs}&` : ""}dpl_signin=1`;const signIn = `${loginUrl}${deps.deployAppsLoginPath ?? "/auth/login"}?returnTo=${encodeURIComponent(returnTo)}`;@@ -873,13 +876,27 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {url.searchParams.delete("__qm_no_shell");const isTopDocument = String(req.headers["sec-fetch-dest"] ?? "") === "document";const isShellRequest = pathname.startsWith(APP_SHELL_PATH_PREFIX);- const canManage = await app.canManageDeployment(slug, sub);- if (ctx.method === "GET" && ((!bareApp && isTopDocument) || isShellRequest) && canManage) {+ const canManage = sub && !session?.appOnly ? await app.canManageDeployment(slug, sub) : false;+ let authenticatedPermission: Permission | null = null;+ if (sub && deployment) {+ if (session?.appOnly) {+ await deps.identity?.refresh();+ if (+ deps.identity?.deactivationSource(sub) !== "manual" &&+ (await app.deploymentGrantees(deployment.id)).some(+ (grant) => grant.scope === scopeId("personal", sub.trim().toLowerCase()) && grant.permission === "read",+ )+ )+ authenticatedPermission = "read";+ } else {+ authenticatedPermission = await app.effectiveDeploymentPermission(deployment, sub);+ }+ }+ if (ctx.method === "GET" && ((!bareApp && isTopDocument) || isShellRequest) && canManage && loginUrl) {if (signInAttempted) {cleanUrlRedirect();return true;}- const deployment = await app.getDeployment(slug);if (isShellRequest) {if (pathname === "/__claw__/version" && deployment)sendJson(res, 200, { version: deployment.appliedVersion ?? deployment.currentVersion });@@ -897,19 +914,27 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {);return true;}- const reach = await app.reachDeployment(slug, sub, canManage ? { bypassAcl: true } : undefined);+ const viewer = sub ?? "";+ const reach =+ session?.appOnly && !isPublic && !authenticatedPermission+ ? { status: deployment ? ("denied" as const) : ("not_found" as const) }+ : await app.reachDeployment(+ deployment?.id ?? slug,+ viewer,+ canManage || isPublic || session?.appOnly ? { bypassAcl: true } : undefined,+ );if (reach.status === "denied") {const owner = (await app.getDeployment(slug).catch(() => null))?.ownerScopeId;const ev = {at: Date.now(),- principalId: sub,+ principalId: viewer,action: "deployment.reach_denied",resource: slug,- scopeLabel: owner ?? scopeId("personal", sub),+ scopeLabel: owner ?? scopeId("personal", viewer),status: "denied",};const hour = Math.floor(ev.at / 3_600_000);- if (deps.auditLog?.recordOnce) await deps.auditLog.recordOnce(`reach_denied|${sub}|${slug}|${hour}`, ev);+ if (deps.auditLog?.recordOnce) await deps.auditLog.recordOnce(`reach_denied|${viewer}|${slug}|${hour}`, ev);else deps.auditLog?.record(ev);}if (reach.status === "denied" && ctx.method === "POST" && pathname === REQUEST_ACCESS_PATH) {@@ -927,13 +952,13 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {try {await app.enqueueDelivery({destination: {- ...principalDestination(ownerId, sub),- deploymentAccess: { deploymentId: d.id, requesterId: sub },+ ...principalDestination(ownerId, viewer),+ deploymentAccess: { deploymentId: d.id, requesterId: viewer },},text:- `${sub} is asking for access to your app "${label}" (https://${rawHost}/). ` +- `They signed in but the app isn't shared with them. To grant it, share the deployment with personal:${sub}.`,- idempotencyKey: `deploy-access-request:${slug}:${sub}:${day}`,+ `${viewer} is asking for access to your app "${label}" (https://${rawHost}/). ` ++ `They signed in but the app isn't shared with them. To grant it, share the deployment with personal:${viewer}.`,+ idempotencyKey: `deploy-access-request:${slug}:${viewer}:${day}`,});sendJson(res, 200, { ok: true });} catch {@@ -947,14 +972,16 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {"cache-control": "no-store","x-content-type-options": "nosniff",});- res.end(notSharedHtml(sub));+ res.end(notSharedHtml(viewer));return true;}if (reach.status === "ok" && signInAttempted && ctx.method === "GET") {cleanUrlRedirect();return true;}- await proxyReach(ctx, reach, pathname, sub, { frameAncestors: embedAncestors });+ await proxyReach(ctx, reach, pathname, sub && (canManage || authenticatedPermission) ? sub : undefined, {+ frameAncestors: embedAncestors,+ });return true;}@@ -1486,8 +1513,12 @@ type ShareTarget =| { kind: "ambiguous"; candidates: Array<{ principalId: string; displayName: string }> }| { kind: "invalid"; message: string };-export function resolveShareTarget(app: App, input: { scope?: string; recipient?: string }): Promise<ShareTarget> {+export function resolveShareTarget(+ app: App,+ input: { scope?: string; recipient?: string; email?: string },+): Promise<ShareTarget> {return resolveShareTargetGrammar(app, input, {+ allowEmail: true,invalidScope: (scope) => `invalid scope "${scope}" — use "org" or a scope id like personal:<id> or org:<id>`,targetRequired: 'a target is required: pass `scope` ("org" or a scope id) or `recipient` (a teammate\'s name)',});@@ -1500,14 +1531,57 @@ 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." });- return sendJson(res, 200, { grantees: await app.deploymentGrantees(deployment.id) });+ return sendJson(res, 200, {+ public: deployment.public === true,+ grantees: await app.deploymentGrantees(deployment.id),+ });}export async function shareDeployment(ctx: ApiCtx): Promise<void> {const { res, app, params, body, capability } = ctx;if (!capability)return sendJson(res, 403, { error: "forbidden", message: "sharing requires an agent capability token" });- const b = (isObj(body) ? body : {}) as { scope?: unknown; recipient?: unknown; access?: unknown };+ const b = (isObj(body) ? body : {}) as {+ scope?: unknown;+ recipient?: unknown;+ email?: unknown;+ access?: unknown;+ public?: unknown;+ };+ if (b.public !== undefined) {+ if (typeof b.public !== "boolean")+ return sendJson(res, 400, { error: "bad_request", message: "public must be a boolean" });+ if (b.scope !== undefined || b.recipient !== undefined || b.email !== undefined || b.access !== undefined)+ return sendJson(res, 400, {+ error: "bad_request",+ message: "public access and person/scope access must be changed separately",+ });+ try {+ const deployment = await app.setDeploymentPublic(params.id!, b.public, { createdBy: capability.actorId });+ return sendJson(res, 200, {+ ok: true,+ public: deployment.public === true,+ reach: deployment.public === true ? "anyone with the link" : "restricted",+ grantees: await app.deploymentGrantees(deployment.id),+ });+ } catch (e) {+ const msg = errMessage(e);+ let status = 400;+ let error = "share_failed";+ if (/no such app/.test(msg)) {+ status = 404;+ error = "not_found";+ } else if (/only the owner/.test(msg)) {+ status = 403;+ error = "forbidden";+ }+ return sendJson(res, status, { error, message: msg });+ }+ }+ if (b.email !== undefined && typeof b.email !== "string")+ return sendJson(res, 400, { error: "bad_request", message: "email must be a string" });+ if (b.email !== undefined && (b.scope !== undefined || b.recipient !== undefined))+ return sendJson(res, 400, { error: "bad_request", message: "pass only one of email, scope, or recipient" });const access = typeof b.access === "string" ? b.access.toLowerCase() : "view";if (access !== "view" && access !== "manage" && access !== "none") {return sendJson(res, 400, { error: "bad_request", message: 'access must be "view", "manage", or "none"' });@@ -1518,6 +1592,7 @@ export async function shareDeployment(ctx: ApiCtx): Promise<void> {const target = await resolveShareTarget(app, {...(typeof b.scope === "string" ? { scope: b.scope } : {}),...(typeof b.recipient === "string" ? { recipient: b.recipient } : {}),+ ...(typeof b.email === "string" ? { email: b.email } : {}),});if (target.kind === "invalid") return sendJson(res, 400, { error: "bad_request", message: target.message });if (target.kind === "none")@@ -1532,16 +1607,25 @@ export async function shareDeployment(ctx: ApiCtx): Promise<void> {candidates: target.candidates,});try {- const grantees = await app.shareDeployment(params.id!, target.scope, permission, { createdBy: capability.actorId });+ const invite =+ typeof b.email === "string" && permission === "read"+ ? await app.inviteToDeployment(params.id!, b.email, capability.actorId)+ : undefined;+ const grantees =+ invite?.grantees ??+ (await app.shareDeployment(params.id!, target.scope, permission, { createdBy: capability.actorId }));const orgGrant = grantees.find((g) => parseScopeId(g.scope).kind === "org");let reach = "owner-only";if (orgGrant) reach = `everyone in ${parseScopeId(orgGrant.scope).ref}`;else if (grantees.length) reach = `${grantees.length} grantee${grantees.length === 1 ? "" : "s"}`;+ const deployment = await app.getDeployment(params.id!);return sendJson(res, 200, {ok: true,target: { scope: target.scope, label: target.label },access,reach,+ ...(invite ? { invitation: invite.invitation } : {}),+ public: deployment?.public === true,grantees,});} catch (e) {diff --git a/src/api/routes/surface.ts b/src/api/routes/surface.tsindex 9a20f8019..5d89133e9 100644--- a/src/api/routes/surface.ts+++ b/src/api/routes/surface.ts@@ -1103,6 +1103,7 @@ export async function shareArtifact(ctx: ApiCtx): Promise<void> {type?: unknown;id?: unknown;toScope?: unknown;+ email?: unknown;permission?: unknown;move?: unknown;};@@ -1111,7 +1112,15 @@ export async function shareArtifact(ctx: ApiCtx): Promise<void> {}if (typeof b.id !== "string" || !b.id.trim())return sendJson(res, 400, { error: "bad_request", message: "id required" });- if (typeof b.toScope !== "string" || !b.toScope.trim()) {+ if (+ b.email !== undefined &&+ (typeof b.email !== "string" || b.toScope !== undefined || b.type !== "deploy" || b.move === true)+ )+ return sendJson(res, 400, {+ error: "bad_request",+ message: "email is only supported for app sharing, instead of toScope",+ });+ if (b.email === undefined && (typeof b.toScope !== "string" || !b.toScope.trim())) {return sendJson(res, 400, {error: "bad_request",message: 'toScope required ("org", a scope id, or a teammate\'s name)',@@ -1124,7 +1133,8 @@ export async function shareArtifact(ctx: ApiCtx): Promise<void> {{type: b.type,id: b.id,- ...splitToScope(b.toScope),+ ...(typeof b.toScope === "string" ? splitToScope(b.toScope) : {}),+ ...(typeof b.email === "string" ? { email: b.email } : {}),...(b.permission === "read" || b.permission === "write" ? { permission: b.permission } : {}),...(b.move === true ? { move: true } : {}),},@@ -1144,6 +1154,7 @@ export async function shareArtifact(ctx: ApiCtx): Promise<void> {id: result.id,target: result.target,permission: result.permission,+ ...(result.invitation ? { invitation: result.invitation } : {}),});}diff --git a/src/deploy/deploy-service.ts b/src/deploy/deploy-service.tsindex 587d7d892..364772af8 100644--- a/src/deploy/deploy-service.ts+++ b/src/deploy/deploy-service.ts@@ -1,6 +1,7 @@import { notifyDeploymentShared } from "./share-notice.ts";import type { DeliveryStore } from "../delivery/delivery-store.ts";import { EMBED_ANCESTORS_HINT, parseEmbedAncestors } from "./embed-ancestors.ts";+import { deploymentShareScope } from "./email-access.ts";import { mkdir, writeFile } from "node:fs/promises";import { join, dirname, resolve, relative, isAbsolute } from "node:path";import { randomUUID } from "node:crypto";@@ -64,6 +65,7 @@ export interface DeployOrUpdateInput {createdInScope?: ScopeId;alwaysOn?: boolean;embedAncestors?: string[];+ public?: boolean;defaultAudience?: { contextScopeId: ScopeId; granteeScopeIds: ScopeId[]; snapshotAt: number; force?: boolean };}@@ -84,6 +86,7 @@ export interface DeployService {setDeploymentDisplayName(id: string, displayName: string): Promise<Deployment>;setDeploymentAlwaysOn(id: string, alwaysOn: boolean): Promise<Deployment>;setDeploymentEmbedAncestors(id: string, embedAncestors: string[]): Promise<Deployment>;+ setDeploymentPublic(idOrName: string, isPublic: boolean, actor: { createdBy: string }): Promise<Deployment>;keepAlwaysOnWarm(): Promise<number>;reachDeployment(idOrName: string, principalId: string, opts?: ReachOptions): Promise<Reach>;@@ -127,6 +130,7 @@ export interface DeployServiceDeps {advisoryLock?: AdvisoryLock;canReadScope?: (principalId: string, scopeId: ScopeId) => Promise<boolean>;canWriteScope?: (principalId: string, scopeId: ScopeId) => Promise<boolean>;+ canManageEmail?: (email: string) => Promise<boolean>;managesArtifactHome?: (homeScopeId: ScopeId, createdBy: string, principalId: string) => Promise<boolean>;deploymentEnv?: (deployment: Deployment) => Promise<Record<string, string>>;}@@ -343,7 +347,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {const grant: Grant = {ownerScopeId: d.ownerScopeId,ref: deploymentRef(d.id),- granteeScopeId: s.scope,+ granteeScopeId: await deploymentShareScope(s.scope, s.permission, deps.canManageEmail),permission: s.permission,grantedBy: createdBy,};@@ -568,6 +572,23 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {});},+ async setDeploymentPublic(idOrName, isPublic, actor) {+ const d = (await deps.deployStore.get(idOrName)) ?? (await deps.deployStore.getByName(idOrName));+ if (!d) throw new Error(`no such app: ${idOrName}`);+ if (d.ownerScopeId !== scopeId("personal", actor.createdBy)) {+ throw new Error(`only the owner can change who can reach "${d.name ?? d.id}"`);+ }+ await deps.deployStore.setPublic(d.id, isPublic);+ deps.auditLog.record({+ at: Date.now(),+ principalId: actor.createdBy,+ action: isPublic ? "deploy_public_enable" : "deploy_public_disable",+ resource: deploymentRef(d.id),+ scopeLabel: d.ownerScopeId,+ });+ return (await deps.deployStore.get(d.id))!;+ },+async keepAlwaysOnWarm() {const result = await leaderLease.hold("deployments:keep-warm", async () => {let warmed = 0;@@ -711,6 +732,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {} else if (input.alwaysOn !== undefined) await this.setDeploymentAlwaysOn(existing.id, input.alwaysOn);if (input.embedAncestors !== undefined)await this.setDeploymentEmbedAncestors(existing.id, input.embedAncestors);+ if (input.public !== undefined) await this.setDeploymentPublic(existing.id, input.public, { createdBy });if (input.share?.length) await issueShares((await deps.deployStore.get(existing.id))!, createdBy, input.share);return (await deps.deployStore.get(existing.id))!;}@@ -728,6 +750,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {);if (input.embedAncestors !== undefined)await this.setDeploymentEmbedAncestors(existing.id, input.embedAncestors);+ if (input.public !== undefined) await this.setDeploymentPublic(existing.id, input.public, { createdBy });if (input.share?.length) await issueShares((await deps.deployStore.get(existing.id))!, createdBy, input.share);return (await deps.deployStore.get(existing.id))!;}@@ -769,6 +792,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {});isCreate = true;}+ if (input.public !== undefined) await this.setDeploymentPublic(d.id, input.public, { createdBy });if (input.defaultAudience)await reconcileDefaultAudience((await deps.deployStore.get(d.id))!,@@ -799,6 +823,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}"`);}+ grantee = await deploymentShareScope(grantee, permission, deps.canManageEmail);const ref = deploymentRef(d.id);await deps.acl.revoke(d.ownerScopeId, ref, grantee, actor.createdBy);if (permission === null) {diff --git a/src/deploy/deploy-store.ts b/src/deploy/deploy-store.tsindex 078b88cbc..de734895f 100644--- a/src/deploy/deploy-store.ts+++ b/src/deploy/deploy-store.ts@@ -69,6 +69,7 @@ export interface Deployment {alwaysOn?: boolean;embedAncestors?: string[];+ public?: true;lastAccessAt?: number;appliedVersion?: number;versions: DeploymentVersion[];@@ -110,6 +111,7 @@ export interface DeployStore {setDisplayName(id: string, displayName: string | undefined): Promise<void>;setAlwaysOn(id: string, alwaysOn: boolean): Promise<void>;setEmbedAncestors(id: string, embedAncestors: string[]): Promise<void>;+ setPublic(id: string, isPublic: boolean): Promise<void>;setDefaultAudience(id: string, snapshot: DefaultAudienceSnapshot): Promise<void>;setAppliedVersion(id: string, version: number): Promise<void>;touch(id: string, at: number): Promise<void>;@@ -436,6 +438,9 @@ export function createDeployStore(backing?: DurableMap<Deployment> | DeployStoreasync setEmbedAncestors(id, embedAncestors) {await backingMap.merge(id, { embedAncestors } as Partial<Deployment>);},+ async setPublic(id, isPublic) {+ await backingMap.merge(id, { public: isPublic ? true : undefined });+ },async setDefaultAudience(id, snapshot) {const d = await backingMap.get(id);if (d) {diff --git a/src/deploy/email-access.ts b/src/deploy/email-access.tsnew file mode 100644index 000000000..9ebabcfbc--- /dev/null+++ b/src/deploy/email-access.ts@@ -0,0 +1,23 @@+import { validEmail } from "../identity/external-members.ts";+import { parseScopeId, scopeId, type Permission, type ScopeId } from "../types.ts";++export async function deploymentShareScope(+ grantee: ScopeId,+ permission: Permission | null,+ canManageEmail?: (email: string) => Promise<boolean>,+): Promise<ScopeId> {+ const { kind, ref } = parseScopeId(grantee);+ if (kind !== "personal" || !ref?.includes("@")) return grantee;+ const email = ref.trim().toLowerCase();+ if (!validEmail(email)) throw new Error("a valid email address is required");+ if (permission === "write" && !(await canManageEmail?.(email)))+ throw new Error("email recipients outside the directory can only view apps");+ return scopeId("personal", email);+}++export interface DeploymentInvitation {+ emailSent: boolean;+ emailProblem?: string;+ appUrl?: string;+ alreadyShared?: true;+}diff --git a/src/deploy/viewer-session.ts b/src/deploy/viewer-session.tsindex dfb7ef0d5..35cbff45e 100644--- a/src/deploy/viewer-session.ts+++ b/src/deploy/viewer-session.ts@@ -2,24 +2,33 @@ import { createHmac, timingSafeEqual } from "node:crypto";export const FRAME_SESSION_COOKIE = "portal_session_x";-export function portalSessionSub(cookieHeader: string | undefined, secret: string, now = Date.now()): string | null {- return portalSessionSubFrom(cookieHeader, "portal_session", secret, now);+export interface PortalViewerSession {+ sub: string;+ appOnly: boolean;}-export function portalSessionSubFrom(+export function portalSession(+ cookieHeader: string | undefined,+ secret: string,+ now = Date.now(),+): PortalViewerSession | null {+ return portalSessionFrom(cookieHeader, "portal_session", secret, now);+}++export function portalSessionFrom(cookieHeader: string | undefined,name: string,secret: string,now = Date.now(),-): string | null {+): PortalViewerSession | null {for (const token of readCookies(cookieHeader, name)) {- const sub = verifySessionToken(token, secret, now);- if (sub) return sub;+ const session = verifySessionToken(token, secret, now);+ if (session) return session;}return null;}-function verifySessionToken(token: string, secret: string, now: number): string | null {+function verifySessionToken(token: string, secret: string, now: number): PortalViewerSession | null {const key = createHmac("sha256", secret).update("portal.session.v1").digest();const dot = token.indexOf(".");if (dot <= 0 || dot === token.length - 1) return null;@@ -38,7 +47,8 @@ function verifySessionToken(token: string, secret: string, now: number): stringif (claims.k !== "session") return null;if (typeof claims.sub !== "string" || !claims.sub) return null;if (typeof claims.exp !== "number" || now >= claims.exp * 1000) return null;- return claims.sub;+ if (claims.appOnly !== undefined && typeof claims.appOnly !== "boolean") return null;+ return { sub: claims.sub, appOnly: claims.appOnly === true };}function readCookies(header: string | undefined, name: string): string[] {diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.tsindex f3a7bf430..b8581fe33 100644--- a/src/harness/agent-tools.ts+++ b/src/harness/agent-tools.ts@@ -1112,13 +1112,14 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):name: "publish",label: "publish",description:- "Publish a directory from the workspace as a durable, scope-bound internal web app " ++ "Publish a directory from the workspace as a durable, private-by-default web app " +"(it keeps running after the turn ends and gets a stable link). Before publishing, verify the " +"directory exists and contains files. For a new app or a code/file update, always pass `entrypoint`; " +"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. Use apps action share for subsequent grants. Share the full absolute URL " ++ "publication-time grants. `public: true` makes the app reachable without sign-in; it is never the default. " ++ "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. " +"Egress is open, " +@@ -1174,6 +1175,12 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):rollbackTo: Type.Optional(Type.Integer({ description: "Flip the deployment named `name` back to this version number." }),),+ public: Type.Optional(+ Type.Boolean({+ description:+ "Explicitly set whether anyone with the link can open the app without signing in. Defaults to private for new apps; omit to preserve the current setting on updates.",+ }),+ ),alwaysOn: Type.Optional(Type.Boolean({description:@@ -1202,6 +1209,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):const reach = describePublishAudience(r.audience);const alwaysOnNote = r.alwaysOn ? "\nAlways-on: the app is kept warm — no idle cold starts." : "";const embedNote = r.embedAncestors?.length ? `\nEmbeddable by: ${r.embedAncestors.join(", ")}` : "";+ const publicNote = r.public ? "\nAccess: public — anyone with the link can open it without signing in." : "";const dataNote = r.dataDir? `\nDurable data: runtime state written under ${r.dataDir} ($DATA_DIR) survives restarts and redeploys — keep SQLite at ${r.dataDir}/app.db (it gets the strongest durability the runtime offers). If this app writes runtime state anywhere else on disk, migrate it there (data deliberately baked into the repo stays where it is).`: "";@@ -1218,7 +1226,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):...(r.dataDir ? { dataDir: r.dataDir } : {}),},text(- `Published ${r.name ?? r.id} (v${r.version}) → ${r.url}\n${reach}${alwaysOnNote}${embedNote}${dataNote}`,+ `Published ${r.name ?? r.id} (v${r.version}) → ${r.url}\n${reach}${publicNote}${alwaysOnNote}${embedNote}${dataNote}`,),);} catch (e) {@@ -2989,17 +2997,47 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):function sharingTool(type: "file" | "skill" | "deploy" | "cron", move = false): ToolDefinition {const tool = { file: "files", skill: "skills", deploy: "apps", cron: "cron" }[type];const action = move ? "move" : "share";+ let description =+ "Grant access to an artifact you own while keeping it in its current home. Only the owner can share; grantees cannot reshare.";+ if (move)+ description =+ "Transfer the artifact to another context. Moving an app transfers ownership; existing shares survive. Moving a skill to the org requires an org admin in a user-started turn.";+ else if (type === "deploy")+ description =+ "Change access to an app you own while keeping it in its current home. Set public to true or false for anonymous link access, or use toScope/email for authenticated access (external emails are view-only). Only the owner can share; grantees cannot reshare.";return defineTool({name: action,label: action,- description: move- ? "Transfer the artifact to another context. Moving an app transfers ownership; existing shares survive. Moving a skill to the org requires an org admin in a user-started turn."- : "Grant access to an artifact you own while keeping it in its current home. Only the owner can share; grantees cannot reshare.",+ description,parameters: Type.Object({id: Type.String({ description: "Artifact ID; an app may also be named by its handle." }),- toScope: Type.String({- description: 'Destination: "org", channel:<id>, team:<id>, personal:<id>, or a teammate name.',- }),+ toScope:+ type === "deploy" && !move+ ? Type.Optional(+ Type.String({+ description:+ 'Authenticated destination: "org", channel:<id>, team:<id>, personal:<id>, or a teammate name. Omit when setting public or email.',+ }),+ )+ : Type.String({+ description: 'Destination: "org", channel:<id>, team:<id>, personal:<id>, or a teammate name.',+ }),+ ...(type === "deploy" && !move+ ? {+ email: Type.Optional(+ Type.String({+ description:+ "Exact email to grant view access, including people outside the directory. Use instead of toScope.",+ }),+ ),+ public: Type.Optional(+ Type.Boolean({+ description:+ "true lets anyone with the link open the app without signing in; false makes it restricted again. Never enabled by default.",+ }),+ ),+ }+ : {}),...(!move? {permission: Type.Optional(@@ -3011,15 +3049,44 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):: {}),}),async execute(callId, args) {- const params = args as { id: string; toScope: string; permission?: "read" | "write" };+ const params = args as {+ id: string;+ toScope?: string;+ email?: string;+ public?: boolean;+ permission?: "read" | "write";+ };const tc = ref.current;if (!tc) return text("[error] no active tool context");const id = params.id;await recordCall(callId, { tool, action, type, id });+ if (type === "deploy" && !move && params.public !== undefined) {+ if (params.toScope !== undefined || params.email !== undefined)+ return recordResult(+ callId,+ { tool, action, error: "bad_request" },+ text("[error] set public, email, or toScope, not more than one"),+ true,+ );+ const d = await tc.setDeploymentPublic(id, params.public);+ return recordResult(+ callId,+ { tool, action, type, id: d.id, public: d.public },+ text(`${d.name ?? d.id} is now ${d.public ? "public — anyone with the link can open it" : "restricted"}.`),+ );+ }+ if (!params.toScope && !params.email)+ return recordResult(+ callId,+ { tool, action, error: "bad_request" },+ text("[error] toScope or email is required unless public is set"),+ true,+ );const r = await tc.shareArtifact({type,id,- ...splitToScope(params.toScope),+ ...(params.toScope ? splitToScope(params.toScope) : {}),+ ...(params.email !== undefined ? { email: params.email } : {}),...(params.permission !== undefined ? { permission: params.permission } : {}),...(move ? { move: true } : {}),});@@ -3030,11 +3097,19 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):: "";return recordResult(callId, { tool, action, error: r.code }, text(`[error] ${r.message}${candidates}`), true);}+ let invitationNote = "";+ if (r.invitation) {+ if (r.invitation.emailSent) invitationNote = " App invitation email sent.";+ else if (r.invitation.alreadyShared) invitationNote = " Already shared; no duplicate email sent.";+ else+ invitationNote = ` Access granted, but invitation email was not sent: ${r.invitation.emailProblem ?? "delivery unavailable"}`;+ if (r.invitation.appUrl) invitationNote += ` App link: ${r.invitation.appUrl}`;+ }return recordResult(callId,{ tool, action, verb: r.verb, type: r.type, id: r.id, target: r.target.scope },text(- `${r.verb === "move" ? "Moved" : "Shared"} ${r.type} ${r.id} → ${r.target.label}${r.verb === "share" ? ` (${r.permission})` : ""}.`,+ `${r.verb === "move" ? "Moved" : "Shared"} ${r.type} ${r.id} → ${r.target.label}${r.verb === "share" ? ` (${r.permission})` : ""}.${invitationNote}`,),);},diff --git a/src/tools/primitives.ts b/src/tools/primitives.tsindex 4631921e8..8e6a77da2 100644--- a/src/tools/primitives.ts+++ b/src/tools/primitives.ts@@ -87,6 +87,7 @@ export interface PublishInput {rollbackTo?: number;alwaysOn?: boolean;embedAncestors?: string[];+ public?: boolean;share?: Array<{ scope: ScopeId; permission: Permission }>;}@@ -108,6 +109,7 @@ interface PublishResult {dataDir?: string;alwaysOn?: boolean;embedAncestors?: string[];+ public?: boolean;}export class NeedsApproval extends Error {@@ -215,6 +217,7 @@ export interface ToolContext extends SurfaceToolDeps {skill(name: string, opts?: { path?: string; sandboxId?: string; signal?: AbortSignal }): Promise<SkillResult>;write(path: string, data?: string, share?: ShareDirective[]): Promise<WriteResult>;publish(input: PublishInput): Promise<PublishResult>;+ setDeploymentPublic(id: string, isPublic: boolean): Promise<{ id: string; name?: string; public: boolean }>;createPlayground(input: { title: string; html: string }): Promise<PlaygroundArtifact>;memorySearch(q: string, limit?: number): Promise<string[] | null>;memoryRead(): Promise<string | null>;@@ -1066,6 +1069,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {...(input.rollbackTo !== undefined ? { rollbackTo: input.rollbackTo } : {}),...(input.alwaysOn !== undefined ? { alwaysOn: input.alwaysOn } : {}),...(input.embedAncestors !== undefined ? { embedAncestors: input.embedAncestors } : {}),+ ...(input.public !== undefined ? { public: input.public } : {}),...(doReconcile? {defaultAudience: {@@ -1100,10 +1104,16 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {...(dataDir ? { dataDir } : {}),...(d.alwaysOn ? { alwaysOn: true } : {}),...(d.embedAncestors?.length ? { embedAncestors: d.embedAncestors } : {}),+ ...(d.public ? { public: true } : {}),};});},+ async setDeploymentPublic(id: string, isPublic: boolean) {+ const d = await deps.deploy.setDeploymentPublic(id, isPublic, { createdBy: deps.createdBy });+ return { id: d.id, ...(d.name ? { name: d.name } : {}), public: d.public === true };+ },+async memorySearch(q: string, limit?: number): Promise<string[] | null> {if (deps.context) return timed("recall", () => deps.context!.searchMemory(q, limit));const read = deps.memoryAccess?.read ?? [];diff --git a/src/wiring.ts b/src/wiring.tsindex dc2f364fd..005706c00 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -1686,6 +1686,15 @@ export function buildApp(advisoryLock,canReadScope,canWriteScope,+ canManageEmail: async (email) => {+ await identity.refresh();+ return (+ identity.isInternal(identity.classify(email)) &&+ ((await directory.get(email))?.type === "internal" ||+ config.emailAuthPrincipals?.includes(email) ||+ identity.externalMember(email) !== undefined)+ );+ },managesArtifactHome,...(deployGitSecret && deployGitBase? {@@ -1887,6 +1896,10 @@ export function buildApp(capabilityTokenCompression: config.capabilityTokenCompression,...(config.apiBaseUrl ? { apiBaseUrl: config.apiBaseUrl } : {}),...(config.publicWebUrl ? { publicWebUrl: config.publicWebUrl } : {}),+ ...(config.deployAppsDomain ? { deployAppsDomain: config.deployAppsDomain } : {}),+ ...(config.resendApiKey && config.emailFrom+ ? { inviteMailer: createResendMailer(config.resendApiKey, config.emailFrom) }+ : {}),...(config.publicUrl ? { webhookPublicUrl: config.publicUrl } : {}),memoryPolicy: { recall: config.memoryRecall, capture: config.memoryCapture },memoryStrategy,diff --git a/test/agent-api-discovery.test.ts b/test/agent-api-discovery.test.tsindex 73a31dadb..4184d6ca2 100644--- a/test/agent-api-discovery.test.ts+++ b/test/agent-api-discovery.test.ts@@ -183,7 +183,7 @@ test("discovery advertises the deployment share endpoint, with guidance", asyncassert.ok(p.includes("/v1/deployments/:id"), "deployment detail is discoverable");assert.ok(p.includes("/v1/deployments/:id/restore"), "restore is discoverable");assert.ok(- body.guidance.some((g: string) => /share it with everyone/i.test(g)),+ body.guidance.some((g: string) => g.includes("POST /v1/deployments/:id/share") && g.includes('scope:"org"')),"share guidance is present",);} finally {diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.tsindex 4903ed575..710e535a1 100644--- a/test/agent-tools.test.ts+++ b/test/agent-tools.test.ts@@ -51,6 +51,9 @@ function fakeToolContext(sink?: { lastExecOpts?: Parameters<ToolContext["executeurl: `/d/${input.name ?? "dep-1"}/`,};},+ async setDeploymentPublic(id, isPublic) {+ return { id, name: id, public: isPublic };+ },async createPlayground(input) {return { kind: "playground", artifactId: "playground-1", title: input.title };},@@ -3412,7 +3415,7 @@ test("resource catalog exposes one home per operation and leaves MCP tools intac],["apps",- { action: "publish", name: "demo" },+ { action: "publish", name: "demo", public: true },{ action: "publish", name: "demo", share: [{ scope: "org", permission: "read" }] },],[@@ -3433,12 +3436,17 @@ test("resource catalog exposes one home per operation and leaves MCP tools intactest("resource actions preserve sharing targets, transfer semantics and file contents", async () => {const writes: unknown[] = [];const shares: unknown[] = [];+ const publicChanges: unknown[] = [];const tc = {...fakeToolContext(),async write(...args: Parameters<ToolContext["write"]>) {writes.push(args);return { shared: [{ scope: "org:test", permission: "read" as const }] };},+ async setDeploymentPublic(id: string, isPublic: boolean) {+ publicChanges.push({ id, isPublic });+ return { id, name: id, public: isPublic };+ },async shareArtifact(req: Parameters<ToolContext["shareArtifact"]>[0]) {shares.push(req);return { ok: false as const, code: "forbidden" as const, message: "not the owner" };@@ -3471,6 +3479,26 @@ test("resource actions preserve sharing targets, transfer semantics and file con...(action === "move" ? { move: true } : {}),});}+ const publicResult = await call(+ tools.find((tool) => tool.name === "apps"),+ {+ action: "share",+ id: "artifact",+ public: true,+ },+ );+ assert.match(textOut(publicResult), /anyone with the link/);+ assert.deepEqual(publicChanges, [{ id: "artifact", isPublic: true }]);+ await call(+ tools.find((tool) => tool.name === "apps"),+ {+ action: "share",+ id: "artifact",+ email: "[email protected]",+ },+ );+ assert.deepEqual(shares.at(-1), { type: "deploy", id: "artifact", email: "[email protected]" });+const before = writes.length;await call(files, { action: "read", path: "notes", data: "unexpected" });await call(files, { action: "write", path: "notes" });diff --git a/test/deploy-access.test.ts b/test/deploy-access.test.tsindex 60260acdd..e554bc55d 100644--- a/test/deploy-access.test.ts+++ b/test/deploy-access.test.ts@@ -40,7 +40,17 @@ async function fixture(t: { after(fn: () => void): void }) {const acl = createAclStore();const auditLog = createAuditLog();const deliveries = createDeliveryStore();+ const identity = createIdentityService();+ const directory = createDirectoryStore();+ await directory.replace(+ [owner, requester, "[email protected]"].map((principalId) => ({+ principalId,+ displayName: principalId,+ type: "internal" as const,+ })),+ );const deploy = createDeployService({+ canManageEmail: async (email) => (await directory.get(email))?.type === "internal",deliveries,deployAppsDomain: "apps.example.com",deployStore: createDeployStore(),@@ -53,8 +63,6 @@ async function fixture(t: { after(fn: () => void): void }) {destroy: async () => {},},});- const identity = createIdentityService();- const directory = createDirectoryStore();const app = createApp({deploy,acl,diff --git a/test/deploy-app-only.test.ts b/test/deploy-app-only.test.tsnew file mode 100644index 000000000..0fc5e6c44--- /dev/null+++ b/test/deploy-app-only.test.ts@@ -0,0 +1,178 @@+import test from "node:test";+import assert from "node:assert/strict";+import { createServer, request } from "node:http";+import type { AddressInfo } from "node:net";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { createApp } from "../src/api/app.ts";+import { createServer as createApiServer } from "../src/api/server.ts";+import { createDeployStore } from "../src/deploy/deploy-store.ts";+import { createDeployService } from "../src/deploy/deploy-service.ts";+import { createAclStore } from "../src/acl/acl-store.ts";+import { createDirectoryStore } from "../src/directory/directory-store.ts";+import { createIdentityService } from "../src/identity/identity-service.ts";+import { createMemorySessionStore } from "../src/sessions/memory-session-store.ts";+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";++const secret = "app-only-gateway-test-secret-long-enough";+const guest = "[email protected]";+const key = deriveKey(secret, "portal.session.v1");+function token(appOnly: unknown = true) {+ const now = Math.floor(Date.now() / 1000);+ return seal({ k: "session", sub: guest, org: "acme", iat: now, exp: now + 3600, appOnly }, key);+}+test("gateway parser keeps app-only authority and rejects malformed signed markers", () => {+ assert.deepEqual(portalSession(`portal_session=${token()}`, secret), { sub: guest, appOnly: true });+ for (const marker of ["false", null, 0, {}])+ assert.equal(portalSession(`portal_session=${token(marker)}`, secret), null);+});++test("app-only gateway checks exact current personal read grants without inherited or management authority", async () => {+ const dir = mkdtempSync(join(tmpdir(), "app-only-gateway-"));+ let upstreamHits = 0;+ const upstream = createServer((req, res) => {+ upstreamHits++;+ res.setHeader("content-type", "application/json");+ res.end(JSON.stringify(req.headers));+ });+ await new Promise<void>((resolve) => upstream.listen(0, "127.0.0.1", resolve));+ const acl = createAclStore();+ const deploy = createDeployService({+ deployStore: createDeployStore({ git: { repoRoot: join(dir, "repos") } }),+ provider: {+ profile: { managedScaleToZero: false },+ apply: async () => ({ host: "127.0.0.1", port: (upstream.address() as AddressInfo).port }),+ destroy: async () => {},+ },+ auditLog: { record() {}, events: async () => [], tail: async () => [] },+ acl,+ deployDir: join(dir, "deploy"),+ });+ const identity = createIdentityService();+ const app = createApp({+ deploy,+ acl,+ directory: createDirectoryStore(),+ sessions: createMemorySessionStore(),+ identity,+ } as unknown as Parameters<typeof createApp>[0]);+ const ownerScopeId = scopeId("personal", "[email protected]");+ const shared = await app.deploy({+ ownerScopeId,+ createdBy: "[email protected]",+ entrypoint: "node app.js",+ files: [],+ name: "shared",+ });+ await app.deploy({+ ownerScopeId: scopeId("org", "acme"),+ createdBy: "[email protected]",+ entrypoint: "node app.js",+ files: [],+ name: "org-app",+ });+ app.canManageDeployment = async () => {+ throw new Error("app-only must not consult management authority");+ };+ app.effectiveDeploymentPermission = async () => {+ throw new Error("app-only must not consult inherited permission");+ };+ const server = createApiServer(app, {+ identity,+ signingSecret: secret,+ deployAppsDomain: "apps.example.test",+ deployGateSecret: "gate",+ deployAppsSessionSecret: secret,+ deployAppsLoginUrl: "https://portal.example.test",+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const port = (server.address() as AddressInfo).port;+ const cookie = `portal_session=${token()}`;+ const get = (name: string, path = "/", method = "GET") =>+ new Promise<{ status: number; body: string }>((resolve, reject) => {+ const req = request(+ {+ host: "127.0.0.1",+ port,+ path,+ method,+ headers: {+ host: `${name}.apps.example.test`,+ cookie,+ "sec-fetch-dest": "document",+ accept: "application/json",+ "x-portal-identity": "forged",+ },+ },+ (res) => {+ let body = "";+ res.on("data", (chunk) => {+ body += chunk;+ });+ res.on("end", () => resolve({ status: res.statusCode!, body }));+ },+ );+ req.on("error", reject);+ req.end();+ });+ try {+ assert.equal((await get("shared")).status, 403);+ assert.equal((await get("org-app")).status, 403, "org ownership is not an app-only entitlement");+ for (const granteeScopeId of [scopeId("org", "acme"), scopeId("channel", "C1")]) {+ await acl.grant({+ ownerScopeId,+ ref: encodeRef(deployRef(shared.id)),+ granteeScopeId,+ permission: "read",+ grantedBy: "[email protected]",+ });+ }+ assert.equal((await get("shared")).status, 403, "scope grants never admit app-only sessions");+ await acl.grant({+ ownerScopeId,+ ref: encodeRef(deployRef(shared.id)),+ granteeScopeId: scopeId("personal", guest),+ permission: "write",+ grantedBy: "[email protected]",+ });+ assert.equal((await get("shared")).status, 403, "a write grant cannot confer app-only management access");+ assert.equal(upstreamHits, 0);+ await app.shareDeployment(shared.id, scopeId("personal", guest), "read", { createdBy: "[email protected]" });+ const granted = await get("shared", "/api/data", "POST");+ assert.equal(granted.status, 200, "read grants allow using the app, including its POST API");+ assert.equal(JSON.parse(granted.body).cookie, undefined, "gateway cookie never reaches app");+ assert.notEqual(JSON.parse(granted.body)["x-portal-identity"], "forged");+ assert.equal((await get("shared", "/__claw__/version")).status, 200, "request goes to app, never management shell");+ assert.equal((await get("org-app")).status, 403, "grant is for one deployment only");+ await identity.deactivate(guest, "manual");+ assert.equal((await get("shared")).status, 403, "manual deactivation overrides the current direct grant");+ await identity.reactivate(guest);+ await app.shareDeployment(shared.id, scopeId("personal", guest), null, { createdBy: "[email protected]" });+ assert.equal((await get("shared")).status, 403, "same session is refused immediately after revoke");+ await app.shareDeployment(shared.id, scopeId("personal", guest), "read", { createdBy: "[email protected]" });+ await app.renameDeployment(shared.id, "renamed");+ await app.deploy({+ ownerScopeId,+ createdBy: "[email protected]",+ entrypoint: "node app.js",+ files: [],+ name: "shared",+ });+ assert.equal((await get("shared")).status, 403, "reused name does not inherit old immutable-ID grant");+ assert.equal((await get("renamed")).status, 200, "same immutable app retains its grant after rename");+ await app.archiveDeployment(shared.id);+ assert.equal((await get("renamed")).status, 404, "archived app cannot be reached even with its grant");+ await app.setDeploymentPublic("shared", true, { createdBy: "[email protected]" });+ const publicVisit = await get("shared");+ assert.equal(publicVisit.status, 200);+ assert.equal(JSON.parse(publicVisit.body)["x-portal-identity"], undefined, "public link access remains anonymous");+ } finally {+ await new Promise<void>((resolve) => server.close(() => resolve()));+ await new Promise<void>((resolve) => upstream.close(() => resolve()));+ rmSync(dir, { recursive: true, force: true });+ }+});diff --git a/test/deploy-subdomain-signin.test.ts b/test/deploy-subdomain-signin.test.tsindex e88ad0d57..536007262 100644--- a/test/deploy-subdomain-signin.test.ts+++ b/test/deploy-subdomain-signin.test.ts@@ -14,7 +14,8 @@ import { createAclStore } from "../src/acl/acl-store.ts";import { createDirectoryStore } from "../src/directory/directory-store.ts";import { createIdentityService } from "../src/identity/identity-service.ts";import { createMemorySessionStore } from "../src/sessions/memory-session-store.ts";-import { portalSessionSub } from "../src/deploy/viewer-session.ts";+import { PORTAL_IDENTITY_HEADER } from "../src/auth/portal-identity.ts";+import { portalSession } from "../src/deploy/viewer-session.ts";import { scopeId } from "../src/types.ts";const auditLog = { record() {}, events: async () => [], tail: async () => [] };@@ -31,30 +32,36 @@ function mintPortalSession(sub: string, expInSeconds = 3600, secret = SESSION_SEreturn `${body}.${sig}`;}-test("portalSessionSub: verifies, and rejects tampering, expiry, wrong kind, wrong secret", () => {+test("portalSession: verifies, and rejects tampering, expiry, wrong kind, wrong secret", () => {const good = mintPortalSession("[email protected]");- assert.equal(portalSessionSub(`portal_session=${good}`, SESSION_SECRET), "[email protected]");- assert.equal(portalSessionSub(`other=1; portal_session=${good}; x=2`, SESSION_SECRET), "[email protected]");- assert.equal(portalSessionSub(`portal_session=${good}x`, SESSION_SECRET), null, "tampered signature");- assert.equal(- portalSessionSub(`portal_session=junk; portal_session=${good}`, SESSION_SECRET),- "[email protected]",+ assert.deepEqual(portalSession(`portal_session=${good}`, SESSION_SECRET), {+ sub: "[email protected]",+ appOnly: false,+ });+ assert.deepEqual(portalSession(`other=1; portal_session=${good}; x=2`, SESSION_SECRET), {+ sub: "[email protected]",+ appOnly: false,+ });+ assert.deepEqual(portalSession(`portal_session=${good}x`, SESSION_SECRET), null, "tampered signature");+ assert.deepEqual(+ portalSession(`portal_session=junk; portal_session=${good}`, SESSION_SECRET),+ { sub: "[email protected]", appOnly: false },"an app's junk same-named cookie cannot shadow the real session",);- assert.equal(portalSessionSub(`portal_session=${good}`, "other-secret"), null, "wrong secret");- assert.equal(- portalSessionSub(`portal_session=${mintPortalSession("[email protected]", -10)}`, SESSION_SECRET),+ assert.deepEqual(portalSession(`portal_session=${good}`, "other-secret"), null, "wrong secret");+ assert.deepEqual(+ portalSession(`portal_session=${mintPortalSession("[email protected]", -10)}`, SESSION_SECRET),null,"expired",);- assert.equal(portalSessionSub(undefined, SESSION_SECRET), null);- assert.equal(portalSessionSub("portal_session=", SESSION_SECRET), null);+ assert.deepEqual(portalSession(undefined, SESSION_SECRET), null);+ assert.deepEqual(portalSession("portal_session=", SESSION_SECRET), null);const key = createHmac("sha256", SESSION_SECRET).update("portal.session.v1").digest();const body = Buffer.from(JSON.stringify({ k: "impersonate", sub: "eve", exp: Math.floor(Date.now() / 1000) + 60 }),).toString("base64url");const sig = createHmac("sha256", key).update(body).digest("base64url");- assert.equal(portalSessionSub(`portal_session=${body}.${sig}`, SESSION_SECRET), null, "non-session claims");+ assert.deepEqual(portalSession(`portal_session=${body}.${sig}`, SESSION_SECRET), null, "non-session claims");});test("forwarded app hosts fail closed before core routes when gateway configuration is absent", async () => {@@ -94,13 +101,16 @@ function httpGet(}test("app sign-in uses the configured trusted entry and preserves the app return address", async () => {- const server = createInsecureTestServer({} as Parameters<typeof createInsecureTestServer>[0], {- deployAppsDomain: "apps.example.com",- deployGateSecret: "gate",- deployAppsSessionSecret: SESSION_SECRET,- deployAppsLoginUrl: LOGIN_URL,- deployAppsLoginPath: "/auth/trusted/login",- });+ const server = createInsecureTestServer(+ { getDeployment: async () => null } as unknown as Parameters<typeof createInsecureTestServer>[0],+ {+ deployAppsDomain: "apps.example.com",+ deployGateSecret: "gate",+ deployAppsSessionSecret: SESSION_SECRET,+ deployAppsLoginUrl: LOGIN_URL,+ deployAppsLoginPath: "/auth/trusted/login",+ },+ );server.listen(0);try {const result = await httpGet((server.address() as AddressInfo).port, "/counter?x=1", {@@ -135,9 +145,11 @@ function httpPost(test("subdomain ingress: portal sign-in admits the owner, denies strangers, bounces the signed-out", async () => {let upstreamCookie: string | undefined = "unset";+ let upstreamIdentity: string | undefined = "unset";let upstreamUrl = "";const upstream = createHttpServer((req, res) => {upstreamCookie = req.headers.cookie as string | undefined;+ upstreamIdentity = req.headers[PORTAL_IDENTITY_HEADER] as string | undefined;upstreamUrl = req.url ?? "";res.writeHead(200, {"content-type": "text/plain",@@ -208,6 +220,26 @@ test("subdomain ingress: portal sign-in admits the owner, denies strangers, bounassert.equal(xhr.status, 401, "a non-HTML request never gets a login redirect");assert.match(xhr.body, /loginUrl/, "…but is told where sign-in lives");+ await app.setDeploymentPublic("mysite", true, { createdBy: "[email protected]" });+ const publicVisitor = await httpGet(port, "/consultants?x=1", { Host: host, Accept: "text/html,*/*" });+ assert.equal(publicVisitor.status, 200, "a public app is reachable without a portal session");+ assert.equal(publicVisitor.body, "UPSTREAM OK");+ assert.equal(upstreamCookie, undefined, "an anonymous request forwards no gateway cookies");+ assert.equal(upstreamIdentity, undefined, "an anonymous request forwards no viewer identity");++ const signedInPublicVisitor = await httpGet(port, "/consultants", {+ Host: host,+ Accept: "text/html",+ Cookie: `portal_session=${mintPortalSession("[email protected]")}`,+ });+ assert.equal(signedInPublicVisitor.status, 200);+ assert.equal(+ upstreamIdentity,+ undefined,+ "a link-only public visitor stays anonymous even when a portal session cookie is present",+ );+ await app.setDeploymentPublic("mysite", false, { createdBy: "[email protected]" });+const backFromLogin = await httpGet(port, "/consultants?x=1&dpl_signin=1", {Host: host,Accept: "text/html",diff --git a/test/share-deployment.test.ts b/test/share-deployment.test.tsindex d94afead0..e049c5f71 100644--- a/test/share-deployment.test.ts+++ b/test/share-deployment.test.ts@@ -1,3 +1,6 @@+import { authBrokerRoutes } from "../src/api/routes/auth-broker.ts";+import { createDirectoryStore } from "../src/directory/directory-store.ts";+import { createControlService } from "../src/api/control-service.ts";import { test } from "node:test";import assert from "node:assert/strict";import { mkdtempSync } from "node:fs";@@ -27,7 +30,7 @@ import { scopeId } from "../src/types.ts";type Dir = { resolve: (orgId: string, q: string) => Promise<RecipientResolution> };-function makeDeploy(): { deploy: DeployService; acl: AclStore } {+function makeDeploy(canManageEmail?: (email: string) => Promise<boolean>): { deploy: DeployService; acl: AclStore } {const acl: AclStore = createAclStore();const deploy = createDeployService({deployStore: createDeployStore(),@@ -38,6 +41,7 @@ function makeDeploy(): { deploy: DeployService; acl: AclStore } {},auditLog: { record() {}, events: async () => [], tail: async () => [] },acl,+ ...(canManageEmail ? { canManageEmail } : {}),deployDir: mkdtempSync(join(tmpdir(), "share-api-")),});return { deploy, acl };@@ -291,6 +295,12 @@ test("share endpoint: unknown app → 404; no capability → 403; bad/ambiguous/"bad access → 400",);assert.equal((await callShare(app, cap("U1"), "a", {})).status, 400, "no target → 400");+ assert.equal((await callShare(app, cap("U1"), "a", { public: "yes" })).status, 400, "public is boolean");+ assert.equal(+ (await callShare(app, cap("U1"), "a", { public: true, scope: "org" })).status,+ 400,+ "public and authenticated targets change separately",+ );assert.equal((await callShare(app, cap("U1"), "a", { scope: "org", recipient: "carol" })).status,400,@@ -404,6 +414,17 @@ test('publish share:[{scope:"org"}] resolves to the org — truthful readback, rassert.equal((await deploy.reachDeployment("wide", "U2")).status, "ok");});+test("publish keeps apps private by default and requires an explicit public opt-in", async () => {+ const { deploy } = makeDeploy();+ const privateApp = await toolCtx(deploy).publish({ entrypoint: "x", name: "private-app" });+ assert.equal(privateApp.public, undefined);+ assert.equal((await deploy.getDeployment("private-app"))?.public, undefined);++ const publicApp = await toolCtx(deploy).publish({ entrypoint: "x", name: "public-app", public: true });+ assert.equal(publicApp.public, true);+ assert.equal((await deploy.getDeployment("public-app"))?.public, true);+});+test("publish rejects a garbage share target instead of silently creating a dead grant", async () => {const { deploy } = makeDeploy();await assert.rejects(@@ -445,6 +466,31 @@ test("transferDeploymentOwner re-homes the app to the teammate: they own it, pri);});+test("a manage grantee may redeploy but cannot make the owner's app public", async () => {+ const { deploy } = makeDeploy();+ const d = await deploy.deploy({+ ownerScopeId: scopeId("personal", "U1"),+ createdBy: "U1",+ entrypoint: "x",+ files: [],+ name: "managed-private",+ });+ await deploy.shareDeployment(d.id, scopeId("personal", "U2"), "write", { createdBy: "U1" });+ await assert.rejects(+ () =>+ deploy.deployOrUpdate({+ ownerScopeId: scopeId("personal", "U2"),+ createdBy: "U2",+ name: "managed-private",+ entrypoint: "x",+ files: [],+ public: true,+ }),+ /only the owner/,+ );+ assert.equal((await deploy.getDeployment(d.id))?.public, undefined);+});+test("transferDeploymentOwner is home authority — a write ('manage') grantee cannot give the app away", async () => {const { deploy } = makeDeploy();const d = await deploy.deploy({@@ -479,6 +525,40 @@ test("transferDeploymentOwner to the current home is a no-op", async () => {assert.equal((await acl.list()).length, 0, "no self-grant sprayed by a no-op transfer");});+test("deployment public access is explicit, owner-only, and reversible", async () => {+ const { app } = apiHarness();+ await app.deploy({+ ownerScopeId: scopeId("personal", "U1"),+ createdBy: "U1",+ entrypoint: "x",+ files: [],+ name: "public-toggle",+ });++ const initial = await callManage(getDeploymentShares, app, cap("U1"), "public-toggle", {});+ assert.equal(initial.status, 200);+ assert.equal(initial.body.public, false, "apps are private by default");++ const denied = await callShare(app, cap("U2"), "public-toggle", { public: true });+ assert.equal(denied.status, 403, "only the owner may make an app public");++ const enabled = await callShare(app, cap("U1"), "public-toggle", { public: true });+ assert.equal(enabled.status, 200);+ assert.equal(enabled.body.public, true);+ assert.equal((await app.getDeployment("public-toggle"))?.public, true);++ const sharedWhilePublic = await callShare(app, cap("U1"), "public-toggle", {+ scope: "personal:U2",+ access: "view",+ });+ assert.equal(sharedWhilePublic.body.public, true, "person changes preserve and return general access");++ const disabled = await callShare(app, cap("U1"), "public-toggle", { public: false });+ assert.equal(disabled.status, 200);+ assert.equal(disabled.body.public, false);+ assert.equal((await app.getDeployment("public-toggle"))?.public, undefined);+});+test("deployment permissions are visible only to the owner, including for managers", async () => {const { app } = apiHarness();await app.deploy({@@ -498,3 +578,252 @@ test("deployment permissions are visible only to the owner, including for manageawait callShare(app, cap("U1"), "permissions", { scope: "personal:U2", access: "none" });assert.deepEqual((await callManage(getDeploymentShares, app, cap("U1"), "permissions", {})).body.grantees, []);});++test("app email grants normalize, dedupe, revoke, and reject external manage without changing the grant", async () => {+ const { app, deploy } = apiHarness();+ await app.deploy({ ownerScopeId: "personal:U1", createdBy: "U1", entrypoint: "x", files: [], name: "email-app" });+ for (const email of [" [email protected] ", "[email protected]"]) {+ const r = await callShare(app, cap("U1"), "email-app", { email });+ assert.equal(r.status, 200);+ assert.equal(r.body.target.scope, "personal:[email protected]");+ }+ const expected = [{ scope: "personal:[email protected]", permission: "read" }];+ assert.deepEqual(await deploy.deploymentGrantees("email-app"), expected);+ assert.equal((await deploy.reachDeployment("email-app", "[email protected]")).status, "ok");+ assert.equal((await deploy.reachDeployment("email-app", "[email protected]")).status, "denied");+ for (const body of [+ { email: "[email protected]", access: "manage" },+ { scope: "personal:[email protected]", access: "manage" },+ { email: "not an email" },+ { email: 123 },+ { email: "[email protected]", scope: "org" },+ { email: "[email protected]", recipient: "other" },+ { email: "[email protected]", public: true },+ ])+ assert.equal((await callShare(app, cap("U1"), "email-app", body)).status, 400);+ assert.equal((await callShare(app, cap("U2"), "email-app", { email: "[email protected]" })).status, 403);+ assert.deepEqual(await deploy.deploymentGrantees("email-app"), expected);+ assert.equal(+ (await callShare(app, cap("U1"), "email-app", { email: "[email protected]", access: "none" })).status,+ 200,+ );+ assert.deepEqual(await deploy.deploymentGrantees("email-app"), []);+});++test("directory email recipients retain manage access", async () => {+ const { deploy } = makeDeploy(async (email) => email === "[email protected]");+ const d = await deploy.deploy({ ownerScopeId: "personal:U1", createdBy: "U1", entrypoint: "x", files: [] });+ await deploy.shareDeployment(d.id, "personal:[email protected]", "write", { createdBy: "U1" });+ assert.deepEqual(await deploy.deploymentGrantees(d.id), [+ { scope: "personal:[email protected]", permission: "write" },+ ]);+ assert.equal(await deploy.canManageDeployment(d.id, "[email protected]"), true);+});++test("exact email read grants admit app-only login and guest reach without membership or source access", async () => {+ const { deploy, acl } = makeDeploy();+ const identity = createIdentityService();+ const directory = createDirectoryStore();+ const app = createApp({ deploy, acl, identity, directory, auditLog: { record() {} } } as unknown as Parameters<+ typeof createApp+ >[0]);+ const d = await app.deploy({+ ownerScopeId: "personal:U1",+ createdBy: "U1",+ entrypoint: "x",+ files: [],+ name: "invite-test",+ });+ const email = "[email protected]";+ await identity.deactivate(email, "directory-sync");+ assert.equal(identity.classify(email).type, "guest");+ const allowed = async (email: string) => {+ 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 },+ url: new URL(`http://core/v1/auth/broker/email-allowed?email=${encodeURIComponent(email)}`),+ res: {+ writeHead(s: number) {+ status = s;+ },+ end(s: string) {+ body = JSON.parse(s);+ },+ },+ } as unknown as ApiCtx);+ assert.equal(status, 200);+ return body;+ };+ assert.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 protected]"), { allowed: false });+ assert.equal(await app.effectiveDeploymentPermission(d, "[email protected]"), "read");+ assert.equal(await app.effectiveDeploymentPermission(d, "[email protected]"), null);+ assert.equal(await app.deploymentGitPermissionFor(d.id, email), null);+ assert.equal((await app.reachDeployment(d.id, email)).status, "ok");+ assert.equal(await app.directoryMember(email), null);+ assert.equal(identity.externalMember(email), undefined);+ assert.equal(identity.classify(email).type, "guest");+ await app.archiveDeployment(d.id);+ assert.deepEqual(await allowed(email), { allowed: false });+ await app.restoreDeployment(d.id, "U1");+ await identity.deactivate(email);+ assert.deepEqual(await allowed(email), { allowed: false });+ assert.equal(await app.effectiveDeploymentPermission(d, email), null);+ await identity.reactivate(email);+ await app.shareDeployment(d.id, `personal:${email}`, null, { createdBy: "U1" });+ assert.deepEqual(await allowed(email), { allowed: false });+ assert.equal(await app.effectiveDeploymentPermission(d, email), null);+ for (const grant of [+ { ref: `deployment:${d.id}`, granteeScopeId: `personal:${email}`, permission: "write" as const },+ { ref: "deployment:missing", granteeScopeId: `personal:${email}`, permission: "read" as const },+ { ref: `deployment:${d.id}`, granteeScopeId: "org:default-org" as const, permission: "read" as const },+ ])+ await acl.grant({ ownerScopeId: "personal:U1", grantedBy: "U1", ...grant });+ assert.deepEqual(+ await allowed(email),+ { allowed: false },+ "write, dangling and org grants do not admit an app-only login",+ );+});++test("uniform app share accepts exact emails and enforces view-only outside the directory", async () => {+ const { deploy, acl } = makeDeploy();+ const app = createApp({+ deploy,+ acl,+ identity: createIdentityService(),+ directory: createDirectoryStore(),+ auditLog: { record() {} },+ } as unknown as Parameters<typeof createApp>[0]);+ const d = await app.deploy({ ownerScopeId: "personal:U1", createdBy: "U1", entrypoint: "x", files: [] });+ const control = createControlService(app);+ const r = await control.shareArtifact({ type: "deploy", id: d.id, email: "[email protected]" }, cap("U1"));+ assert.ok(r.ok, JSON.stringify(r));+ assert.equal(r.target.scope, "personal:[email protected]");+ const blocked = await control.shareArtifact(+ { type: "deploy", id: d.id, email: "[email protected]", permission: "write" },+ cap("U1"),+ );+ assert.equal(blocked.ok, false);+ assert.deepEqual(await deploy.deploymentGrantees(d.id), [+ { scope: "personal:[email protected]", permission: "read" },+ ]);+ const moved = await control.shareArtifact(+ { type: "deploy", id: d.id, email: "[email protected]", move: true },+ cap("U1"),+ );+ assert.equal(moved.ok, false);+});++test("new email grants send an app-specific invitation once; re-adds and revocations send nothing", async () => {+ const { deploy, acl } = makeDeploy();+ const sent: Array<{ to: string; subject: string; text: string; html: string }> = [];+ const app = createApp({+ deploy,+ acl,+ identity: createIdentityService(),+ deployAppsDomain: "apps.example.com",+ inviteMailer: {+ async send(message: (typeof sent)[number]) {+ sent.push(message);+ return "message-id";+ },+ },+ } as unknown as Parameters<typeof createApp>[0]);+ const d = await app.deploy({+ ownerScopeId: "personal:U1",+ createdBy: "U1",+ entrypoint: "x",+ files: [],+ name: "status-page",+ });+ await app.setDeploymentDisplayName(d.id, "Status <page>");+ const added = await callShare(app, cap("U1"), d.id, { email: " [email protected] " });+ assert.equal(added.status, 200);+ assert.deepEqual(added.body.invitation, { emailSent: true, appUrl: "https://status-page.apps.example.com/" });+ assert.equal(sent.length, 1);+ assert.equal(sent[0]!.to, "[email protected]");+ assert.equal(sent[0]!.subject, "You've been invited to Status <page>");+ assert.match(sent[0]!.text, /Sign in using this email address \([email protected]\)/);+ assert.match(sent[0]!.text, /https:\/\/status-page\.apps\.example\.com\//);+ assert.doesNotMatch(sent[0]!.text, /single-use|token=/);+ assert.match(sent[0]!.html, /Status <page>/);+ const repeated = await Promise.all(+ ["[email protected]", "[email protected]"].map((email) => callShare(app, cap("U1"), d.id, { email })),+ );+ assert.ok(repeated.every((r) => r.body.invitation.alreadyShared && !r.body.invitation.emailSent));+ assert.equal(sent.length, 1);+ await callShare(app, cap("U1"), d.id, { email: "[email protected]", access: "none" });+ assert.equal(sent.length, 1);+ const addedConcurrently = await Promise.all(+ ["[email protected]", "[email protected]"].map((email) => callShare(app, cap("U1"), d.id, { email })),+ );+ assert.equal(addedConcurrently.filter((r) => r.body.invitation.emailSent).length, 1);+ assert.equal(sent.length, 2);+});++test("failed invitation delivery leaves the grant and reports the failure and manual app link", async () => {+ for (const mailer of [+ undefined,+ {+ async send() {+ throw new Error("mail unavailable");+ },+ },+ ]) {+ const { deploy, acl } = makeDeploy();+ const app = createApp({+ deploy,+ acl,+ identity: createIdentityService(),+ deployAppsDomain: "apps.example.com",+ inviteMailer: mailer,+ } as unknown as Parameters<typeof createApp>[0]);+ const d = await app.deploy({+ ownerScopeId: "personal:U1",+ createdBy: "U1",+ entrypoint: "x",+ files: [],+ name: "status-page",+ });+ const added = await callShare(app, cap("U1"), d.id, { email: "[email protected]" });+ assert.equal(added.status, 200);+ assert.equal(added.body.invitation.emailSent, false);+ assert.match(added.body.invitation.emailProblem, mailer ? /mail unavailable/ : /not configured/);+ assert.equal(added.body.invitation.appUrl, "https://status-page.apps.example.com/");+ assert.deepEqual(await deploy.deploymentGrantees(d.id), [+ { scope: "personal:[email protected]", permission: "read" },+ ]);+ }+});++test("uniform app share uses the same invitation sender", async () => {+ const { deploy, acl } = makeDeploy();+ const sent: string[] = [];+ const app = createApp({+ deploy,+ acl,+ identity: createIdentityService(),+ directory: createDirectoryStore(),+ deployAppsDomain: "apps.example.com",+ inviteMailer: {+ async send(message: { to: string }) {+ sent.push(message.to);+ return "sent";+ },+ },+ } as unknown as Parameters<typeof createApp>[0]);+ const d = await app.deploy({ ownerScopeId: "personal:U1", createdBy: "U1", entrypoint: "x", files: [] });+ const result = await createControlService(app).shareArtifact(+ { type: "deploy", id: d.id, email: "[email protected]" },+ cap("U1"),+ );+ assert.ok(result.ok, JSON.stringify(result));+ assert.equal(result.invitation?.emailSent, true);+ assert.deepEqual(sent, ["[email protected]"]);+});