Multiplayer agent harness for work.
feat: invite external users by email with role and expiry
Sina Matian0e1aeaa0beec
diff --git a/cli/src/preflight.ts b/cli/src/preflight.tsindex 63b3268a9..7550fe2b3 100644--- a/cli/src/preflight.ts+++ b/cli/src/preflight.ts@@ -278,9 +278,9 @@ export async function emailTransportPreflight(config: QmConfig, secrets: Readonlreturn;}if (value("RESEND_API_KEY")) {- warn(- 'RESEND_API_KEY is set but env.auth.AUTH_EMAIL_TRANSPORT is "smtp" — the value is unused; ' +- 'remove it or set the transport to "resend"',+ step(+ 'RESEND_API_KEY is set but env.auth.AUTH_EMAIL_TRANSPORT is "smtp" — the sign-in broker ignores it; ' ++ "core still uses it to email external-user invitations",);}const host = value("SMTP_HOST");diff --git a/cli/src/secrets.ts b/cli/src/secrets.tsindex d0291789e..1522ea68a 100644--- a/cli/src/secrets.ts+++ b/cli/src/secrets.ts@@ -392,13 +392,27 @@ export const FIRST_PARTY_SECRET_SPECS: readonly SecretSpec[] = [name: "AUTH_EMAIL_FROM",service: "auth",required: true,- description: 'Verified sender for sign-in links, e.g. "Acme <[email protected]>".',+ description: 'Verified sender for sign-in links and external-user invitations, e.g. "Acme <[email protected]>".',+ },+ {+ name: "AUTH_EMAIL_FROM",+ service: "core",+ required: false,+ description:+ "Sender for external-user invitations sent from the admin Users tab or by chatting with QM; the same verified sender the sign-in broker uses.",},{name: "RESEND_API_KEY",service: "auth",required: { when: { kind: "env-equals", service: "auth", name: "AUTH_EMAIL_TRANSPORT", value: "resend" } },- description: "Resend API key used to deliver sign-in links.",+ description: "Resend API key used to deliver sign-in links and external-user invitations.",+ },+ {+ name: "RESEND_API_KEY",+ service: "core",+ required: false,+ description:+ "Lets core email invitations to external users, added from the admin Users tab or by chatting with QM, through Resend.",},{name: "SMTP_HOST",diff --git a/cli/src/services.ts b/cli/src/services.tsindex a07a21945..014ac2011 100644--- a/cli/src/services.ts+++ b/cli/src/services.ts@@ -154,6 +154,7 @@ export function brokerWiring(...(o.allowedEmailDomain ? { OIDC_ALLOWED_EMAIL_DOMAIN: o.allowedEmailDomain } : {}),};}+ if (service === "core") return o.allowedEmailDomain ? { AUTH_ALLOWED_EMAIL_DOMAIN: o.allowedEmailDomain } : {};if (service === "auth") {return {AUTH_ISSUER: issuer,@@ -164,16 +165,19 @@ export function brokerWiring(return {};}-const pluginWiring = (service: string, s: ServiceCtx): Record<string, string> => ({- CORE_API_URL: s.coreUrl,- ...orgEnv(service, s.orgId, s.publicUrl, s.hasPortal, s.brand),- ...(s.hasAuth+const brokerEnv = (service: string, s: ServiceCtx): Record<string, string> =>+ s.hasAuth? brokerWiring(service, {publicUrl: s.publicUrl,authBaseUrl: s.authUrl,...(s.authAllowedEmailDomain ? { allowedEmailDomain: s.authAllowedEmailDomain } : {}),})- : {}),+ : {};++const pluginWiring = (service: string, s: ServiceCtx): Record<string, string> => ({+ CORE_API_URL: s.coreUrl,+ ...orgEnv(service, s.orgId, s.publicUrl, s.hasPortal, s.brand),+ ...brokerEnv(service, s),});const CATALOG: Record<ServiceName, ServiceDef> = {@@ -186,6 +190,7 @@ const CATALOG: Record<ServiceName, ServiceDef> = {fly: {managed: (s) => ({...orgEnv("core", s.orgId, s.publicUrl, s.hasPortal, s.brand),+ ...brokerEnv("core", s),FLY_DEPLOY_APP_PREFIX: s.deployAppPrefix,}),stackKeys: [diff --git a/cli/templates/deployment/references/email.md b/cli/templates/deployment/references/email.mdindex 8abfda16d..2288f4e5d 100644--- a/cli/templates/deployment/references/email.md+++ b/cli/templates/deployment/references/email.md@@ -97,6 +97,16 @@ verified address; for a whole team, the operator requests production accessfrom the SES console (usually granted within a day) or verifies eachrecipient.+## Invitation emails for external users++Admins invite people outside the organization from the admin Users tab or by+chatting with QM. Core emails those invitations through Resend, so the CLI+delivers `RESEND_API_KEY` and `AUTH_EMAIL_FROM` to core as well as to the+broker. Both are optional on core: without them the invitation is still created+and the admin shares the sign-in link by hand. Core also receives+`AUTH_ALLOWED_EMAIL_DOMAIN`, so an address in the organization's own domain is+refused as an external user; those people sign in directly.+## Who may sign inSet one of these, or the broker refuses to start:diff --git a/cli/test/auth-broker.test.ts b/cli/test/auth-broker.test.tsindex 45028eb06..c14ead7ac 100644--- a/cli/test/auth-broker.test.ts+++ b/cli/test/auth-broker.test.ts@@ -67,6 +67,9 @@ test("fly derives the portal's whole OIDC block from the broker, over the privatassert.match(portal, /OIDC_ALLOWED_EMAIL_DOMAIN = "example\.com"/);assert.doesNotMatch(portal, /accounts\.google\.com|slack\.com/, "the template's external-IdP defaults are replaced");+ const core = derivedTomlFor(brokerConfig(), "core", repoRoot);+ assert.match(core, /AUTH_ALLOWED_EMAIL_DOMAIN = "example\.com"/, "core refuses in-domain external invites");+const auth = derivedTomlFor(brokerConfig(), "auth", repoRoot);assert.equal(auth, readFileSync(join(repoRoot, "deploy", "auth", "fly.toml"), "utf8"));assert.match(auth, /AUTH_ISSUER = "https:\/\/agent\.example\.com\/idp"/);@@ -125,6 +128,7 @@ test("docker and AWS wire the broker with parity", () => {assert.equal(awsPortal.AUTH_BROKER_UPSTREAM, "http://auth.acme.internal:8080");assert.equal(awsPortal.OIDC_JWKS_URI, "http://auth.acme.internal:8080/.well-known/jwks.json");assert.equal(awsPortal.OIDC_ALLOWED_EMAIL_DOMAIN, "example.com");+ assert.equal(serviceEnvironment(aws, "core").AUTH_ALLOWED_EMAIL_DOMAIN, "example.com");assert.equal(awsPortal.PORTAL_XFF_TRUSTED_HOPS,"1",@@ -166,6 +170,12 @@ test("the broker's generated secrets reach both sides under the right names", ()assert.ok(!names.has("AUTH_ALLOWED_EMAILS"), "a configured domain removes the per-address allowlist requirement");assert.ok(names.has("RESEND_API_KEY"));assert.ok(!names.has("SMTP_HOST"), "only the configured transport's credentials are collected");+ for (const name of ["RESEND_API_KEY", "AUTH_EMAIL_FROM"]) {+ const shared = secrets.find((secret) => secret.name === name)!;+ assert.ok(shared.required);+ assert.deepEqual(runtimeSecretNames("auth", shared), [name]);+ assert.deepEqual(runtimeSecretNames("core", shared), [name], `core emails external-user invitations with ${name}`);+ }assert.ok(secretsForService(config, "auth").some((secret) => secret.name === "CORE_SIGNING_SECRET"));});@@ -178,7 +188,10 @@ test("without a configured domain the allowlist becomes a required secret on botassert.deepEqual(runtimeSecretNames("core", allowed), ["AUTH_ALLOWED_EMAILS"]);const names = new Set(computedSecrets(config).map((secret) => secret.name));for (const name of ["SMTP_HOST", "SMTP_USERNAME", "SMTP_PASSWORD"]) assert.ok(names.has(name), name);- assert.ok(!names.has("RESEND_API_KEY"));+ const resend = computedSecrets(config).find((secret) => secret.name === "RESEND_API_KEY")!;+ assert.equal(resend.required, false, "the unselected transport's key stays optional");+ assert.deepEqual(runtimeSecretNames("auth", resend), []);+ assert.deepEqual(runtimeSecretNames("core", resend), ["RESEND_API_KEY"], "core alone keeps it for invitations");});test("the config refuses a broker without a portal, a bad transport, and hand-set derived env", () => {diff --git a/cli/test/init.test.ts b/cli/test/init.test.tsindex 1c334e40a..3ba0f6004 100644--- a/cli/test/init.test.ts+++ b/cli/test/init.test.ts@@ -197,8 +197,12 @@ test("init --email-transport smtp scaffolds smtp keys only and a matching configfor (const line of ["SMTP_HOST=", "SMTP_USERNAME=", "SMTP_PASSWORD="]) {assert.ok(env.split("\n").includes(line), `.env.example should require ${line}`);}- assert.ok(!env.includes("RESEND_API_KEY"), "the unselected resend transport's key stays out of .env.example");- assert.ok(!readFileSync(join(dir, ".env"), "utf8").includes("RESEND_API_KEY"), "and out of .env");+ assert.ok(+ env.split("\n").includes("# RESEND_API_KEY= # optional"),+ "the unselected resend transport's key stays optional: core alone uses it for external-user invitations",+ );+ assert.ok(!env.split("\n").includes("RESEND_API_KEY="), "and is never required");+ assert.ok(!readFileSync(join(dir, ".env"), "utf8").split("\n").includes("RESEND_API_KEY="), "in .env either");} finally {rmSync(dir, { recursive: true, force: true });}diff --git a/cli/test/preflight.test.ts b/cli/test/preflight.test.tsindex cc1a73cee..79c4746e7 100644--- a/cli/test/preflight.test.ts+++ b/cli/test/preflight.test.ts@@ -157,7 +157,10 @@ test("email preflight fails check on rejected SMTP credentials and warns on stra),);assert.ok(okLines.some((line) => line.includes("credentials accepted")));- assert.ok(okLines.some((line) => line.includes("RESEND_API_KEY is set but")));+ assert.ok(+ okLines.some((line) => line.includes("RESEND_API_KEY is set but") && line.includes("external-user invitations")),+ "a Resend key beside an SMTP broker is core's invitation sender, not a stray value",+ );await assert.rejects(() =>emailTransportPreflight(diff --git a/cli/test/secrets.test.ts b/cli/test/secrets.test.tsindex c10f89908..25db02b84 100644--- a/cli/test/secrets.test.ts+++ b/cli/test/secrets.test.ts@@ -335,6 +335,24 @@ test("PORTAL_IDENTITY_SECRET reaches every service that signs or verifies a port);});+test("the invitation-email pair reaches core as optional secrets on every topology", () => {+ for (const name of ["RESEND_API_KEY", "AUTH_EMAIL_FROM"]) {+ const alone = secretByName(makeConfig(), name);+ assert.equal(alone.required, false);+ assert.deepEqual([...secretDestinations(alone).keys()], ["core"]);+ assert.match(alone.description, /admin Users tab or by chatting with QM/);+ assert.match(renderEnvExample(makeConfig()), new RegExp(`^# ${name}= # optional$`, "m"));++ const broker = makeConfig({+ services: ["core", "portal", "auth"],+ env: { auth: { AUTH_EMAIL_TRANSPORT: "resend" } },+ });+ const shared = secretByName(broker, name);+ assert.equal(shared.required, true);+ assert.deepEqual([...secretDestinations(shared).keys()].sort(), ["auth", "core"]);+ }+});+test("a fly deployment tells core which sandbox substrate to boot", () => {const config = makeConfig({target: "fly",diff --git a/cli/test/setup.test.ts b/cli/test/setup.test.tsindex 7b8d1002a..32d2c19db 100644--- a/cli/test/setup.test.ts+++ b/cli/test/setup.test.ts@@ -141,7 +141,9 @@ test("the broker's operator secrets replace the external-IdP ones", () => {const external = configFor(["core", "web-ui", "admin", "portal"]);const externalNames = pendingSecrets(external, new Map()).todo.map((secret) => secret.name);assert.ok(externalNames.includes("OIDC_CLIENT_SECRET"));- assert.ok(!externalNames.includes("AUTH_EMAIL_FROM"));+ for (const name of ["AUTH_EMAIL_FROM", "RESEND_API_KEY"]) {+ assert.ok(!externalNames.includes(name), `${name} is core's optional invitation sender, never a setup prompt`);+ }const broker = configFor(["core", "web-ui", "admin", "portal", "auth"],diff --git a/deploy/README.md b/deploy/README.mdindex 458528af4..9430dfe78 100644--- a/deploy/README.md+++ b/deploy/README.md@@ -38,7 +38,11 @@ under `/idp/`, so the issuer and the sign-in pages live on the portal's ownorigin while the token, userinfo, and JWKS calls stay on the private network.The self-hoster supplies an admin address, a verified sender, and a Resend keyor SMTP credentials; the CLI generates the broker's signing key and the portal's-client credentials and wires both sides. Dropping `"auth"` from `services` hands+client credentials and wires both sides. Core receives the same `RESEND_API_KEY`+and `AUTH_EMAIL_FROM`, which let admins email invitations to external users from+the admin Users tab or by chatting with QM; both are optional on core, and+without them the invitation is still created and the sign-in link is shared by+hand. Dropping `"auth"` from `services` handssign-in back to an external identity provider, which then has to register theexact `<publicUrl>/auth/callback` redirect.diff --git a/docs/porter.md b/docs/porter.mdindex a1a443305..a648d9400 100644--- a/docs/porter.md+++ b/docs/porter.md@@ -123,6 +123,10 @@ Nothing generates the inter-service wiring for you — `cli/src/services.ts` has| admin | `ADMIN_BASE_PATH=/admin` || auth | `AUTH_ISSUER=<portal>/idp`, `AUTH_CLIENT_ID`, `AUTH_CLIENT_SECRET`, `AUTH_REDIRECT_URI=<portal>/auth/callback`, `AUTH_TOKEN_SECRET`, `AUTH_SIGNING_JWK` (a P-256 private JWK), `AUTH_EMAIL_FROM`, and `AUTH_EMAIL_TRANSPORT` with a `RESEND_API_KEY` or SMTP credentials — without a mail transport nobody can sign in |+Core also reads `RESEND_API_KEY` and `AUTH_EMAIL_FROM` when they are set — optional there,+they let admins email external-user invitations from the admin Users tab or by chatting+with QM.+`src/deployment/secret-schema.ts` is the authoritative list of what each servicerequires; when a boot refusal names a variable this table doesn't, that file is the placeto look.diff --git a/plugins/admin/README.md b/plugins/admin/README.mdindex 5fcbe06a2..b6417e3c8 100644--- a/plugins/admin/README.md+++ b/plugins/admin/README.md@@ -15,6 +15,15 @@ The **Users** tab (org-wide, org_admin-only, like Retention) lists everyone whoused the agent (from session metadata — no content) with admin status joined, plus theauthoritative grant list, and lets an org_admin **promote** a principal to org_adminor **revoke** — every mutation attributed and audited, the last org_admin protected.+The **+** on the Users card invites an **external user** (an address outside the org's+Slack / email domain) with a role and an expiry; they get an invitation email and sign in+at the portal with that address until it expires. Invitation emails go out through Resend+when core has `RESEND_API_KEY` and `AUTH_EMAIL_FROM`; without them the user is still added+and the dashboard shows the sign-in link for you to share. External users are listed in+their own card, where **Revoke** ends access immediately and leaves the row listed as+expired; a day after expiry, **Remove** drops the row. An address that already belongs to an+org member (the org's email domain, the Slack directory, the sign-in allow-list, or anyone who+has used the agent) cannot be invited.(`org_admin` is the only supported role for now; `team_admin` was removed — team-scoped adminobservability is future work. See `src/admin/admin-service.ts`.) Metricsshows TTFT + turn/queue/execution-latency@@ -72,6 +81,7 @@ status) · `POST /api/logout` ·`GET /api/sessions/:id?scope=` (transcript) · `GET /api/sessions/:id/llm?scope=`(captured model requests) · `GET /api/files/read?id=` + `GET /api/files/download?id=` (document content) ·`GET /api/retention` (org-wide) · `GET /api/users` (org-wide; roster + grants) ·-`POST /api/grants` (promote) · `DELETE /api/grants/:principalId?scope=&role=` (revoke) — all-proxied to the core's `/v1/admin/…` with the admin actor injected. Grant mutation is-**org_admin-only** (enforced in the core, not the surface).+`POST /api/grants` (promote) · `DELETE /api/grants/:principalId?scope=&role=` (revoke) ·+`POST /api/external-users` (invite) · `DELETE /api/external-users/:email` (revoke) — all+proxied to the core's `/v1/admin/…` with the admin actor injected. Grant and external-user+mutation is **org_admin-only** (enforced in the core, not the surface).diff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.htmlindex 49e2f1dd1..e776937c2 100644--- a/plugins/admin/public/index.html+++ b/plugins/admin/public/index.html@@ -476,6 +476,8 @@margin: 0 0 6px;}input[type="text"],+ input[type="email"],+ input[type="date"],input[type="password"],input[type="number"],textarea,@@ -10891,6 +10893,21 @@"err",);}+ async function revokeExternalUser(m) {+ const question =+ m.status === "active"+ ? 'Revoke access for "' + m.email + '"? They will no longer be able to sign in.'+ : 'Remove "' + m.email + '" from the list?';+ if (!confirm(question)) return;+ const r = await api("DELETE", "/api/external-users/" + encodeURIComponent(m.email));+ if (r.ok) renderData();+ else+ setStatus(+ "st-external",+ r.status === 403 ? "Only an org admin may revoke." : r.data?.message || "Revoke failed.",+ "err",+ );+ }function keychainGrantStatus(g) {const expired = g.expiresAt && g.expiresAt <= Date.now();if (expired && g.status === "active") return ["expired", "warn"];@@ -11087,6 +11104,7 @@function renderUsers(root, d) {const users = d.users || [];const grants = d.grants || [];+ const externalUsers = d.externalUsers || [];let filterVal = "";defaultShell({stats: [@@ -11218,6 +11236,97 @@impCard.querySelector(".body").append(impDatalist, impSt);root.appendChild(impCard);+ const inviteEmail = d.inviteEmail || {};+ const emailInput = document.createElement("input");+ emailInput.type = "email";+ emailInput.placeholder = "[email protected]";+ emailInput.spellcheck = false;+ emailInput.autocapitalize = "none";+ const roleSelect = document.createElement("select");+ roleSelect.append(new Option("Member", "member"), new Option("Org admin", "org_admin"));+ const isoDay = (ms) => new Date(ms).toISOString().slice(0, 10);+ const expiresInput = document.createElement("input");+ expiresInput.type = "date";+ expiresInput.min = isoDay(Date.now());+ expiresInput.value = isoDay(Date.now() + 30 * 86400000);+ const inviteBtn = document.createElement("button");+ inviteBtn.className = "primary";+ inviteBtn.type = "button";+ inviteBtn.textContent = "Send invite";+ inviteBtn.onclick = async () => {+ const email = emailInput.value.trim();+ if (!email) return setStatus("st-external", "Email required.", "err");+ if (!expiresInput.value) return setStatus("st-external", "Expiry date required.", "err");+ inviteBtn.disabled = true;+ const r = await api("POST", "/api/external-users", {+ email,+ role: roleSelect.value,+ expiresAt: expiresInput.value,+ });+ inviteBtn.disabled = false;+ if (!r.ok)+ return setStatus(+ "st-external",+ r.status === 403 ? "Only an org admin may invite." : r.data?.message || "Invite failed.",+ "err",+ );+ const member = r.data.member;+ const expires = " (expires " + fmtTime(member.expiresAt) + ")";+ await renderData();+ setStatus(+ "st-external",+ r.data.emailSent+ ? "Invite sent to " + member.email + expires+ : r.data.emailProblem+ ? "Added " ++ member.email ++ ", but no invitation email was sent: " ++ r.data.emailProblem ++ "." ++ (r.data.signInUrl ? " Share " + r.data.signInUrl + " with them." : "")+ : "Updated " + member.email + " — " + labelRole(member.role) + expires,+ r.data.emailSent || !r.data.emailProblem ? "ok" : "dirty",+ true,+ );+ };+ const inviteForm = document.createElement("div");+ inviteForm.className = "grant-form";+ inviteForm.append(+ mkField("grow", "Email", emailInput),+ mkField("", "Role", roleSelect),+ mkField("", "Expires", expiresInput),+ inviteBtn,+ );+ const inviteNote = document.createElement("p");+ inviteNote.className = inviteEmail.configured === false ? "hint flag-warn" : "hint";+ const signInHint = inviteEmail.signInUrl ? " Sign-in link to share: " + inviteEmail.signInUrl : "";+ inviteNote.textContent =+ inviteEmail.configured === false+ ? (inviteEmail.problem || "Invitation emails are not configured") ++ ". The user is still added; share the sign-in link yourself." ++ signInHint+ : "Invitation emails go out through Resend — core needs RESEND_API_KEY and AUTH_EMAIL_FROM. Without them the user is still added and you share the sign-in link yourself.";+ const invite = document.createElement("div");+ invite.className = "hidden";+ invite.style.margin = "0 0 14px";+ invite.append(inviteForm, inviteNote);+ const addBtn = document.createElement("button");+ addBtn.type = "button";+ addBtn.className = "rowbtn";+ addBtn.textContent = "+";+ addBtn.title = "Add external user";+ addBtn.setAttribute("aria-label", "Add external user");+ addBtn.setAttribute("aria-expanded", "false");+ addBtn.onclick = () => {+ const open = !invite.classList.toggle("hidden");+ addBtn.setAttribute("aria-expanded", String(open));+ if (open) emailInput.focus();+ };+ const externalSt = document.createElement("p");+ externalSt.className = "status";+ externalSt.id = "st-external";+ externalSt.style.margin = "10px 0 0";+const lists = document.createElement("div");lists.className = "list-root";root.appendChild(lists);@@ -11229,6 +11338,7 @@const filteredUsers = users.filter((u) =>matches([u.principalId, u.admin?.role || "", u.admin?.scopeId || "member"]),);+ const filteredExternal = externalUsers.filter((m) => matches([m.email, m.role, m.invitedBy || "", m.status]));const admins = actionTable(["Principal", "Role", "Scope", "Granted by", ""],@@ -11289,11 +11399,40 @@(u) => go({ view: "user", scope, session: null, principal: u.principalId }),"No users match.",);+ const usersCard = dataCard(+ "Users",+ "Everyone who has used the agent — click a row for their activity, artifacts, and config.",+ roster,+ );+ usersCard.querySelector(".head h2").append(" ", addBtn);+ usersCard.querySelector(".body").prepend(invite);+ usersCard.querySelector(".body").appendChild(externalSt);+ lists.appendChild(usersCard);++ const external = actionTable(+ ["Email", "Role", "Expires", "Invited by", "Status", ""],+ filteredExternal,+ (m) => [+ { text: m.email, cls: "mono" },+ nodeCell(mutedText(labelRole(m.role))),+ (m.status === "active" ? "Ends " : "Ended ") + isoDay(m.expiresAt) + " (UTC)",+ m.invitedBy || "-",+ { badge: m.status === "active" ? "Active" : "Expired", kind: m.status === "active" ? "ok" : "warn" },+ m.status === "active"+ ? { action: { label: "Revoke", danger: true, run: () => revokeExternalUser(m) } }+ : Date.now() - m.expiresAt >= 86400000+ ? { action: { label: "Remove", run: () => revokeExternalUser(m) } }+ : "",+ ],+ externalUsers.length+ ? "No external users match."+ : "No external users. Use + on the Users card to invite one.",+ );lists.appendChild(dataCard(- "Users",- "Everyone who has used the agent — click a row for their activity, artifacts, and config.",- roster,+ "External users",+ "Outside collaborators invited by email. They sign in at the portal with that address until it expires.",+ external,),);};diff --git a/plugins/admin/src/index.ts b/plugins/admin/src/index.tsindex 706c3ddc1..15aab08b2 100644--- a/plugins/admin/src/index.ts+++ b/plugins/admin/src/index.ts@@ -282,6 +282,7 @@ async function coreWhoami(principal: string): Promise<{ isAdmin: boolean; role?:const WRITES = new Map<string, string[]>([["grants", ["POST", "DELETE"]],+ ["external-users", ["POST", "DELETE"]],["memory", ["PUT"]],["crons", ["PUT"]],["skills", ["DELETE"]],diff --git a/plugins/admin/test/grants.test.ts b/plugins/admin/test/grants.test.tsindex 68d2043f4..fb5566ab6 100644--- a/plugins/admin/test/grants.test.ts+++ b/plugins/admin/test/grants.test.ts@@ -63,6 +63,36 @@ test("DELETE /api/grants/:id forwards the path + query to the core", async () =>assert.equal(c.actor, "U-admin@acme");});+test("POST /api/external-users forwards the invite to the core with the actor + a signature", async () => {+ const invite = { email: "[email protected]", role: "member", expiresAt: "2026-10-02T23:59:59.999Z" };+ const r = await fetch(`${base}/api/external-users`, {+ method: "POST",+ headers: { cookie: ADMIN, "content-type": "application/json" },+ body: JSON.stringify(invite),+ });+ assert.equal(r.status, 200);+ const c = calls.at(-1)!;+ assert.equal(c.method, "POST");+ assert.equal(c.url, "/v1/admin/external-users");+ assert.equal(c.actor, "U-admin@acme");+ assert.equal(c.signed, true);+ assert.deepEqual(JSON.parse(c.body), invite);+});++test("DELETE /api/external-users/:email forwards the encoded address to the core", async () => {+ const r = await fetch(`${base}/api/external-users/${encodeURIComponent("[email protected]")}`, {+ method: "DELETE",+ headers: { cookie: ADMIN },+ });+ assert.equal(r.status, 200);+ const c = calls.at(-1)!;+ assert.equal(c.method, "DELETE");+ assert.equal(c.url, "/v1/admin/external-users/dana%40partner.example");+ assert.equal(c.actor, "U-admin@acme");+ assert.equal(c.signed, true);+ assert.equal(c.body, "");+});+test("GET /api/users forwards to /v1/admin/users", async () => {const r = await fetch(`${base}/api/users`, { headers: { cookie: ADMIN } });assert.equal(r.status, 200);@@ -90,6 +120,17 @@ test("grants/users require a signed-in cookie → 401 when absent (no core hop)"401,);assert.equal((await fetch(`${base}/api/grants/U1?scope=org:acme&role=org_admin`, { method: "DELETE" })).status, 401);+ assert.equal(+ (+ await fetch(`${base}/api/external-users`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: "{}",+ })+ ).status,+ 401,+ );+ assert.equal((await fetch(`${base}/api/external-users/dana%40partner.example`, { method: "DELETE" })).status, 401);assert.equal((await fetch(`${base}/api/users`)).status, 401);assert.equal((await fetch(`${base}/api/keychain`)).status, 401);assert.equal(calls.length, before, "a signed-out request is rejected at the surface, never forwarded");diff --git a/plugins/auth/README.md b/plugins/auth/README.mdindex 38e040ebd..f3373a201 100644--- a/plugins/auth/README.md+++ b/plugins/auth/README.md@@ -55,6 +55,18 @@ store; the broker refuses to start if any of it is missing or a placeholder.The signing key is single, not a set: rotating it means redeploying, and linksminted by the previous key stop verifying at that moment.+## Invited external users++An address an org admin has invited as an external user (Admin → Users, or by+asking the agent) may sign in until its expiry even though it is on neither+`AUTH_ALLOWED_EMAILS` nor `AUTH_ALLOWED_EMAIL_DOMAIN`. The env list is checked+first and settles the answer on its own; only an address it does not cover is+looked up in core over the signed core client (`GET+/v1/auth/broker/email-allowed`), at every step — when the link is requested,+when it is opened, and when the code is exchanged — so a revoked or expired+invitation stops working at once. A lookup that fails or times out counts as not+allowed. One of the two env variables is still required at boot.+## Email transport`AUTH_EMAIL_TRANSPORT` selects one of two, and the broker refuses to startdiff --git a/plugins/auth/src/server.ts b/plugins/auth/src/server.tsindex e1e24b086..cbc04284e 100644--- a/plugins/auth/src/server.ts+++ b/plugins/auth/src/server.ts@@ -4,6 +4,7 @@ import { errMessage } from "../../chassis/src/errors.ts";import type { AuthConfig } from "./config.ts";import { validEmail } from "./config.ts";import { claimOnce, withinRateLimit, ClaimStoreUnavailableError, type ClaimStore } from "../../chassis/src/claims.ts";+import { coreEmailAllowed } from "../../chassis/src/external-members.ts";import { mintIdToken, pkceMatches, safeEqual, subjectFor, TokenSigner, type AuthRequest } from "./tokens.ts";import { ID_TOKEN_ALG, type SigningKey } from "./keys.ts";import { renderSignInEmail, type Mailer } from "./email.ts";@@ -20,15 +21,11 @@ export interface AuthDeps {claims: ClaimStore;mailer: Mailer;brandName?: () => string;+ emailAllowed?: (email: string) => Promise<boolean>;now?: () => number;onBackgroundTask?: (task: Promise<void>) => void;}-function emailAllowed(cfg: AuthConfig, email: string): boolean {- if (cfg.allowedEmails.includes(email)) return true;- return Boolean(cfg.allowedEmailDomain) && email.endsWith(`@${cfg.allowedEmailDomain}`);-}-function normalizeEmail(raw: string): string {return raw.trim().toLowerCase();}@@ -104,6 +101,13 @@ function readAuthorizeRequest(export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: ServerResponse) => Promise<void> {const { cfg, signer, claims, mailer, signingKey } = deps;const brandName = deps.brandName ?? ((): string => cfg.brandName);+ const invited =+ deps.emailAllowed ??+ ((email: string): Promise<boolean> => coreEmailAllowed(cfg.coreApiUrl, cfg.coreSigningSecret, email, "auth"));+ const emailAllowed = async (email: string): Promise<boolean> =>+ cfg.allowedEmails.includes(email) ||+ (Boolean(cfg.allowedEmailDomain) && email.endsWith(`@${cfg.allowedEmailDomain}`)) ||+ invited(email);const now = deps.now ?? Date.now;const notify = deps.onBackgroundTask ?? ((task: Promise<void>) => void task.catch(() => undefined));const formAction = `${cfg.publicPath}/authorize`;@@ -167,7 +171,7 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: Sconst nowMs = now();const within = async (kind: string, value: string, limit: number): Promise<boolean> =>withinRateLimit(claims, { secret: cfg.tokenSecret, kind, value, limit, windowS: cfg.sendWindowS, nowMs });- if (!emailAllowed(cfg, email)) {+ if (!(await emailAllowed(email))) {console.warn(`[auth] sign-in link suppressed: ${email} is not on the permitted list`);return;}@@ -277,7 +281,7 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: S"The sign-in configuration changed after this link was sent. Start again.",);}- if (!emailAllowed(cfg, link.email)) {+ if (!(await emailAllowed(link.email))) {return problem(res, 403, "This address can't sign in", "Your administrator has not allowed this email address.");}const code = await signer.sealCode(@@ -335,7 +339,7 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: Sif (!codeClaimed) return sendJson(res, 400, { error: "invalid_grant" });if (!pkceMatches(form.get("code_verifier") ?? "", granted.codeChallenge))return sendJson(res, 400, { error: "invalid_grant" });- if (!emailAllowed(cfg, granted.email)) return sendJson(res, 400, { error: "invalid_grant" });+ if (!(await emailAllowed(granted.email))) return sendJson(res, 400, { error: "invalid_grant" });const nowMs = now();const sub = subjectFor(cfg.issuer, granted.email);diff --git a/plugins/auth/test/flow.test.ts b/plugins/auth/test/flow.test.tsindex 40e18d427..7679dc798 100644--- a/plugins/auth/test/flow.test.ts+++ b/plugins/auth/test/flow.test.ts@@ -307,6 +307,46 @@ test("an address outside the allowlist is never emailed and never redeemed", asyassert.notEqual(refused.status, 302, "a link minted for an address that is no longer allowed must not redeem");});+test("an invited external address signs in through core's answer and an uninvited one does not", async (t) => {+ const invited = new Set(["[email protected]"]);+ const asked: string[] = [];+ const h = await startHarness({+ emailAllowed: async (email) => {+ asked.push(email);+ return invited.has(email);+ },+ });+ t.after(() => h.close());++ await requestLink(h, { email: "[email protected]" });+ assert.deepEqual(asked, [], "an address on the env allow-list never consults core");++ const { verifier } = await requestLink(h, { email: "[email protected]" });+ assert.equal(h.mailer.sent.length, 2);+ assert.equal(h.mailer.sent[1]!.to, "[email protected]");+ assert.deepEqual(asked, ["[email protected]"]);+ const code = new URL(await redeem(h)).searchParams.get("code")!;+ const tokens = await exchange(h, code, verifier);+ assert.equal(tokens.status, 200);+ const claims = await verifyIdTokenLikePortal(+ h,+ ((await tokens.json()) as { id_token: string }).id_token,+ "nonce-value",+ );+ assert.equal(claims.email, "[email protected]");++ await requestLink(h, { email: "[email protected]" });+ assert.equal(h.mailer.sent.length, 2, "an address core does not know must not receive a link");++ await requestLink(h, { email: "[email protected]" });+ invited.clear();+ const revoked = await fetch(`${h.base}/verify`, {+ ...form({ token: tokenOf(linkFrom(h.mailer)) }),+ redirect: "manual",+ });+ assert.equal(revoked.status, 403, "a link minted before the invitation was revoked must not redeem");+});+test("the confirmation page is identical for permitted and unknown addresses", async (t) => {const h = await startHarness();t.after(() => h.close());diff --git a/plugins/auth/test/helpers.ts b/plugins/auth/test/helpers.tsindex 96afdd5a4..5b36d639f 100644--- a/plugins/auth/test/helpers.ts+++ b/plugins/auth/test/helpers.ts@@ -95,6 +95,7 @@ export async function startHarness(env?: Record<string, string | undefined>;claims?: ClaimStore & { calls: string[][] };brandName?: () => string;+ emailAllowed?: (email: string) => Promise<boolean>;} = {},): Promise<Harness> {const cfg = readConfig(testEnv(options.env));@@ -109,6 +110,7 @@ export async function startHarness(claims,mailer,...(options.brandName ? { brandName: options.brandName } : {}),+ emailAllowed: options.emailAllowed ?? (async () => false),now: () => now.ms,onBackgroundTask: (task) => pending.push(task),});diff --git a/plugins/chassis/src/external-members.ts b/plugins/chassis/src/external-members.tsnew file mode 100644index 000000000..0e9d399d9--- /dev/null+++ b/plugins/chassis/src/external-members.ts@@ -0,0 +1,29 @@+import { signedHeaders, withSourceAuthNonce } from "./core-client.ts";+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(+ coreApiUrl: string,+ signingSecret: string | undefined,+ email: string,+ label = "chassis",+): Promise<boolean> {+ const path = withSourceAuthNonce(`${EMAIL_ALLOWED_PATH}?email=${encodeURIComponent(email)}`, signingSecret);+ try {+ const r = await fetch(`${coreApiUrl}${path}`, {+ headers: signedHeaders(signingSecret, "GET", path),+ signal: AbortSignal.timeout(EMAIL_ALLOWED_TIMEOUT_MS),+ });+ if (!r.ok) {+ console.error(`[${label}] core refused an external-member lookup: HTTP ${r.status}`);+ return false;+ }+ const parsed = (await r.json()) as { allowed?: unknown };+ return parsed.allowed === true;+ } catch (e) {+ console.error(`[${label}] core external-member lookup failed: ${errMessage(e)}`);+ return false;+ }+}diff --git a/plugins/portal/README.md b/plugins/portal/README.mdindex 3c6752fbc..d5fe009d0 100644--- a/plugins/portal/README.md+++ b/plugins/portal/README.md@@ -144,6 +144,11 @@ verified work email, lowercased; sign-in fails unless the IdP marks the email ve(the IdP's opaque subject, e.g. the Slack U… id — only for deployments still keyed on Slack ids).`OIDC_ALLOWED_EMAIL_DOMAIN` — with `email`, additionally reject any account outside this domain(checked against the email suffix and Google's `hd` claim).+An address those rules reject still signs in when an org admin has invited it as an+external user: the callback asks core over the signed core client+(`GET /v1/auth/broker/email-allowed`) and accepts an active invitation, `hd` notwithstanding.+An address the env rules permit never triggers the lookup; core unreachable means not allowed.+Deployments keyed on `sub` never consult it, so external users cannot sign in there.### Google Workspace SSO with the email principaldiff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.tsindex 66f338b68..444545cf2 100644--- a/plugins/portal/src/index.ts+++ b/plugins/portal/src/index.ts@@ -39,6 +39,7 @@ import {} from "./proxy.ts";import { signedHeaders, withSourceAuthNonce } from "../../chassis/src/core-client.ts";import { coreClaimStore, withinRateLimit, ClaimStoreUnavailableError } from "../../chassis/src/claims.ts";+import { coreEmailAllowed } 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 { json, escapeHtml, serveEmojiFavicon } from "../../chassis/src/http.ts";@@ -1187,7 +1188,9 @@ 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 = resolvePrincipal(PRINCIPAL_RULE, { sub: infoSub, claims, userinfo: info });+ sub = await resolvePrincipal(PRINCIPAL_RULE, { sub: infoSub, claims, userinfo: info }, (email) =>+ coreEmailAllowed(CORE, CORE_SIGNING_SECRET, email, "portal"),+ );const rawName = info.name ?? claims.name;if (typeof rawName === "string") name = rawName.trim().slice(0, 200);} catch (e) {diff --git a/plugins/portal/src/oidc.ts b/plugins/portal/src/oidc.tsindex 7cd70dd0d..874b37b8a 100644--- a/plugins/portal/src/oidc.ts+++ b/plugins/portal/src/oidc.ts@@ -125,29 +125,37 @@ export interface PrincipalRule {allowedEmails?: readonly string[];}-export function resolvePrincipal(- rule: PrincipalRule,- args: { sub: string; claims: Record<string, unknown>; userinfo: Record<string, unknown> },-): string {- if (rule.claim === "sub") return 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();+type PrincipalArgs = { sub: string; claims: Record<string, unknown>; userinfo: Record<string, unknown> };++function envRefusal(rule: PrincipalRule, email: string, args: PrincipalArgs): string | null {if (rule.allowedEmails?.length &&!rule.allowedEmails.map((allowed) => allowed.trim().toLowerCase()).includes(email)) {- throw new Error("account is not on the permitted email list");+ return "account is not on the permitted email list";}if (rule.allowedEmailDomain) {const domain = rule.allowedEmailDomain.toLowerCase();- if (!email.endsWith(`@${domain}`)) throw new Error("account is outside the permitted domain");+ if (!email.endsWith(`@${domain}`)) return "account is outside the permitted domain";const hd = args.userinfo.hd ?? args.claims.hd;- if (typeof hd === "string" && hd.toLowerCase() !== domain)- throw new Error("account is outside the permitted domain");+ if (typeof hd === "string" && hd.toLowerCase() !== domain) return "account is outside the permitted domain";}+ return null;+}++export async function resolvePrincipal(+ rule: PrincipalRule,+ args: PrincipalArgs,+ invited: (email: string) => Promise<boolean> = async () => false,+): Promise<string> {+ if (rule.claim === "sub") return 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;}diff --git a/plugins/portal/test/oidc.test.ts b/plugins/portal/test/oidc.test.tsindex 9dc6939de..a52d40886 100644--- a/plugins/portal/test/oidc.test.ts+++ b/plugins/portal/test/oidc.test.ts@@ -149,86 +149,138 @@ test("verifyIdToken requires a valid signature, issuer, audience, subject, nonceawait assert.rejects(verifyIdToken(provider, signed, "wrong", fetchJwks), /nonce/);});-test("resolvePrincipal claim=sub returns the subject untouched", () => {- assert.equal(resolvePrincipal({ claim: "sub" }, { sub: "U1", claims: {}, userinfo: { email: "[email protected]" } }), "U1");+test("resolvePrincipal claim=sub returns the subject untouched", async () => {+ assert.equal(+ await resolvePrincipal({ claim: "sub" }, { sub: "U1", claims: {}, userinfo: { email: "[email protected]" } }),+ "U1",+ );});-test("resolvePrincipal claim=email returns the verified email, normalized", () => {- const got = resolvePrincipal(+test("resolvePrincipal claim=email returns the verified email, normalized", async () => {+ const got = await resolvePrincipal({ claim: "email" },{ sub: "g-123", claims: {}, userinfo: { email: " [email protected] ", email_verified: true } },);assert.equal(got, "[email protected]");});-test("resolvePrincipal claim=email requires the verified userinfo response", () => {- assert.throws(- () =>- resolvePrincipal(- { claim: "email" },- { sub: "g-123", claims: { email: "[email protected]", email_verified: "true" }, userinfo: {} },- ),+test("resolvePrincipal claim=email requires the verified userinfo response", async () => {+ await assert.rejects(+ resolvePrincipal(+ { claim: "email" },+ { sub: "g-123", claims: { email: "[email protected]", email_verified: "true" }, userinfo: {} },+ ),/no email/,);});-test("resolvePrincipal claim=email rejects missing or unverified emails", () => {- assert.throws(() => resolvePrincipal({ claim: "email" }, { sub: "g", claims: {}, userinfo: {} }), /no email/);- assert.throws(- () => resolvePrincipal({ claim: "email" }, { sub: "g", claims: {}, userinfo: { email: "[email protected]" } }),+test("resolvePrincipal claim=email rejects missing or unverified emails", async () => {+ await assert.rejects(resolvePrincipal({ claim: "email" }, { sub: "g", claims: {}, userinfo: {} }), /no email/);+ await assert.rejects(+ resolvePrincipal({ claim: "email" }, { sub: "g", claims: {}, userinfo: { email: "[email protected]" } }),/not verified/,);- assert.throws(- () =>- resolvePrincipal(- { claim: "email" },- { sub: "g", claims: {}, userinfo: { email: "[email protected]", email_verified: false } },- ),+ await assert.rejects(+ resolvePrincipal(+ { claim: "email" },+ { sub: "g", claims: {}, userinfo: { email: "[email protected]", email_verified: false } },+ ),/not verified/,);});-test("resolvePrincipal allowedEmailDomain gates the email suffix and the hd claim", () => {+test("resolvePrincipal allowedEmailDomain gates the email suffix and the hd claim", async () => {const rule = { claim: "email" as const, allowedEmailDomain: "example.com" };- const ok = resolvePrincipal(rule, {+ const ok = await resolvePrincipal(rule, {sub: "g",claims: {},userinfo: { email: "[email protected]", email_verified: true, hd: "example.com" },});assert.equal(ok, "[email protected]");- assert.throws(- () => resolvePrincipal(rule, { sub: "g", claims: {}, userinfo: { email: "[email protected]", email_verified: true } }),+ await assert.rejects(+ resolvePrincipal(rule, { sub: "g", claims: {}, userinfo: { email: "[email protected]", email_verified: true } }),/permitted domain/,);- assert.throws(- () =>- resolvePrincipal(rule, {- sub: "g",- claims: {},- userinfo: { email: "[email protected]", email_verified: true, hd: "evil.com" },- }),+ await assert.rejects(+ resolvePrincipal(rule, {+ sub: "g",+ claims: {},+ userinfo: { email: "[email protected]", email_verified: true, hd: "evil.com" },+ }),/permitted domain/,);- assert.throws(- () =>- resolvePrincipal(rule, {- sub: "g",- claims: {},- userinfo: { email: "[email protected]", email_verified: true },- }),+ await assert.rejects(+ resolvePrincipal(rule, {+ sub: "g",+ claims: {},+ userinfo: { email: "[email protected]", email_verified: true },+ }),/permitted domain/,);});-test("resolvePrincipal allowedEmails permits only the seeded verified addresses", () => {+test("resolvePrincipal allowedEmails permits only the seeded verified addresses", async () => {const rule = { claim: "email" as const, allowedEmails: ["[email protected]"] };assert.equal(- resolvePrincipal(rule, { sub: "g", claims: {}, userinfo: { email: "[email protected]", email_verified: true } }),+ await resolvePrincipal(rule, {+ sub: "g",+ claims: {},+ userinfo: { email: "[email protected]", email_verified: true },+ }),);- assert.throws(- () =>- resolvePrincipal(rule, { sub: "g", claims: {}, userinfo: { email: "[email protected]", email_verified: true } }),+ await assert.rejects(+ resolvePrincipal(rule, { sub: "g", claims: {}, userinfo: { email: "[email protected]", email_verified: true } }),+ /permitted email list/,+ );+});++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> => {+ asked.push(email);+ return email === "[email protected]";+ };+ const verified = (email: string, extra: Record<string, unknown> = {}) => ({+ sub: "g",+ claims: {},+ userinfo: { email, email_verified: true, ...extra },+ });++ assert.equal(await resolvePrincipal(rule, verified("[email protected]"), invited), "[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(asked, ["[email protected]"], "core is asked with the normalized address");+ assert.equal(+ await resolvePrincipal(rule, verified("[email protected]", { hd: "partner.test" }), invited),+ "[email protected]",+ "a foreign hd claim does not block an invited address",+ );++ await assert.rejects(resolvePrincipal(rule, verified("[email protected]"), invited), /permitted/);+ await assert.rejects(+ resolvePrincipal(+ { claim: "email", allowedEmails: ["[email protected]"] },+ verified("[email protected]"),+ invited,+ ),/permitted email list/,);++ asked.length = 0;+ await assert.rejects(+ resolvePrincipal(rule, { sub: "g", claims: {}, userinfo: { email: "[email protected]" } }, invited),+ /not verified/,+ );+ await assert.rejects(resolvePrincipal(rule, { sub: "g", claims: {}, userinfo: {} }, invited), /no email/);+ assert.deepEqual(asked, [], "an unverified or missing email is refused before core is consulted");++ await assert.rejects(+ resolvePrincipal(rule, verified("[email protected]"), async () => {+ throw new Error("core down");+ }),+ /core down/,+ );});diff --git a/skills-seed/admin/SKILL.md b/skills-seed/admin/SKILL.mdindex f76b67d36..a150a54bf 100644--- a/skills-seed/admin/SKILL.md+++ b/skills-seed/admin/SKILL.md@@ -1,6 +1,6 @@---name: admin-description: Act for an org admin — the admin API (scope directory, per-scope config & SOUL, any scope's memory, transcripts & captured prompts, files, user roster, audit/errors/metrics/egress) accepts your token when the user you're talking to is an org admin and started this turn themselves. Use when an admin asks you to inspect or change anything org-wide or in another scope, or anyone asks whether they're an admin.+description: Act for an org admin — the admin API (scope directory, per-scope config & SOUL, any scope's memory, transcripts & captured prompts, files, user roster & external users, audit/errors/metrics/egress) accepts your token when the user you're talking to is an org admin and started this turn themselves. Use when an admin asks you to inspect or change anything org-wide or in another scope, or anyone asks whether they're an admin.---# admin — act for an org admin, from chat@@ -91,6 +91,24 @@ GET /v1/admin/egress?scope= GET /v1/admin/retentionGET /v1/admin/users → roster + admin status (org-wide)```+## External users++Outside collaborators, admitted by email with a role and an expiry; they sign in at the+portal with that address until it lapses. Listed alongside the roster:++```bash+GET /v1/admin/users → externalUsers: [{email, role, expiresAt, invitedBy, status: active|expired}]+POST /v1/admin/external-users {"email":"[email protected]","expiresAt":"2026-12-31"} role defaults to member; expiresAt required (a bare date means end of that day UTC; ISO date-time or epoch ms also work)+DELETE /v1/admin/external-users/<email> → revokes access now; the row stays listed as expired (a DELETE a day after expiry removes it)+```++Confirm with the admin before inviting or revoking — say who, which role, and until+when. The invitation email needs Resend configured on core (`RESEND_API_KEY` ++`AUTH_EMAIL_FROM`); without it the user is still added. When the response has+`emailSent:false`, tell the admin why (`emailProblem`) and hand them `signInUrl` to pass+along themselves. The `org_admin` role for externals is portal-only, like every other+grant change — don't offer it.+## Admin grants (promote / revoke)Not available through you: who governs the org changes only in the admin dashboard,@@ -108,5 +126,12 @@ where the admin acts directly. If asked, point them there — don't try the APIrecurring in this room, to turn on this scope's `admin-session-reads` flag — fromtheir DM, never from here).- `403 … grant changes (promote/revoke) are portal-only` — point them at the dashboard.+- `403 granting or removing org admin for an external user is portal-only …` — same+ answer: the dashboard.+- `409 that address already belongs to a member of the org …` — org email domain, Slack+ directory, sign-in allow-list, or someone who has already used the agent. They are not+ external; point the admin at Users / Admins for that person instead.+- `409 that address holds an org admin grant of its own …` — the admin manages that grant+ under Admins in the dashboard first.- `403 capability token not valid for this route` — this core predates agent adminaccess; the user must use the admin dashboard.diff --git a/src/admin/invite-email.ts b/src/admin/invite-email.tsnew file mode 100644index 000000000..42caf8c83--- /dev/null+++ b/src/admin/invite-email.ts@@ -0,0 +1,71 @@+import { escapeHtml } from "../api/http.ts";++export interface InviteMailer {+ send(message: { to: string; subject: string; text: string; html: string }): Promise<string>;+}++export const INVITE_EMAIL_NOT_CONFIGURED =+ "invitation emails are not configured — set RESEND_API_KEY and AUTH_EMAIL_FROM on core (the same Resend key and verified sender the sign-in broker uses)";++const RESEND_ENDPOINT = "https://api.resend.com/emails";+const RESEND_TIMEOUT_MS = 15_000;++export function createResendMailer(apiKey: string, from: string, fetchImpl: typeof fetch = fetch): InviteMailer {+ return {+ async send(message) {+ const r = await fetchImpl(RESEND_ENDPOINT, {+ method: "POST",+ headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json" },+ body: JSON.stringify({+ from,+ to: [message.to],+ subject: message.subject,+ text: message.text,+ html: message.html,+ }),+ signal: AbortSignal.timeout(RESEND_TIMEOUT_MS),+ });+ const body = (await r.json().catch(() => ({}))) as { id?: string; message?: string; name?: string };+ if (!r.ok)+ throw new Error(`Resend rejected the message: HTTP ${r.status} ${body.message ?? body.name ?? ""}`.trim());+ return body.id ?? "accepted";+ },+ };+}++export function renderInviteEmail(a: {+ to: string;+ brandName: string;+ invitedBy: string;+ signInUrl: string;+ expiresAt: number;+}): { subject: string; text: string; html: string } {+ const ends = new Date(a.expiresAt).toUTCString();+ const subject = `You've been invited to ${a.brandName}`;+ const text = [+ subject,+ "",+ `${a.invitedBy} invited you to ${a.brandName}.`,+ "",+ `Sign in at ${a.signInUrl} using this email address (${a.to}) — a one-time link is emailed to you at sign-in.`,+ "",+ `Your access ends on ${ends}.`,+ ].join("\n");+ const html = `<!doctype html>+<html lang="en"><head><meta charset="utf-8"><meta name="color-scheme" content="light"></head>+<body style="margin:0;padding:0;background:#f5f5f5">+<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f5f5f5;padding:32px 12px">+<tr><td align="center">+<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:440px;background:#ffffff;border:1px solid #e5e5e5;border-radius:16px;padding:32px;font:15px/1.6 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;color:#0a0a0a">+<tr><td>+<h1 style="margin:0 0 10px;font-size:20px;font-weight:600">${escapeHtml(subject)}</h1>+<p style="margin:0 0 24px;color:#525252">${escapeHtml(a.invitedBy)} invited you to ${escapeHtml(a.brandName)}. Sign in using this email address (${escapeHtml(a.to)}) — a one-time link is emailed to you at sign-in.</p>+<p style="margin:0 0 24px"><a href="${escapeHtml(a.signInUrl)}" style="display:inline-block;background:#0a0a0a;color:#ffffff;text-decoration:none;font-weight:600;padding:13px 22px;border-radius:10px">Sign in</a></p>+<p style="margin:0 0 8px;color:#737373;font-size:13px">Or paste this address into your browser:</p>+<p style="margin:0 0 24px;word-break:break-all;font-size:12px;color:#525252">${escapeHtml(a.signInUrl)}</p>+<p style="margin:0;color:#737373;font-size:13px">Your access ends on ${escapeHtml(ends)}.</p>+</td></tr></table>+</td></tr></table>+</body></html>`;+ return { subject, text, html };+}diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.tsindex c92ae07d3..7ee190050 100644--- a/src/api/agent-api-catalog.ts+++ b/src/api/agent-api-catalog.ts@@ -625,7 +625,19 @@ const FAMILIES: AgentApiFamily[] = [method: "GET",path: "/v1/admin/users",summary:- "org roster with admin status; /v1/admin/users/:id for one user's activity, conversations, and personal-scope artifacts (DM only)",+ "org roster with admin status plus externalUsers (invited outside collaborators with role, expiry, status); /v1/admin/users/:id for one user's activity, conversations, and personal-scope artifacts (DM only)",+ },+ {+ method: "POST",+ path: "/v1/admin/external-users",+ summary:+ "invite an outside collaborator by email — {email, role?: member|org_admin, expiresAt (ISO date-time, a bare YYYY-MM-DD meaning end of that day UTC, or epoch ms)}; they sign in at the portal with that address until expiry; 409 if the address already belongs to an org member (org email domain, Slack directory, sign-in allow-list, or anyone who has used the agent). The invitation email needs Resend on core (RESEND_API_KEY + AUTH_EMAIL_FROM); when the response says emailSent:false, relay emailProblem and hand the user signInUrl to share. org_admin role is portal-only",+ },+ {+ method: "DELETE",+ path: "/v1/admin/external-users/:email",+ summary:+ "revoke an external user's access now — they stay listed as expired, and a DELETE a day after expiry removes the row (externals holding org_admin: portal-only)",},{method: "GET",diff --git a/src/api/app-messaging.ts b/src/api/app-messaging.tsindex d2f2ccea6..91b95de7c 100644--- a/src/api/app-messaging.ts+++ b/src/api/app-messaging.ts@@ -15,6 +15,8 @@ import {type ReachResolution,} from "../reach/reach.ts";import { isVisible } from "../directory/visibility.ts";+import type { DirectoryMember } from "../directory/directory-store.ts";+import { externalMemberActive } from "../identity/external-members.ts";import { answerWebContextRequest } from "./web-context.ts";import { validateUserSchedule } from "../cron/schedule.ts";@@ -89,11 +91,21 @@ export function createMessagingMethods(const contextRequests = deps.contextRequests ?? createMemoryMap<SurfaceContextRequest>();const contextRequestListeners = new Set<(request: SurfaceContextRequest) => void>();const contextRequestTokens = new Map<string, string>();- const emailAuthMembers = deps.emailAuthMembers ?? [];+ const emailMembers = async (): Promise<DirectoryMember[]> => {+ const externals = (await deps.identity.listExternalMembers()).filter((member) => externalMemberActive(member));+ return [+ ...(deps.emailAuthMembers ?? []),+ ...externals.map((member) => ({+ principalId: member.email,+ displayName: member.email,+ type: "internal" as const,+ })),+ ];+ };const mergedDirectoryMembers = async () => {- const stored = await deps.directory.list();+ const [stored, viaEmail] = await Promise.all([deps.directory.list(), emailMembers()]);const seen = new Set(stored.map((member) => personKey(member.principalId)));- return [...stored, ...emailAuthMembers.filter((member) => !seen.has(personKey(member.principalId)))];+ return [...stored, ...viaEmail.filter((member) => !seen.has(personKey(member.principalId)))];};return {@@ -404,7 +416,7 @@ export function createMessagingMethods(const stored = await deps.directory.resolve(query);if (stored.kind !== "none") return stored;const key = personKey(query);- const member = emailAuthMembers.find(+ const member = (await emailMembers()).find((candidate) => personKey(candidate.principalId) === key || personKey(candidate.displayName) === key,);return member ? { kind: "one", member } : { kind: "none" };@@ -421,7 +433,7 @@ export function createMessagingMethods(async directoryMember(principalId) {return ((await deps.directory.get(principalId)) ??- emailAuthMembers.find((member) => personKey(member.principalId) === personKey(principalId)) ??+ (await emailMembers()).find((member) => personKey(member.principalId) === personKey(principalId)) ??null);},diff --git a/src/api/deps.ts b/src/api/deps.tsindex 63d2bd662..b6bc3407c 100644--- a/src/api/deps.ts+++ b/src/api/deps.ts@@ -14,6 +14,7 @@ import type { EgressAuditSink } from "../admin/egress-audit-sink.ts";import type { BrokerFetch } from "./credential-broker.ts";import type { GitHttpFetch } from "./git-http-broker.ts";import type { AdminService } from "../admin/admin-service.ts";+import type { InviteMailer } from "../admin/invite-email.ts";import type { SessionStore } from "../sessions/session-store.ts";import type { SecurityScreenProbe } from "../security/security-screener.ts";import type { AuditLog } from "../audit/audit-log.ts";@@ -99,6 +100,9 @@ export interface ServerDeps {harnessId?: string;harnessCarriedModelAuth?: ModelProvider;admin?: AdminService;+ inviteMailer?: InviteMailer;+ emailAuthPrincipals?: readonly string[];+ emailAuthDomain?: string;rateLimiter?: RateLimiter;sessions?: SessionStore;screenSecurity?: SecurityScreenProbe;diff --git a/src/api/routes/admin.ts b/src/api/routes/admin.tsindex 61350b717..a3fe1675c 100644--- a/src/api/routes/admin.ts+++ b/src/api/routes/admin.ts@@ -17,10 +17,12 @@ import { listSandboxRoutes, migrateSandboxScope } from "./admin/sandbox.ts";import {createAdminGrant,getUserDetail,+ inviteExternalUser,listKeychainStatus,listUsers,resetUserToBrandNew,revokeAdminGrant,+ revokeExternalUser,searchDirectory,setUserOnboarding,startImpersonation,@@ -127,6 +129,8 @@ const routes: ReadonlyArray<Route<ApiCtx>> = [{ method: "POST", path: "/v1/admin/users/:principalId/reset", auth: "either", handle: resetUserToBrandNew },{ method: "POST", path: "/v1/admin/grants", auth: "either", handle: createAdminGrant },{ method: "DELETE", path: "/v1/admin/grants/:principalId", auth: "either", handle: revokeAdminGrant },+ { method: "POST", path: "/v1/admin/external-users", auth: "either", handle: inviteExternalUser },+ { method: "DELETE", path: "/v1/admin/external-users/:email", auth: "either", handle: revokeExternalUser },{ method: "POST", path: "/v1/admin/impersonate/stop", auth: "either", handle: stopImpersonation },{ method: "POST", path: "/v1/admin/impersonate", auth: "either", handle: startImpersonation },];diff --git a/src/api/routes/admin/scope-config.ts b/src/api/routes/admin/scope-config.tsindex b7457b53a..35985084a 100644--- a/src/api/routes/admin/scope-config.ts+++ b/src/api/routes/admin/scope-config.ts@@ -17,7 +17,7 @@ import {type ModelCatalogEntry,} from "../../../model/model-catalog.ts";import { sendJson } from "../../http.ts";-import { adminActorFrom, audit, authorizeAdmin, orgScope } from "../shared.ts";+import { activePrincipal, adminActorFrom, audit, authorizeAdmin, orgScope } from "../shared.ts";import {ADMIN_RESOURCES,ADMIN_RESOURCE_BY_ID,@@ -116,7 +116,8 @@ export async function whoami(ctx: ApiCtx): Promise<void> {const { res, deps } = ctx;if (!deps.admin) return sendJson(res, 404, { error: "not_found" });const actor = adminActorFrom(ctx);- if (!actor) return sendJson(res, 200, { isAdmin: false, permissions: [] });+ if (!actor || !(await activePrincipal(deps, actor.id)))+ return sendJson(res, 200, { isAdmin: false, permissions: [] });const status = await deps.admin.adminStatusOf(actor);const permissions = status.isAdmin ? ["admin"] : [];audit(deps, {diff --git a/src/api/routes/admin/users.ts b/src/api/routes/admin/users.tsindex 2cfd57974..837fd6837 100644--- a/src/api/routes/admin/users.ts+++ b/src/api/routes/admin/users.ts@@ -6,14 +6,27 @@ import type { AdminRole } from "../../../admin/admin-grant-store.ts";import type { DirectoryMember } from "../../../directory/directory-store.ts";import { computeUsers } from "../../../admin/users.ts";import { forEachAttributedTurn } from "../../../admin/attribution.ts";+import { INVITE_EMAIL_NOT_CONFIGURED, renderInviteEmail } from "../../../admin/invite-email.ts";+import { externalMemberActive, validEmail, type ExternalMember } from "../../../identity/external-members.ts";+import { resolveBranding } from "../../../resolution/branding.ts";+import { errMessage } from "../../../util/errors.ts";+import { normalizeInboundExpiresAt } from "../../expiry.ts";import { detectOnboardingStatus, setOnboardingStatus, type OnboardingStatus } from "../../../onboarding/onboarding.ts";import { sendJson } from "../../http.ts";-import { audit, authorizeAdmin, orgScope } from "../shared.ts";+import { audit, authorizeAdmin, isObj, orgScope } from "../shared.ts";import { type ApiCtx } from "../route.ts";import { FILES_PAGE_SIZE } from "./common.ts";const USER_CONVERSATIONS_MAX = 100;const USER_FILES_MAX = 200;+const EXTERNAL_ORG_ADMIN_PORTAL_ONLY =+ "granting or removing org admin for an external user is portal-only — the agent cannot manage who governs the org";+const ALREADY_A_MEMBER =+ "that address already belongs to a member of the org — manage them under Users and Admins, not as an external user";+const HOLDS_OWN_GRANT =+ "that address holds an org admin grant of its own — revoke it under Admins first, or re-invite with role org_admin";+const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;+const FORGET_AFTER_MS = 24 * 60 * 60 * 1000;export async function listUsers(ctx: ApiCtx): Promise<void> {const { res, deps } = ctx;@@ -25,7 +38,179 @@ export async function listUsers(ctx: ApiCtx): Promise<void> {const turns = (await deps.sessions?.attributedTurns()) ?? [];const grants = (await deps.admin?.listGrants()) ?? [];const users = computeUsers({ participants, turns, grants });- return sendJson(res, 200, { scopeId: scope, users, grants });+ const now = Date.now();+ const externalUsers = ((await deps.identity?.listExternalMembers()) ?? [])+ .map((m) => ({ ...m, status: externalMemberActive(m, now) ? ("active" as const) : ("expired" as const) }))+ .sort((a, b) => Number(b.status === "active") - Number(a.status === "active") || a.expiresAt - b.expiresAt);+ const signInUrl = signInUrlOf(deps);+ const inviteEmail = {+ configured: deps.inviteMailer !== undefined,+ ...(deps.inviteMailer ? {} : { problem: INVITE_EMAIL_NOT_CONFIGURED }),+ ...(signInUrl ? { signInUrl } : {}),+ };+ return sendJson(res, 200, { scopeId: scope, users, grants, externalUsers, inviteEmail });+}++function signInUrlOf(deps: ApiCtx["deps"]): string | undefined {+ return deps.portalUrl ? `${deps.portalUrl.replace(/\/+$/, "")}/auth/login` : undefined;+}++function endOfDayUtc(value: unknown): unknown {+ return typeof value === "string" && DATE_ONLY.test(value.trim()) ? `${value.trim()}T23:59:59.999Z` : value;+}++function grantError(res: ApiCtx["res"], error: string, e: unknown): void {+ if (e instanceof AdminError) return sendJson(res, e.status, { error, message: e.message });+ throw e;+}++async function orgMember(ctx: ApiCtx, email: string, includeSessions: boolean): Promise<boolean> {+ const { deps } = ctx;+ if (deps.emailAuthDomain && email.endsWith(`@${deps.emailAuthDomain}`)) return true;+ if ((deps.emailAuthPrincipals ?? []).some((principal) => samePerson(principal, email))) return true;+ if (await deps.directory?.get(email)) return true;+ if (!includeSessions) return false;+ const participants = (await deps.sessions?.listParticipants()) ?? [];+ return participants.some((participant) => samePerson(participant.principalId, email));+}++export async function inviteExternalUser(ctx: ApiCtx): Promise<void> {+ const { res, deps, body } = ctx;+ const scope = orgScope(deps);+ const actor = await authorizeAdmin(ctx, scope);+ if (!actor) return;+ if (!deps.identity) return sendJson(res, 404, { error: "not_found" });+ const bad = (message: string) => sendJson(res, 400, { error: "bad_request", message });+ const b = isObj(body) ? body : {};+ const email = String(b.email ?? "")+ .trim()+ .toLowerCase();+ if (!validEmail(email)) return bad("a valid email address is required");+ const role = b.role ?? "member";+ if (role !== "member" && role !== "org_admin") return bad("role must be member or org_admin");+ const expiry = normalizeInboundExpiresAt(endOfDayUtc(b.expiresAt));+ if (!expiry.ok) return bad(expiry.message);+ const now = Date.now();+ if (expiry.value === undefined || expiry.value <= now) return bad("expiresAt is required and must be in the future");+ await deps.identity.refresh(true);+ const existing = deps.identity.externalMember(email);+ const holdsGrant = adminStatusFromGrants(await deps.admin!.listGrants(), email).isAdmin;+ const ownsGrant = existing?.role === "org_admin";+ if ((!existing && holdsGrant) || (await orgMember(ctx, email, !existing)))+ return sendJson(res, 409, { error: "conflict", message: ALREADY_A_MEMBER });+ if (ctx.capability && (role === "org_admin" || ownsGrant || holdsGrant)) {+ return sendJson(res, 403, { error: "forbidden", message: EXTERNAL_ORG_ADMIN_PORTAL_ONLY });+ }+ if (role === "member" && holdsGrant && !ownsGrant)+ return sendJson(res, 409, { error: "conflict", message: HOLDS_OWN_GRANT });+ let grantChange: "grant.create" | "grant.revoke" | null = null;+ if (role === "org_admin" && !holdsGrant) grantChange = "grant.create";+ else if (role === "member" && holdsGrant) grantChange = "grant.revoke";+ try {+ if (grantChange === "grant.create")+ await deps.admin!.createGrant(actor, { principalId: email, role: "org_admin", scopeId: scope });+ else if (grantChange === "grant.revoke") await deps.admin!.revokeGrant(actor, email, scope, "org_admin");+ } catch (e) {+ return grantError(res, "grant_failed", e);+ }+ if (grantChange)+ audit(deps, { principalId: actor.id, action: grantChange, resource: `${email}/org_admin`, scopeLabel: scope });+ const created = existing === undefined;+ const readmitted = existing !== undefined && !externalMemberActive(existing, now);+ const member: ExternalMember = {+ email,+ role,+ expiresAt: expiry.value,+ invitedBy: existing?.invitedBy ?? actor.id,+ createdAt: existing?.createdAt ?? now,+ updatedAt: now,+ };+ await deps.identity.putExternalMember(member);+ audit(deps, {+ principalId: actor.id,+ action: created || readmitted ? "external_user.invite" : "external_user.update",+ resource: email,+ scopeLabel: scope,+ });+ const signInUrl = signInUrlOf(deps);+ let emailSent = false;+ let emailProblem: string | undefined;+ if (created || readmitted || b.resendInvite === true) {+ if (!deps.inviteMailer) emailProblem = INVITE_EMAIL_NOT_CONFIGURED;+ else if (!signInUrl)+ emailProblem = "no sign-in URL is configured on core (set PUBLIC_WEB_URL) — share the portal address by hand";+ else {+ const branding = await resolveBranding(deps.config, scope, deps.brandingDefault);+ try {+ await deps.inviteMailer.send({+ to: email,+ ...renderInviteEmail({+ to: email,+ brandName: branding.selfLabel ?? "qm",+ invitedBy: actor.id,+ signInUrl,+ expiresAt: member.expiresAt,+ }),+ });+ emailSent = true;+ } catch (e) {+ emailProblem = errMessage(e);+ }+ }+ }+ return sendJson(res, 200, {+ ok: true,+ member,+ created,+ emailSent,+ ...(emailProblem ? { emailProblem } : {}),+ ...(signInUrl ? { signInUrl } : {}),+ });+}++export async function revokeExternalUser(ctx: ApiCtx): Promise<void> {+ const { res, deps, params } = ctx;+ const scope = orgScope(deps);+ const actor = await authorizeAdmin(ctx, scope);+ if (!actor) return;+ if (!deps.identity) return sendJson(res, 404, { error: "not_found" });+ await deps.identity.refresh(true);+ const existing = deps.identity.externalMember(params.email ?? "");+ if (!existing) return sendJson(res, 404, { error: "not_found", message: "external user not found" });+ const holdsGrant = adminStatusFromGrants(await deps.admin!.listGrants(), existing.email).isAdmin;+ const ownsGrant = existing.role === "org_admin";+ if (ctx.capability && (ownsGrant || holdsGrant)) {+ return sendJson(res, 403, { error: "forbidden", message: EXTERNAL_ORG_ADMIN_PORTAL_ONLY });+ }+ if (holdsGrant && !ownsGrant) return sendJson(res, 409, { error: "conflict", message: HOLDS_OWN_GRANT });+ if (holdsGrant) {+ try {+ await deps.admin!.revokeGrant(actor, existing.email, scope, "org_admin");+ } catch (e) {+ return grantError(res, "revoke_failed", e);+ }+ audit(deps, {+ principalId: actor.id,+ action: "grant.revoke",+ resource: `${existing.email}/org_admin`,+ scopeLabel: scope,+ });+ }+ const now = Date.now();+ const tombstone: ExternalMember = {+ ...existing,+ role: "member",+ expiresAt: Math.min(existing.expiresAt, now),+ updatedAt: now,+ };+ if (externalMemberActive(existing, now) || existing.role !== "member") {+ await deps.identity.putExternalMember(tombstone);+ audit(deps, { principalId: actor.id, action: "external_user.revoke", resource: existing.email, scopeLabel: scope });+ }+ if (now - tombstone.expiresAt < FORGET_AFTER_MS) return sendJson(res, 200, { ok: true, removed: false });+ await deps.identity.removeExternalMember(existing.email);+ audit(deps, { principalId: actor.id, action: "external_user.forget", resource: existing.email, scopeLabel: scope });+ return sendJson(res, 200, { ok: true, removed: true });}export async function searchDirectory(ctx: ApiCtx): Promise<void> {diff --git a/src/api/routes/auth-broker.ts b/src/api/routes/auth-broker.tsindex 7a66658d8..d0d68ae9d 100644--- a/src/api/routes/auth-broker.ts+++ b/src/api/routes/auth-broker.ts@@ -1,4 +1,5 @@import { sendJson } from "../http.ts";+import { externalMemberActive } from "../../identity/external-members.ts";import { isObj } from "./shared.ts";import { type ApiCtx, type Route } from "./route.ts";@@ -47,6 +48,19 @@ async function claimBrokerNonce(ctx: ApiCtx): Promise<void> {return sendJson(res, 200, { claimed: null });}+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" });+ 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 } : {}) });+}+export const authBrokerRoutes: ReadonlyArray<Route<ApiCtx>> = [{ method: "POST", path: "/v1/auth/broker/claim", auth: "source", handle: claimBrokerNonce },+ { method: "GET", path: "/v1/auth/broker/email-allowed", auth: "source", handle: emailAllowed },];diff --git a/src/api/routes/shared.ts b/src/api/routes/shared.tsindex e350a969d..4c91765c5 100644--- a/src/api/routes/shared.ts+++ b/src/api/routes/shared.ts@@ -32,11 +32,21 @@ export async function authorizeAdmin(}const grants = await deps.admin.listGrants();const actor = adminActorFrom(ctx);+ if (actor && !(await activePrincipal(deps, actor.id))) {+ sendJson(res, 403, { error: "forbidden", message: "this principal is no longer active" });+ return null;+ }if (actor && adminStatusFromGrants(grants, actor.id).isAdmin) return actor;sendJson(res, 403, { error: "forbidden", message: "admin grant required for this scope" });return null;}+export async function activePrincipal(deps: ServerDeps, principalId: string): Promise<boolean> {+ if (!deps.identity) return true;+ await deps.identity.refresh();+ return deps.identity.classify(principalId).type === "internal";+}+export async function requireScopedAdmin(ctx: Pick<ApiCtx, "req" | "res" | "deps" | "capability" | "actor" | "url">,): Promise<{ actor: Principal; scope: string } | null> {diff --git a/src/config.ts b/src/config.tsindex 2ee517c82..4d32ae961 100644--- a/src/config.ts+++ b/src/config.ts@@ -68,6 +68,9 @@ export interface Config {sessionTapeMode: "shadow" | "serve";adminGrants?: string;emailAuthPrincipals?: string[];+ emailAuthDomain?: string;+ resendApiKey?: string;+ emailFrom?: string;rateLimitPerWindow: number;rateLimitWindowMs: number;budgetUsdPerWindow?: number;@@ -1032,6 +1035,11 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {],}: {}),+ ...(env.AUTH_ALLOWED_EMAIL_DOMAIN?.trim()+ ? { emailAuthDomain: env.AUTH_ALLOWED_EMAIL_DOMAIN.trim().toLowerCase() }+ : {}),+ ...(env.RESEND_API_KEY?.trim() ? { resendApiKey: env.RESEND_API_KEY.trim() } : {}),+ ...(env.AUTH_EMAIL_FROM?.trim() ? { emailFrom: env.AUTH_EMAIL_FROM.trim() } : {}),piCaptureRequests: boolEnvStrict("PI_CAPTURE_REQUESTS", env.PI_CAPTURE_REQUESTS) ?? true,piSystemCacheSplit: boolEnvStrict("PI_SYSTEM_CACHE_SPLIT", env.PI_SYSTEM_CACHE_SPLIT) ?? false,sessionTapeMode: env.SESSION_TAPE_MODE === "shadow" ? "shadow" : "serve",diff --git a/src/identity/external-members.ts b/src/identity/external-members.tsnew file mode 100644index 000000000..fcf46d3ca--- /dev/null+++ b/src/identity/external-members.ts@@ -0,0 +1,18 @@+type ExternalRole = "member" | "org_admin";++export interface ExternalMember {+ email: string;+ role: ExternalRole;+ expiresAt: number;+ invitedBy: string;+ createdAt: number;+ updatedAt: number;+}++export function externalMemberActive(m: ExternalMember, now = Date.now()): boolean {+ return m.expiresAt > now;+}++export function validEmail(value: string): boolean {+ return value.length <= 254 && /^[^@\s,;<>"]+@[^@\s,;<>"]+\.[^@\s,;<>"]+$/.test(value);+}diff --git a/src/identity/identity-service.ts b/src/identity/identity-service.tsindex 9790f08eb..479fd7cfc 100644--- a/src/identity/identity-service.ts+++ b/src/identity/identity-service.ts@@ -1,6 +1,7 @@import type { ActorAssertion, Principal } from "../types.ts";import { createMemoryMap, type DurableMap } from "../persistence/durable-map.ts";import { personKey } from "../directory/person.ts";+import { externalMemberActive, type ExternalMember } from "./external-members.ts";interface IdentityProvider {resolve(actor: ActorAssertion): Principal;@@ -26,27 +27,54 @@ export interface IdentityService extends IdentityProvider {deactivate(externalId: string, source?: DeactivationSource): Promise<void>;reactivate(externalId: string): Promise<void>;recordDirectorySync(removedIds: string[], presentIds: string[]): Promise<DirectorySyncOutcome>;+ listExternalMembers(): Promise<ExternalMember[]>;+ externalMember(principalId: string): ExternalMember | undefined;+ putExternalMember(m: ExternalMember): Promise<void>;+ removeExternalMember(principalId: string): Promise<void>;hydrate(): Promise<void>;- refresh(): Promise<void>;+ refresh(force?: boolean): Promise<void>;}export function createIdentityService(backing?: DurableMap<DeactivationRecord>,- opts: { directorySyncProtected?: readonly string[] } = {},+ opts: { directorySyncProtected?: readonly string[]; externalMembers?: DurableMap<ExternalMember> } = {},): IdentityService {const store = backing ?? createMemoryMap<DeactivationRecord>();+ const externalStore = opts.externalMembers ?? createMemoryMap<ExternalMember>();const deactivated = new Map<string, DeactivationRecord>();+ const externals = new Map<string, ExternalMember>();const directorySyncProtected = new Set((opts.directorySyncProtected ?? []).map(personKey).filter(Boolean));const REFRESH_TTL_MS = 10_000;let refreshedAt = 0;let refreshP: Promise<void> | null = null;let hydrateP: Promise<void> | null = null;+ const keptByDirectorySync = (key: string): boolean => directorySyncProtected.has(key) || externals.has(key);++ async function load(overwrite: boolean): Promise<void> {+ const [deactivations, members] = await Promise.all([store.all(), externalStore.all()]);+ if (overwrite) {+ deactivated.clear();+ externals.clear();+ }+ for (const r of deactivations) {+ const key = personKey(r.principalId);+ if (overwrite || !deactivated.has(key)) deactivated.set(key, r);+ }+ for (const m of members) {+ const key = personKey(m.email);+ if (overwrite || !externals.has(key)) externals.set(key, m);+ }+ }+function classify(externalId: string, isExternalGuest?: boolean): Principal {- const record = deactivated.get(personKey(externalId));+ const key = personKey(externalId);+ const record = deactivated.get(key);+ const external = externals.get(key);const inactive =record?.source === "manual" ||- (record?.source === "directory-sync" && !directorySyncProtected.has(personKey(externalId)));+ (record?.source === "directory-sync" && !keptByDirectorySync(key)) ||+ (external !== undefined && !externalMemberActive(external));const type: Principal["type"] = inactive || isExternalGuest ? "guest" : "internal";return { id: externalId, type };}@@ -66,6 +94,20 @@ export function createIdentityService(await store.delete(key);}+ async function refresh(force = false): Promise<void> {+ const now = Date.now();+ if (refreshP) return refreshP;+ if (!force && now - refreshedAt < REFRESH_TTL_MS) return;+ refreshP = load(true)+ .then(() => {+ refreshedAt = Date.now();+ })+ .finally(() => {+ refreshP = null;+ });+ return refreshP;+ }+return {classify,deactivate,@@ -73,7 +115,7 @@ export function createIdentityService(async recordDirectorySync(removedIds: string[], presentIds: string[]): Promise<DirectorySyncOutcome> {const outcome: DirectorySyncOutcome = { deactivated: [], reactivated: [] };for (const id of removedIds) {- if (directorySyncProtected.has(personKey(id)) || deactivated.has(personKey(id))) continue;+ if (keptByDirectorySync(personKey(id)) || deactivated.has(personKey(id))) continue;await deactivate(id, "directory-sync");outcome.deactivated.push(id);}@@ -84,33 +126,28 @@ export function createIdentityService(}return outcome;},+ async listExternalMembers(): Promise<ExternalMember[]> {+ await refresh();+ return [...externals.values()];+ },+ externalMember(principalId: string): ExternalMember | undefined {+ return externals.get(personKey(principalId));+ },+ async putExternalMember(m: ExternalMember): Promise<void> {+ const key = personKey(m.email);+ externals.set(key, m);+ await externalStore.put(key, m);+ },+ async removeExternalMember(principalId: string): Promise<void> {+ const key = personKey(principalId);+ externals.delete(key);+ await externalStore.delete(key);+ },hydrate(): Promise<void> {- if (!hydrateP) {- hydrateP = store.all().then((records) => {- for (const r of records) {- const key = personKey(r.principalId);- if (!deactivated.has(key)) deactivated.set(key, r);- }- });- }+ if (!hydrateP) hydrateP = load(false);return hydrateP;},- async refresh(): Promise<void> {- const now = Date.now();- if (refreshP) return refreshP;- if (now - refreshedAt < REFRESH_TTL_MS) return;- refreshP = store- .all()- .then((records) => {- deactivated.clear();- for (const record of records) deactivated.set(personKey(record.principalId), record);- refreshedAt = Date.now();- })- .finally(() => {- refreshP = null;- });- return refreshP;- },+ refresh,resolve(actor: ActorAssertion): Principal {const p = classify(actor.externalId, actor.isExternalGuest);return {diff --git a/src/wiring.ts b/src/wiring.tsindex 7b3fa3b7e..f955751bc 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -10,6 +10,8 @@ import {} from "./config.ts";import type { ServerDeps } from "./api/deps.ts";import { createIdentityService, type DeactivationRecord, type IdentityService } from "./identity/identity-service.ts";+import type { ExternalMember } from "./identity/external-members.ts";+import { createResendMailer } from "./admin/invite-email.ts";import {createMemoryConfigStore,type ScopedConfigStore,@@ -453,6 +455,7 @@ export function buildApp(});const identity = createIdentityService(artifactMap<DeactivationRecord>("deactivated_principals"), {directorySyncProtected: config.emailAuthPrincipals,+ externalMembers: artifactMap<ExternalMember>("external_members"),});void identity.hydrate();const leaderLease: LeaderLease = pgArtifactMap@@ -1764,6 +1767,11 @@ export function serverDeps(...(config.publicUrl ? { publicUrl: config.publicUrl } : {}),...(config.publicWebUrl ? { portalUrl: config.publicWebUrl } : {}),admin: built.admin,+ ...(config.emailAuthPrincipals ? { emailAuthPrincipals: config.emailAuthPrincipals } : {}),+ ...(config.emailAuthDomain ? { emailAuthDomain: config.emailAuthDomain } : {}),+ ...(config.resendApiKey && config.emailFrom+ ? { inviteMailer: createResendMailer(config.resendApiKey, config.emailFrom) }+ : {}),rateLimiter: built.rateLimiter,acl: built.acl,credentialUsage: built.credentialUsage,diff --git a/test/admin-external-users.test.ts b/test/admin-external-users.test.tsnew file mode 100644index 000000000..803903719--- /dev/null+++ b/test/admin-external-users.test.ts@@ -0,0 +1,565 @@+import "./support/auto-fake-sprites.ts";++import { test } from "node:test";+import assert from "node:assert/strict";+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import type { AddressInfo } from "node:net";+import { createInsecureTestServer, createServer } from "../src/api/server.ts";+import { buildApp } from "../src/wiring.ts";+import { INVITE_EMAIL_NOT_CONFIGURED, renderInviteEmail, type InviteMailer } from "../src/admin/invite-email.ts";+import { adminStatusFromGrants } from "../src/admin/admin-service.ts";+import { coreEmailAllowed } from "../plugins/chassis/src/external-members.ts";+import { mintCapabilityToken, CAPABILITY_TTL_MS, CONTROL_PLANE_AUD } from "../src/auth/capability-token.ts";+import { scopeId, type TurnRequest } from "../src/types.ts";+import { testConfig } from "./support/test-config.ts";++const ALICE = "admin-alice@default-org";+const NOBODY = "user-uma@default-org";+const SECRET = "external-users-test-secret".repeat(2);+const PORTAL = "https://portal.example.com";+const ORG = scopeId("org", "default-org");+const DAY_MS = 24 * 60 * 60 * 1000;++type Sent = { to: string; subject: string; text: string; html: string };++function stubMailer(fail?: string): { sent: Sent[]; mailer: InviteMailer } {+ const sent: Sent[] = [];+ return {+ sent,+ mailer: {+ async send(message) {+ if (fail) throw new Error(fail);+ sent.push(message);+ return "msg-1";+ },+ },+ };+}++function start(+ opts: { mailer?: InviteMailer; signed?: boolean; emailAuthDomain?: string; emailAuthPrincipals?: string[] } = {},+) {+ const built = buildApp(+ testConfig({+ dataDir: mkdtempSync(join(tmpdir(), "admin-external-users-")),+ ...(opts.signed ? { signingSecret: SECRET } : {}),+ }),+ );+ const deps = {+ admin: built.admin,+ sessions: built.sessions,+ auditLog: built.auditLog,+ identity: built.identity,+ directory: built.directory,+ config: built.config,+ portalUrl: PORTAL,+ brandingDefault: { selfLabel: "Acme Bot" },+ ...(opts.mailer ? { inviteMailer: opts.mailer } : {}),+ ...(opts.emailAuthDomain ? { emailAuthDomain: opts.emailAuthDomain } : {}),+ ...(opts.emailAuthPrincipals ? { emailAuthPrincipals: opts.emailAuthPrincipals } : {}),+ };+ const server = opts.signed+ ? createServer(built.app, { ...deps, signingSecret: SECRET })+ : createInsecureTestServer(built.app, deps);+ server.listen(0);+ const base = `http://localhost:${(server.address() as AddressInfo).port}`;+ return { base, built, close: () => new Promise<void>((r) => server.close(() => r())) };+}++const invite = (base: string, body: unknown, headers: Record<string, string> = { "x-admin-actor": ALICE }) =>+ fetch(`${base}/v1/admin/external-users`, {+ method: "POST",+ headers: { ...headers, "content-type": "application/json" },+ body: JSON.stringify(body),+ });+const revoke = (base: string, email: string, headers: Record<string, string> = { "x-admin-actor": ALICE }) =>+ fetch(`${base}/v1/admin/external-users/${encodeURIComponent(email)}`, { method: "DELETE", headers });+const roster = async (base: string, headers: Record<string, string> = { "x-admin-actor": ALICE }): Promise<any> =>+ (await fetch(`${base}/v1/admin/users`, { headers })).json();++const capFor = (actorId: string) =>+ mintCapabilityToken(+ {+ actorId,+ scopeId: scopeId("personal", actorId),+ aud: CONTROL_PLANE_AUD,+ liveActor: true,+ exp: Date.now() + CAPABILITY_TTL_MS,+ },+ SECRET,+ );++test("inviting an external user stores the record, lists it as active, audits, and reports the missing mailer", async () => {+ const s = start();+ try {+ const expiresAt = new Date(Date.now() + 30 * DAY_MS).toISOString();+ const r = await invite(s.base, { email: " [email protected] ", expiresAt });+ assert.equal(r.status, 200);+ const d: any = await r.json();+ assert.equal(d.ok, true);+ assert.equal(d.created, true);+ assert.equal(d.member.email, "[email protected]");+ assert.equal(d.member.role, "member");+ assert.equal(d.member.invitedBy, "admin-alice");+ assert.equal(d.member.expiresAt, Date.parse(expiresAt));+ assert.equal(d.emailSent, false);+ assert.equal(d.emailProblem, INVITE_EMAIL_NOT_CONFIGURED);+ assert.equal(d.signInUrl, `${PORTAL}/auth/login`);++ const list = await roster(s.base);+ assert.deepEqual(list.inviteEmail, {+ configured: false,+ problem: INVITE_EMAIL_NOT_CONFIGURED,+ signInUrl: `${PORTAL}/auth/login`,+ });+ assert.equal(list.externalUsers.length, 1);+ assert.equal(list.externalUsers[0].email, "[email protected]");+ assert.equal(list.externalUsers[0].status, "active");+ assert.ok(!list.users.some((u: any) => u.principalId === "[email protected]"), "not folded into users");++ const again = await invite(s.base, { email: "[email protected]", expiresAt: Date.now() + 60 * DAY_MS });+ const updated: any = await again.json();+ assert.equal(updated.created, false);+ assert.equal(updated.member.createdAt, d.member.createdAt);+ assert.equal(updated.emailSent, false);+ assert.equal(updated.emailProblem, undefined, "an update does not retry the invitation email");++ const events = await s.built.auditLog.events();+ assert.ok(events.some((e) => e.action === "external_user.invite" && e.resource === "[email protected]"));+ assert.ok(events.some((e) => e.action === "external_user.update" && e.resource === "[email protected]"));++ assert.equal((await invite(s.base, { email: "[email protected]", expiresAt }, { "x-admin-actor": NOBODY })).status, 403);+ } finally {+ await s.close();+ }+});++test("role org_admin grants admin; member revokes it; DELETE drops the grant and expires the record", async () => {+ const s = start();+ try {+ const expiresAt = Date.now() + 7 * DAY_MS;+ const isAdmin = async (email: string) => adminStatusFromGrants(await s.built.admin.listGrants(), email).isAdmin;++ assert.equal((await invite(s.base, { email: "[email protected]", role: "org_admin", expiresAt })).status, 200);+ assert.equal(await isAdmin("[email protected]"), true);++ assert.equal((await invite(s.base, { email: "[email protected]", role: "member", expiresAt })).status, 200);+ assert.equal(await isAdmin("[email protected]"), false);++ assert.equal((await invite(s.base, { email: "[email protected]", role: "org_admin", expiresAt })).status, 200);+ assert.equal(await isAdmin("[email protected]"), true);+ assert.equal(s.built.identity.classify("[email protected]").type, "internal");++ const gone = await revoke(s.base, "[email protected]");+ assert.equal(gone.status, 200);+ assert.equal(await isAdmin("[email protected]"), false);+ assert.equal(+ s.built.identity.classify("[email protected]").type,+ "guest",+ "a revoked external loses access now",+ );+ const tomb = s.built.identity.externalMember("[email protected]");+ assert.equal(tomb?.role, "member");+ assert.ok(tomb!.expiresAt <= Date.now());+ assert.deepEqual(+ (await roster(s.base)).externalUsers.map((m: any) => [m.email, m.status]),+ [["[email protected]", "expired"]],+ );+ const events = await s.built.auditLog.events();+ assert.ok(events.some((e) => e.action === "external_user.revoke"));+ assert.deepEqual(+ events.filter((e) => e.action === "grant.create" || e.action === "grant.revoke").map((e) => e.action),+ ["grant.create", "grant.revoke", "grant.create", "grant.revoke"],+ );++ const again: any = await (await revoke(s.base, "[email protected]")).json();+ assert.deepEqual(again, { ok: true, removed: false }, "revoking again is a no-op until a day has passed");+ assert.equal((await revoke(s.base, "[email protected]")).status, 404);++ const back = await invite(s.base, { email: "[email protected]", expiresAt });+ assert.equal(((await back.json()) as any).created, false);+ assert.equal(s.built.identity.classify("[email protected]").type, "internal", "a new expiry readmits them");++ const now = Date.now();+ await s.built.identity.putExternalMember({+ email: "[email protected]",+ role: "member",+ expiresAt: now - 2 * DAY_MS,+ invitedBy: "admin-alice",+ createdAt: now - 30 * DAY_MS,+ updatedAt: now - 2 * DAY_MS,+ });+ const forgotten: any = await (await revoke(s.base, "[email protected]")).json();+ assert.deepEqual(forgotten, { ok: true, removed: true });+ assert.equal(s.built.identity.externalMember("[email protected]"), undefined);+ assert.ok((await s.built.auditLog.events()).some((e) => e.action === "external_user.forget"));+ } finally {+ await s.close();+ }+});++test("an address that already belongs to an org member cannot be invited", async () => {+ const s = start({ emailAuthDomain: "corp.example", emailAuthPrincipals: ["[email protected]"] });+ try {+ const expiresAt = Date.now() + DAY_MS;+ const alice = s.built.admin.resolveActor(ALICE)!;+ await s.built.admin.createGrant(alice, { principalId: "[email protected]", role: "org_admin", scopeId: ORG });+ await s.built.directory.replace([{ principalId: "[email protected]", displayName: "Dana", type: "internal" }]);+ const dm: TurnRequest = {+ surface: "test",+ actor: { externalId: "[email protected]" },+ conversation: { kind: "dm", threadRef: "dm:seen:t1" },+ text: "hello",+ };+ assert.equal((await s.built.app.turn(dm)).status, "ok");++ for (const email of [+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ ]) {+ const r = await invite(s.base, { email, expiresAt });+ assert.equal(r.status, 409, email);+ assert.match(((await r.json()) as any).message, /already belongs to a member/);+ assert.equal(s.built.identity.externalMember(email), undefined, email);+ }+ assert.equal(adminStatusFromGrants(await s.built.admin.listGrants(), "[email protected]").isAdmin, true);+ assert.deepEqual((await roster(s.base)).externalUsers, []);++ assert.equal((await invite(s.base, { email: "[email protected]", expiresAt })).status, 200);+ await s.built.admin.createGrant(alice, { principalId: "[email protected]", role: "org_admin", scopeId: ORG });+ const extend = await invite(s.base, { email: "[email protected]", expiresAt: expiresAt + DAY_MS });+ assert.equal(extend.status, 409, "a member record cannot silently carry an independently granted admin role");+ assert.match(((await extend.json()) as any).message, /holds an org admin grant/);+ const del = await revoke(s.base, "[email protected]");+ assert.equal(del.status, 409);+ assert.equal(adminStatusFromGrants(await s.built.admin.listGrants(), "[email protected]").isAdmin, true);+ assert.equal(s.built.identity.classify("[email protected]").type, "internal");++ const adopt: any = await (+ await invite(s.base, { email: "[email protected]", role: "org_admin", expiresAt: expiresAt + DAY_MS })+ ).json();+ assert.equal(adopt.member.role, "org_admin", "re-inviting with role org_admin adopts the grant");+ const grantAudits = (await s.built.auditLog.events()).filter((e) => e.resource === "[email protected]/org_admin");+ assert.deepEqual(grantAudits, [], "adopting an existing grant creates nothing");+ assert.equal((await revoke(s.base, "[email protected]")).status, 200);+ assert.equal(adminStatusFromGrants(await s.built.admin.listGrants(), "[email protected]").isAdmin, false);+ } finally {+ await s.close();+ }+});++test("an expired external org admin no longer passes the admin authorizer", async () => {+ const s = start();+ try {+ assert.equal(+ (await invite(s.base, { email: "[email protected]", role: "org_admin", expiresAt: Date.now() + DAY_MS }))+ .status,+ 200,+ );+ const boss = { "x-admin-actor": "[email protected]@default-org" };+ assert.equal((await fetch(`${s.base}/v1/admin/users`, { headers: boss })).status, 200);+ const record = s.built.identity.externalMember("[email protected]")!;+ await s.built.identity.putExternalMember({ ...record, expiresAt: Date.now() - 1 });+ const denied = await fetch(`${s.base}/v1/admin/users`, { headers: boss });+ assert.equal(denied.status, 403);+ assert.match(((await denied.json()) as any).message, /no longer active/);+ const who: any = await (await fetch(`${s.base}/v1/admin/whoami`, { headers: boss })).json();+ assert.equal(who.isAdmin, false);+ } finally {+ await s.close();+ }+});++test("revoking the last org admin is refused and leaves the external record untouched", async () => {+ const s = start();+ try {+ const expiresAt = Date.now() + DAY_MS;+ assert.equal((await invite(s.base, { email: "[email protected]", role: "org_admin", expiresAt })).status, 200);+ const alice = s.built.admin.resolveActor(ALICE)!;+ await s.built.admin.revokeGrant(alice, "admin-bob", ORG, "org_admin");+ await s.built.admin.revokeGrant(alice, "admin-alice", ORG, "org_admin");++ const boss = { "x-admin-actor": "[email protected]@default-org" };+ const r = await revoke(s.base, "[email protected]", boss);+ assert.equal(r.status, 400);+ assert.match(((await r.json()) as any).message, /last org admin/);+ const kept = s.built.identity.externalMember("[email protected]");+ assert.equal(kept?.role, "org_admin");+ assert.equal(kept?.expiresAt, expiresAt);+ assert.ok(!(await s.built.auditLog.events()).some((e) => e.action === "external_user.revoke"));++ const demote = await invite(s.base, { email: "[email protected]", role: "member", expiresAt }, boss);+ assert.equal(demote.status, 400);+ assert.equal(s.built.identity.externalMember("[email protected]")?.role, "org_admin");+ } finally {+ await s.close();+ }+});++test("invite validation: past expiry, missing expiry, bad email, and bad role are 400", async () => {+ const s = start();+ try {+ const cases: unknown[] = [+ { email: "[email protected]", expiresAt: Date.now() - 1000 },+ { email: "[email protected]" },+ { email: "[email protected]", expiresAt: "not a date" },+ { email: "not-an-email", expiresAt: Date.now() + DAY_MS },+ { email: "[email protected]", role: "owner", expiresAt: Date.now() + DAY_MS },+ ];+ for (const body of cases) {+ const r = await invite(s.base, body);+ assert.equal(r.status, 400, JSON.stringify(body));+ assert.equal(((await r.json()) as any).error, "bad_request");+ }+ assert.deepEqual((await roster(s.base)).externalUsers, []);++ const dated: any = await (await invite(s.base, { email: "[email protected]", expiresAt: "2031-03-04" })).json();+ assert.equal(dated.member.expiresAt, Date.UTC(2031, 2, 4, 23, 59, 59, 999), "a bare date ends that day, UTC");+ } finally {+ await s.close();+ }+});++test("with a mailer the invitation goes out carrying the sign-in URL and brand; a send failure still saves the record", async () => {+ const ok = stubMailer();+ const s = start({ mailer: ok.mailer });+ try {+ const expiresAt = Date.now() + 14 * DAY_MS;+ const r: any = await (await invite(s.base, { email: "[email protected]", expiresAt })).json();+ assert.equal(r.emailSent, true);+ assert.equal(r.emailProblem, undefined);+ assert.equal(ok.sent.length, 1);+ assert.equal(ok.sent[0]!.to, "[email protected]");+ assert.match(ok.sent[0]!.subject, /invited to Acme Bot/);+ assert.ok(ok.sent[0]!.text.includes(`${PORTAL}/auth/login`));+ assert.match(ok.sent[0]!.text, /admin-alice/);+ assert.match(ok.sent[0]!.html, /Acme Bot/);+ assert.equal((await roster(s.base)).inviteEmail.configured, true);++ const resent: any = await (+ await invite(s.base, { email: "[email protected]", expiresAt, resendInvite: true })+ ).json();+ assert.equal(resent.emailSent, true);+ assert.equal(ok.sent.length, 2);++ assert.equal((await revoke(s.base, "[email protected]")).status, 200);+ const readmit: any = await (await invite(s.base, { email: "[email protected]", expiresAt })).json();+ assert.equal(readmit.created, false);+ assert.equal(readmit.emailSent, true, "readmitting a revoked address sends the invitation again");+ assert.equal(ok.sent.length, 3);+ const extend: any = await (+ await invite(s.base, { email: "[email protected]", expiresAt: expiresAt + DAY_MS })+ ).json();+ assert.equal(extend.emailSent, false, "extending an active member sends nothing");+ assert.equal(ok.sent.length, 3);+ } finally {+ await s.close();+ }++ const broken = stubMailer("Resend rejected the message: HTTP 403 domain not verified");+ const f = start({ mailer: broken.mailer });+ try {+ const r: any = await (+ await invite(f.base, { email: "[email protected]", expiresAt: Date.now() + DAY_MS })+ ).json();+ assert.equal(r.ok, true);+ assert.equal(r.emailSent, false);+ assert.match(r.emailProblem, /HTTP 403 domain not verified/);+ assert.equal(r.signInUrl, `${PORTAL}/auth/login`);+ assert.equal(f.built.identity.externalMember("[email protected]")?.role, "member");+ } finally {+ await f.close();+ }+});++test("renderInviteEmail escapes HTML and names the sign-in URL and expiry", () => {+ const mail = renderInviteEmail({+ to: "[email protected]",+ brandName: "<Acme>",+ invitedBy: "admin-alice",+ signInUrl: "https://portal.example.com/auth/login",+ expiresAt: Date.UTC(2030, 0, 2),+ });+ assert.equal(mail.subject, "You've been invited to <Acme>");+ assert.match(mail.html, /<Acme>/);+ assert.doesNotMatch(mail.html, /<Acme>/);+ assert.match(mail.text, /https:\/\/portal\.example\.com\/auth\/login/);+ assert.match(mail.text, /02 Jan 2030/);+});++test("an agent token may invite a member but never grant, demote, or revoke an org_admin external", async () => {+ const s = start({ signed: true });+ try {+ const cap = { "x-agent-capability": await capFor("admin-alice") };+ const expiresAt = Date.now() + DAY_MS;++ const member = await invite(s.base, { email: "[email protected]", expiresAt }, cap);+ assert.equal(member.status, 200);+ assert.equal(((await member.json()) as any).member.invitedBy, "admin-alice");++ const promote = await invite(s.base, { email: "[email protected]", role: "org_admin", expiresAt }, cap);+ assert.equal(promote.status, 403);+ assert.match(((await promote.json()) as any).message, /portal-only/);+ assert.equal(s.built.identity.externalMember("[email protected]"), undefined);++ const now = Date.now();+ await s.built.identity.putExternalMember({+ email: "[email protected]",+ role: "org_admin",+ expiresAt,+ invitedBy: "admin-bob",+ createdAt: now,+ updatedAt: now,+ });+ const demote = await invite(s.base, { email: "[email protected]", role: "member", expiresAt }, cap);+ assert.equal(demote.status, 403);+ const del = await revoke(s.base, "[email protected]", cap);+ assert.equal(del.status, 403);+ assert.match(((await del.json()) as any).message, /portal-only/);+ assert.equal(s.built.identity.externalMember("[email protected]")?.role, "org_admin");++ assert.equal((await revoke(s.base, "[email protected]", cap)).status, 200);+ assert.equal(s.built.identity.classify("[email protected]").type, "guest");++ const alice = s.built.admin.resolveActor(ALICE)!;+ await s.built.admin.createGrant(alice, { principalId: "[email protected]", role: "org_admin", scopeId: ORG });+ const demoteViaInvite = await invite(s.base, { email: "[email protected]", role: "member", expiresAt }, cap);+ assert.equal(demoteViaInvite.status, 409);+ assert.equal(adminStatusFromGrants(await s.built.admin.listGrants(), "[email protected]").isAdmin, true);+ assert.equal(s.built.identity.externalMember("[email protected]"), undefined);++ await s.built.identity.putExternalMember({+ email: "[email protected]",+ role: "member",+ expiresAt,+ invitedBy: "admin-bob",+ createdAt: now,+ updatedAt: now,+ });+ await s.built.admin.createGrant(alice, {+ principalId: "[email protected]",+ role: "org_admin",+ scopeId: ORG,+ });+ for (const attempt of [+ revoke(s.base, "[email protected]", cap),+ invite(s.base, { email: "[email protected]", role: "member", expiresAt: expiresAt + DAY_MS }, cap),+ ]) {+ const r = await attempt;+ assert.equal(r.status, 403);+ assert.match(((await r.json()) as any).message, /portal-only/);+ }+ assert.equal(s.built.identity.classify("[email protected]").type, "internal");+ assert.equal(adminStatusFromGrants(await s.built.admin.listGrants(), "[email protected]").isAdmin, true);++ assert.equal((await invite(s.base, { email: "[email protected]", expiresAt }, { "x-admin-actor": ALICE })).status, 401);+ } finally {+ await s.close();+ }+});++test("expiry classifies an external as guest, and the signed broker check answers accordingly", async () => {+ const s = start({ signed: true });+ try {+ const now = Date.now();+ const record = (email: string, expiresAt: number) => ({+ email,+ role: "member" as const,+ expiresAt,+ invitedBy: "admin-alice",+ createdAt: now,+ updatedAt: now,+ });+ await s.built.identity.putExternalMember(record("[email protected]", now + DAY_MS));+ await s.built.identity.putExternalMember(record("[email protected]", now - 1));+ assert.equal(s.built.identity.classify("[email protected]").type, "internal");+ assert.equal(s.built.identity.classify("[email protected]").type, "guest");++ assert.equal(await coreEmailAllowed(s.base, SECRET, "[email protected]", "test"), true);+ assert.equal(await coreEmailAllowed(s.base, SECRET, "[email protected]", "test"), false);+ assert.equal(await coreEmailAllowed(s.base, SECRET, "[email protected]", "test"), false);+ assert.equal(await coreEmailAllowed(s.base, "wrong-secret".repeat(4), "[email protected]", "test"), false);+ assert.equal(await coreEmailAllowed("http://127.0.0.1:1", SECRET, "[email protected]", "test"), false);+ const unsigned = await fetch(`${s.base}/v1/auth/broker/email-allowed?email=live%40partner.example`);+ assert.equal(unsigned.status, 401);++ await s.built.identity.deactivate("[email protected]");+ assert.equal(await coreEmailAllowed(s.base, SECRET, "[email protected]", "test"), false);+ await s.built.identity.reactivate("[email protected]");++ const list = await roster(s.base, { "x-agent-capability": await capFor("admin-alice") });+ assert.deepEqual(+ list.externalUsers.map((m: any) => [m.email, m.status]),+ [+ ["[email protected]", "active"],+ ["[email protected]", "expired"],+ ],+ );+ } finally {+ await s.close();+ }+});++test("the directory resolves an active external member and not an expired one", async () => {+ const s = start();+ try {+ const now = Date.now();+ const record = (email: string, expiresAt: number) => ({+ email,+ role: "member" as const,+ expiresAt,+ invitedBy: "admin-alice",+ createdAt: now,+ updatedAt: now,+ });+ await s.built.identity.putExternalMember(record("[email protected]", now + DAY_MS));+ await s.built.identity.putExternalMember(record("[email protected]", now - 1));++ assert.deepEqual(await s.built.app.directoryMember("[email protected]"), {+ principalId: "[email protected]",+ displayName: "[email protected]",+ type: "internal",+ });+ assert.equal(await s.built.app.directoryMember("[email protected]"), null);+ assert.equal((await s.built.app.resolveRecipient("[email protected]")).kind, "one");+ assert.equal((await s.built.app.resolveRecipient("[email protected]")).kind, "none");+ assert.ok((await s.built.app.directoryMembers()).some((m) => m.principalId === "[email protected]"));+ assert.ok(!(await s.built.app.directoryMembers()).some((m) => m.principalId === "[email protected]"));++ const hit = await fetch(`${s.base}/v1/admin/directory?q=${encodeURIComponent("[email protected]")}`, {+ headers: { "x-admin-actor": ALICE },+ });+ assert.deepEqual(((await hit.json()) as any).members, [+ { principalId: "[email protected]", displayName: "[email protected]" },+ ]);+ } finally {+ await s.close();+ }+});++test("directory sync never deactivates an external member; manual deactivation still wins", async () => {+ const s = start();+ try {+ const now = Date.now();+ await s.built.identity.putExternalMember({+ email: "[email protected]",+ role: "member",+ expiresAt: now + DAY_MS,+ invitedBy: "admin-alice",+ createdAt: now,+ updatedAt: now,+ });+ const outcome = await s.built.identity.recordDirectorySync(["[email protected]"], []);+ assert.deepEqual(outcome.deactivated, []);+ assert.equal(s.built.identity.classify("[email protected]").type, "internal");+ await s.built.identity.deactivate("[email protected]");+ assert.equal(s.built.identity.classify("[email protected]").type, "guest");+ } finally {+ await s.close();+ }+});diff --git a/test/identity.test.ts b/test/identity.test.tsindex 58eaa044f..f358a8fcf 100644--- a/test/identity.test.ts+++ b/test/identity.test.ts@@ -1,6 +1,7 @@import { test } from "node:test";import assert from "node:assert/strict";import { createIdentityService, type DeactivationRecord } from "../src/identity/identity-service.ts";+import type { ExternalMember } from "../src/identity/external-members.ts";import { createMemoryMap } from "../src/persistence/durable-map.ts";const id = createIdentityService();@@ -93,6 +94,36 @@ test("a running instance refreshes deactivations written by another instance", aassert.equal(reader.classify("U-leaver").type, "guest");});+test("external members written by one instance reach another over the same backing", async () => {+ const externalMembers = createMemoryMap<ExternalMember>();+ const writer = createIdentityService(undefined, { externalMembers });+ const reader = createIdentityService(undefined, { externalMembers });+ await reader.hydrate();+ const now = Date.now();+ const member = (expiresAt: number): ExternalMember => ({+ email: "[email protected]",+ role: "member",+ expiresAt,+ invitedBy: "admin-alice",+ createdAt: now,+ updatedAt: now,+ });+ await writer.putExternalMember(member(now + 60_000));+ assert.equal(reader.externalMember("[email protected]"), undefined);+ await reader.refresh();+ assert.equal(reader.externalMember("[email protected]")?.expiresAt, now + 60_000);+ assert.equal(reader.classify("[email protected]").type, "internal");++ await writer.putExternalMember(member(now - 1));+ await reader.refresh();+ assert.equal(reader.classify("[email protected]").type, "internal", "within the TTL the cache is served");+ await reader.refresh(true);+ assert.equal(reader.classify("[email protected]").type, "guest", "a forced refresh reads the store");+ const late = createIdentityService(undefined, { externalMembers });+ await late.hydrate();+ assert.equal(late.classify("[email protected]").type, "guest");+});+test("a directory sync deactivates dropped members and self-heals when they reappear", async () => {const svc = createIdentityService();const out = await svc.recordDirectorySync(["U-gone"], ["U-here"]);diff --git a/test/share-deployment.test.ts b/test/share-deployment.test.tsindex 2dc1c7ea8..f3a3abcc5 100644--- a/test/share-deployment.test.ts+++ b/test/share-deployment.test.ts@@ -4,6 +4,7 @@ import { mkdtempSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { createApp, deploymentView } from "../src/api/app.ts";+import { createIdentityService } from "../src/identity/identity-service.ts";import { createToolContext, type ToolContext } from "../src/tools/primitives.ts";import { createDeployStore } from "../src/deploy/deploy-store.ts";import { createDeployService, type DeployService } from "../src/deploy/deploy-service.ts";@@ -43,7 +44,11 @@ function makeDeploy(): { deploy: DeployService; acl: AclStore } {function apiHarness(directory?: Dir) {const { deploy, acl } = makeDeploy();- const app = createApp({ deploy, ...(directory ? { directory } : {}) } as unknown as Parameters<typeof createApp>[0]);+ const app = createApp({+ deploy,+ identity: createIdentityService(),+ ...(directory ? { directory } : {}),+ } as unknown as Parameters<typeof createApp>[0]);return { app, deploy, acl };}