Multiplayer agent harness for work.
Add teammate invitations and single-use sign-in links to Admin (#1513)
Regan Bellb81ab34d647a
diff --git a/plugins/admin/README.md b/plugins/admin/README.mdindex 0deeda8f4..8e96d1387 100644--- a/plugins/admin/README.md+++ b/plugins/admin/README.md@@ -15,15 +15,14 @@ The **Users** tab (org-wide, org_admin-only) lists everyone who hasused 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.+**Invite teammate** adds someone by email with Member or Org admin access. The invite form grants access without an+expiration date. Teammates appear in Users before their+first session. Addresses already admitted through the domain or allow-list may receive a+sign-in invitation too. Re-inviting an admin never removes their admin role.+Invitations are durable and listed with their access status. Revoke ends access immediately.+Invitation email uses Resend when configured. Teammate invitations contain a single-use sign-in link valid for 24 hours. If delivery is unavailable or fails, Admin shows the same link with a copy control after the invitation is created. Redemption checks current membership and claims the token through durable storage; revocation or a new invitation invalidates earlier links. Company access displays the web email domain and the local Slack allow-list; these are deployment settings, not editable Admin policy.+The existing external-user API still requires an expiry and rejects org members.+Teammate invitations and revocations are restricted to the Admin surface.(`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`.) History (conversation listing with aby-type usage rollup, drilling into transcripts with per-turn model-context breakdowns), Filesdiff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.htmlindex dca74c4c7..d15e68c34 100644--- a/plugins/admin/public/index.html+++ b/plugins/admin/public/index.html@@ -10100,6 +10100,7 @@function renderUsers(root, d) {governanceUI.users.users(root, d, {api,+ copyText,defaultShell,fmtTime,relTime,diff --git a/plugins/admin/test/user-admin-confirmation.test.ts b/plugins/admin/test/user-admin-confirmation.test.tsnew file mode 100644index 000000000..034a2e859--- /dev/null+++ b/plugins/admin/test/user-admin-confirmation.test.ts@@ -0,0 +1,40 @@+import assert from "node:assert/strict";+import test from "node:test";+import { UsersView } from "../ui/users.ts";++test("admin promotion and admin invitations require confirmation before making a request", async () => {+ for (const approved of [false, true]) {+ for (const invite of [false, true]) {+ const requests: string[] = [];+ let message = "";+ const view = Object.create(UsersView.prototype) as UsersView;+ Object.assign(view, {+ data: {},+ email: "[email protected]",+ role: "org_admin",+ pending: new Set(),+ refreshRequest: 0,+ root: { isConnected: true },+ draw() {},+ renderShell() {},+ services: {+ orgScope: "org:qa",+ confirm(text: string) {+ message = text;+ return approved;+ },+ async api(method: string, path: string) {+ if (method === "POST") requests.push(path);+ return { ok: true, data: { member: { email: "[email protected]" }, emailSent: true } };+ },+ clearCache() {},+ },+ });+ if (invite) await view.invite();+ else await view.admin({ principalId: "[email protected]" }, { stopPropagation() {} } as Event);+ assert.match(message, /Make [email protected] an org admin/);+ assert.match(message, /manage users, permissions, and organization settings/);+ assert.deepEqual(requests, approved ? [invite ? "/api/users/invite" : "/api/grants"] : []);+ }+ }+});diff --git a/plugins/admin/test/user-invite-placement.test.ts b/plugins/admin/test/user-invite-placement.test.tsindex 7e6e8f1ac..62ba2e89b 100644--- a/plugins/admin/test/user-invite-placement.test.ts+++ b/plugins/admin/test/user-invite-placement.test.ts@@ -2,7 +2,7 @@ import assert from "node:assert/strict";import test from "node:test";import { litFixture } from "./lit-fixture.ts";-test("external invitation form stays in External users and preserves draft through async counts", async () => {+test("teammate invitation form stays in Users and preserves draft through async counts", async () => {const f = litFixture();let resolve!: (v: any) => void;const pending = new Promise((r) => {@@ -15,9 +15,9 @@ test("external invitation form stays in External users and preserves draft throu);assert.deepEqual([...f.root.querySelectorAll("h2")].map((e) => e.textContent),- ["External users", "Users"],+ ["Users", "Invitations", "Company access"],);- const invite = f.root.querySelector<HTMLButtonElement>('[aria-label="Invite external user"]')!;+ const invite = f.root.querySelector<HTMLButtonElement>('[aria-label="Invite teammate"]')!;invite.click();const input = f.root.querySelector<HTMLInputElement>("#users-email")!;input.value = "[email protected]";@@ -28,6 +28,6 @@ test("external invitation form stays in External users and preserves draft throuassert.equal(controller.email, "[email protected]");assert.equal(input, f.root.querySelector("#users-email"));assert.equal(input.value, "[email protected]");- assert.equal(input.closest("section")!.querySelector("h2")!.textContent, "External users");+ assert.equal(input.closest("section")!.querySelector("h2")!.textContent, "Users");f.dom.window.close();});diff --git a/plugins/admin/test/users-state.test.ts b/plugins/admin/test/users-state.test.tsindex 7b7c01349..715e7c536 100644--- a/plugins/admin/test/users-state.test.ts+++ b/plugins/admin/test/users-state.test.ts@@ -13,7 +13,6 @@ function model() {data: {},email: "[email protected]",role: "member",- expires: "2026-12-01",inviteOpen: true,});return view;@@ -70,7 +69,7 @@ test("roster refresh updates shell counts while retaining search focus and invitclearCache() {},labelRole: String,});- f.root.querySelector<HTMLButtonElement>('[aria-label="Invite external user"]')!.click();+ f.root.querySelector<HTMLButtonElement>('[aria-label="Invite teammate"]')!.click();const email = f.root.querySelector<HTMLInputElement>("#users-email")!;email.value = "[email protected]";email.dispatchEvent(new f.window.Event("input"));diff --git a/plugins/admin/ui/users.ts b/plugins/admin/ui/users.tsindex 260338c2b..edbc42ce6 100644--- a/plugins/admin/ui/users.ts+++ b/plugins/admin/ui/users.ts@@ -11,7 +11,9 @@ export class UsersView {inviteOpen = false;email = "";role = "member";- expires = new Date(Date.now() + 30 * 86400000).toISOString().slice(0, 10);+ inviteLink = "";+ inviteWarning = "";+ copyLabel = "Copy invite link";counts = new Map<string, number[]>();pending = new Set<string>();refreshRequest = 0;@@ -98,10 +100,22 @@ export class UsersView {}this.services.clearCache();}+ confirmAdmin(principalId: string) {+ return this.services.confirm(+ "Make " ++ principalId ++ " an org admin?\n\nThey will be able to manage users, permissions, and organization settings.",+ );+ }async admin(user: any, event: Event) {event.stopPropagation();const revoke = user.admin?.isAdmin;- if (!this.services.confirm((revoke ? "Revoke admin access for " : "Make admin: ") + user.principalId + "?")) return;+ if (+ !(revoke+ ? this.services.confirm("Revoke admin access for " + user.principalId + "?")+ : this.confirmAdmin(user.principalId))+ )+ return;await this.action(user.principalId, async () => {const r = revoke? await this.services.api(@@ -147,16 +161,20 @@ export class UsersView {);}async invite() {- const body = { email: this.email.trim(), role: this.role, expiresAt: this.expires };- if (!body.email || !body.expiresAt) {- this.feedback(!body.email ? "Email required." : "Expiry date required.", "err", true);+ const body = { email: this.email.trim(), role: this.role };+ if (!body.email) {+ this.feedback("Email required.", "err", true);this.draw();return;}+ if (body.role === "org_admin" && !this.confirmAdmin(body.email)) return;+ this.inviteLink = "";+ this.inviteWarning = "";+ this.copyLabel = "Copy invite link";await this.action("invite",async () => {- const r = await this.services.api("POST", "/api/external-users", body);+ const r = await this.services.api("POST", "/api/users/invite", body);if (!r.ok)return this.feedback(r.status === 403 ? "Only an admin may invite." : r.data?.message || "Invite failed.",@@ -164,21 +182,16 @@ export class UsersView {true,);const member = r.data.member;- const expiry = " (expires " + this.services.fmtTime(member.expiresAt) + ")";await this.refresh();- let message = "Updated " + member.email + " — " + this.services.labelRole(member.role) + expiry;- if (r.data.emailSent) message = "Invite sent to " + member.email + expiry;- else if (r.data.emailProblem)- message =- "Added " +- member.email +- ", but no invitation email was sent: " +- r.data.emailProblem +- "." +- (r.data.signInUrl ? " Portal: " + r.data.signInUrl + ". A working sign-in method is required." : "");- this.feedback(message, r.data.emailSent || !r.data.emailProblem ? "ok" : "dirty", true);- if (this.email.trim() === body.email && this.role === body.role && this.expires === body.expiresAt)- this.inviteOpen = false;+ this.feedback(r.data.emailSent ? "Invite sent to " + member.email : "Added " + member.email + ".", "ok", true);+ if (!r.data.emailSent && r.data.signInUrl) {+ this.inviteLink = r.data.signInUrl;+ this.inviteWarning =+ this.data.inviteEmail?.configured === false+ ? "You'll need to configure RESEND_API_KEY to send magic link emails. Otherwise, share the link directly:"+ : "Email couldn't be sent. Share the invite link directly.";+ }+ if (this.email.trim() === body.email && this.role === body.role) this.inviteOpen = false;},true,);@@ -226,34 +239,22 @@ export class UsersView {<option value="member">Member</option><option value="org_admin">Admin</option></select>`,- )}${field(- "Expires",- html`<input- id="users-expires"- type="date"- min=${new Date().toISOString().slice(0, 10)}- .value=${this.expires}- @input=${(e: Event) => {- this.expires = (e.target as HTMLInputElement).value;- }}- />`,)}<button type="button" class="primary" ?disabled=${this.pending.has("invite")} @click=${() => this.invite()}>- ${inviteEmail.configured === false ? "Add user" : "Send invite"}+ Send invite</button></div>- <p class=${inviteEmail.configured === false ? "hint flag-warn" : "hint"}>- ${inviteEmail.configured === false ? (inviteEmail.problem || "Invitation emails are not configured") + ". Users can still be added, but need a configured sign-in method before they can log in." + (inviteEmail.signInUrl ? " Sign-in link to share: " + inviteEmail.signInUrl : "") : "Invitation emails go out through Resend — core needs RESEND_API_KEY and AUTH_EMAIL_FROM. Without them users can still be added, but need a configured sign-in method before they can log in."}- </p></div>`;const externalTable = table(["Email", "Role", "Expires", "Invited by", "Status", ""],externals.map((m: any) => [{ text: m.email, cls: "mono" },{ node: html`<span class="subline">${s.labelRole(m.role)}</span>` },- (m.status === "active" ? "Ends " : "Ended ") + new Date(m.expiresAt).toISOString().slice(0, 10) + " (UTC)",+ m.expiresAt === null+ ? "No expiration"+ : (m.status === "active" ? "Ends " : "Ended ") + new Date(m.expiresAt).toISOString().slice(0, 10) + " (UTC)",m.invitedBy || "-",{ badge: m.status === "active" ? "Active" : "Expired", kind: m.status === "active" ? "ok" : "warn" },- m.status === "active" || Date.now() - m.expiresAt >= 86400000+ m.status === "active" || (m.kind !== "teammate" && Date.now() - m.expiresAt >= 86400000)? {action: {label: m.status === "active" ? "Revoke" : "Remove",@@ -264,9 +265,7 @@ export class UsersView {}: "",]),- this.data.externalUsers?.length- ? "No external users match."- : "No external users. Use Invite external user to invite an outside collaborator.",+ this.data.externalUsers?.length ? "No invitations match." : "No invitations yet. Invite a teammate above.",);const roster = table(["Principal", "Role", "Last seen", "Sessions", "Turns", "Credentials", "Grants", "", ""],@@ -309,15 +308,12 @@ export class UsersView {<div class="list-root"><section class="card users-roster"><div class="head">- <h2>External users</h2>- <p>- Outside collaborators invited by email until an expiry date. Org members do not need an external invite.- </p>+ <h2>Users</h2><buttontype="button"- class="rowbtn"- title="Invite external user"- aria-label="Invite external user"+ class="primary"+ title="Invite teammate"+ aria-label="Invite teammate"aria-expanded=${String(this.inviteOpen)}@click=${() => {this.inviteOpen = !this.inviteOpen;@@ -325,11 +321,12 @@ export class UsersView {if (this.inviteOpen) this.root.querySelector<HTMLInputElement>("#users-email")?.focus();}}>- Invite external user+ Invite teammate</button></div><div class="body">- ${invite}${externalTable}+ ${invite}${roster}+ <p class=${"status " + this.tone} id="st-users" role="status">${this.message}</p><pid="st-external"class=${"status" + (this.externalTone ? " " + this.externalTone : "")}@@ -337,15 +334,53 @@ export class UsersView {>${this.externalMessage}</p>+ ${+ this.inviteLink+ ? html`<p class="flag-warn">${this.inviteWarning}</p>+ <button+ type="button"+ @click=${async () => {+ this.copyLabel = (await s.copyText(this.inviteLink)) ? "Copied" : "Copy failed";+ this.draw();+ }}+ >+ ${this.copyLabel}+ </button>`+ : ""+ }</div></section>+ ${card("Invitations", "Access granted by email. Revoking ends access to this instance.", externalTable)}${card(- "Users",- "Everyone who has used the agent — click a row for their activity, artifacts, and config.",- html`<p class=${"status" + (this.tone ? " " + this.tone : "")} id="st-users" role="status">- ${this.message}- </p>- ${roster}`,+ "Company access",+ "",+ table(+ ["Rule", "Value", "Purpose"],+ [+ [+ "Email domain allowlist",+ this.data.access?.emailDomain+ ? "@" + this.data.access.emailDomain+ : { node: html`<span class="subline">Not configured</span>` },+ {+ node: html`Controls who can create an account at+ <a href=${(inviteEmail.signInUrl || "/auth/login") + "?provider=primary"}+ >${inviteEmail.signInUrl || "/auth/login"}</a+ >.`,+ },+ ],+ [+ "Slack email allowlist",+ this.data.access?.slackAllowFrom?.length+ ? this.data.access.slackAllowFrom+ .map((rule: string) => (rule.includes("@") ? rule : "@" + rule))+ .join(", ")+ : { node: html`<span class="subline">Not configured</span>` },+ "Controls who the bot treats as an internal employee in shared Slack workspaces.",+ ],+ ],+ "",+ ),)}</div></div>`,diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.tsindex bd5bff708..8291825ec 100644--- a/plugins/portal/src/index.ts+++ b/plugins/portal/src/index.ts@@ -1,3 +1,4 @@+import { INVITE_LOGIN_SCRIPT, INVITE_LOGIN_SCRIPT_HASH } from "./invite-login.ts";import { reportBackendError } from "../../chassis/src/error-reporting.ts";import "./instrument.ts";import { provisionTrustedAdmin } from "./trusted-admin.ts";@@ -498,6 +499,7 @@ const CARD_STYLE = `<style>.note .who b{ color:var(--text); }.note p{ margin:8px 0 0; color:var(--muted); }.actions{ display:grid; gap:10px; }+ .actions form{ display:grid; margin:0; }.btn{ display:flex; align-items:center; justify-content:center; min-height:44px; padding:0 18px;text-decoration:none; font-weight:600; font-size:14px; border-radius:var(--radius-md); cursor:pointer;transition:opacity .12s ease, background .12s ease, color .12s ease; }@@ -539,12 +541,12 @@ ${CARD_STYLE}${o.icon}</div><h1 id="t">${escapeHtml(o.heading)}</h1>- <p class="msg">${escapeHtml(o.msg)}</p>+ ${o.msg ? `<p class="msg">${escapeHtml(o.msg)}</p>` : ""}${o.extra ?? ""}<div class="actions">${o.actions}</div>- <p class="help">${escapeHtml(o.help)}</p>+ ${o.help ? `<p class="help">${escapeHtml(o.help)}</p>` : ""}</section></main></body>@@ -986,6 +988,7 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>if (pathname === "/auth/login" && method === "GET") return authLogin(req, res, url);if (pathname === "/auth/callback" && method === "GET") return authCallback(req, res, url);if (pathname.startsWith("/auth/trusted/") && method === "GET") return trustedAuth(req, res, url);+ if (pathname === "/auth/invite") return inviteLogin(req, res);if (pathname === "/auth/admin-login") return adminLogin(req, res);if (pathname === "/auth/logout" && method === "POST") {if (!sameOriginRequest(req)) return json(res, 403, { error: "forbidden" });@@ -1319,6 +1322,61 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>});}+async function inviteLogin(req: IncomingMessage, res: ServerResponse): Promise<void> {+ if (!SESSION_SECRET || !CORE_SIGNING_SECRET) return json(res, 503, { error: "not_configured" });+ if (req.method === "GET")+ return sendHtml(+ res,+ 200,+ cardPage({+ title: "Accept invitation",+ heading: "You're invited",+ icon: LOCK_ICON,+ msg: "",+ extra: '<p id="invite-status"></p><noscript>JavaScript is required to open this invitation.</noscript>',+ actions: `<form method="post" action="/auth/invite"><input id="invite-token" name="token" type="hidden"><button id="invite-confirm" class="btn primary" type="submit" disabled>Accept invitation</button></form><script>${INVITE_LOGIN_SCRIPT}</script>`,+ help: "",+ }),+ `${PAGE_CSP}; script-src '${INVITE_LOGIN_SCRIPT_HASH}'`,+ );+ if (req.method !== "POST") return json(res, 405, { error: "method_not_allowed" });+ if (!sameOriginRequest(req)) return json(res, 403, { error: "forbidden" });+ let token: string;+ try {+ token = new URLSearchParams(await readBody(req, 8192)).get("token") ?? "";+ } catch (error) {+ if (error instanceof PayloadTooLargeError) return json(res, 413, { error: "payload_too_large" });+ throw error;+ }+ if (!token || token.length > 4096) return sendHtml(res, 400, signInErrorHtml("This invitation is invalid."));+ const path = withSourceAuthNonce("/v1/auth/invitations/redeem", CORE_SIGNING_SECRET);+ const body = JSON.stringify({ token });+ try {+ const r = await fetch(`${CORE}${path}`, {+ method: "POST",+ headers: signedHeaders(CORE_SIGNING_SECRET, "POST", path, body),+ body,+ signal: AbortSignal.timeout(10_000),+ });+ if (!r.ok)+ return sendHtml(+ res,+ r.status >= 500 ? 503 : 400,+ signInErrorHtml(+ r.status >= 500+ ? "Sign-in is temporarily unavailable. Please try again."+ : "This invitation is expired, revoked, or already used. Ask your administrator for a new one.",+ ),+ );+ const data = (await r.json()) as { email: string };+ setAuthenticatedSession(res, data.email);+ res.writeHead(303, { location: "/", "cache-control": "no-store" });+ res.end();+ } catch {+ return sendHtml(res, 503, signInErrorHtml("Sign-in is temporarily unavailable. Please try again."));+ }+}+async function adminLogin(req: IncomingMessage, res: ServerResponse): Promise<void> {if (!SESSION_SECRET || SESSION_SECRET.trim().length < 32 || !CORE_SIGNING_SECRET) {return json(res, 503, { error: "not_configured" });diff --git a/plugins/portal/src/invite-login.ts b/plugins/portal/src/invite-login.tsnew file mode 100644index 000000000..bfd14782f--- /dev/null+++ b/plugins/portal/src/invite-login.ts@@ -0,0 +1,19 @@+import { createHash } from "node:crypto";++export const INVITE_LOGIN_SCRIPT = `(function () {+ var token = new URLSearchParams(location.hash.slice(1)).get("token");+ history.replaceState(null, "", location.pathname);+ if (token && token.length <= 4096) {+ try {+ var payload = token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");+ var claims = JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(payload), function(c) { return c.charCodeAt(0); })));+ if (typeof claims.email !== "string") throw new Error();+ document.getElementById("invite-status").textContent = "Sign in as " + claims.email;+ } catch (e) { return; }+ document.getElementById("invite-token").value = token;+ document.getElementById("invite-confirm").disabled = false;+ } else {+ document.getElementById("invite-status").textContent = "This invitation is missing or invalid. Ask your administrator for a new one.";+ }+})();`;+export const INVITE_LOGIN_SCRIPT_HASH = `sha256-${createHash("sha256").update(INVITE_LOGIN_SCRIPT).digest("base64")}`;diff --git a/plugins/portal/test/invite-routes.test.ts b/plugins/portal/test/invite-routes.test.tsnew file mode 100644index 000000000..031cd0a00--- /dev/null+++ b/plugins/portal/test/invite-routes.test.ts@@ -0,0 +1,166 @@+import test from "node:test";+import assert from "node:assert/strict";+import { createServer } from "node:http";+import type { AddressInfo } from "node:net";+import { runInNewContext } from "node:vm";+import { canonicalPayload, signRequest } from "../../chassis/src/source-auth-sign.ts";+import { INVITE_LOGIN_SCRIPT, INVITE_LOGIN_SCRIPT_HASH } from "../src/invite-login.ts";+import { deriveKey, openSession } from "../src/session.ts";++const coreSecret = "invite-route-core-secret";+const sessionSecret = "invite-route-session-secret";+const origin = "http://127.0.0.1:19997";+const requests: { path: string; body: string; signature: string | undefined; timestamp: string | undefined }[] = [];+const upstream = createServer((req, res) => {+ void (async () => {+ let body = "";+ for await (const chunk of req) body += chunk;+ if (new URL(req.url!, "http://core.test").pathname !== "/v1/auth/invitations/redeem") {+ res.end("{}");+ return;+ }+ requests.push({+ path: req.url!,+ body,+ signature: req.headers["x-signature"] as string | undefined,+ timestamp: req.headers["x-timestamp"] as string | undefined,+ });+ const { token } = JSON.parse(body);+ if (token === "disconnected") return req.socket.destroy();+ const statusByToken: Record<string, number> = { valid: 200, revoked: 403, unavailable: 503 };+ res.statusCode = statusByToken[token] ?? 400;+ res.setHeader("content-type", "application/json");+ res.end(JSON.stringify(token === "valid" ? { email: "[email protected]" } : { error: token }));+ })().catch((error) => {+ res.statusCode = 500;+ res.end(String(error));+ });+});+await new Promise<void>((resolve) => upstream.listen(0, "127.0.0.1", resolve));+const upstreamUrl = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`;+Object.assign(process.env, {+ NODE_ENV: "test",+ PORTAL_PUBLIC_URL: origin,+ PORTAL_SESSION_SECRET: sessionSecret,+ CORE_SIGNING_SECRET: coreSecret,+ CORE_ORG_ID: "invite-test",+ CORE_API_URL: upstreamUrl,+ WEB_UI_UPSTREAM: upstreamUrl,+ ADMIN_UPSTREAM: upstreamUrl,+ PORTAL_LOCAL_AUTH_BYPASS: "0",+ PORTAL_PLAYGROUND: "0",+});+const { server } = await import("../src/index.ts");+await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+test.after(() => {+ server.close();+ upstream.close();+});++function redeem(token: string, requestOrigin: string | null = origin) {+ return fetch(`${base}/auth/invite`, {+ method: "POST",+ redirect: "manual",+ headers: {+ "content-type": "application/x-www-form-urlencoded",+ ...(requestOrigin ? { origin: requestOrigin } : {}),+ },+ body: new URLSearchParams({ token }),+ });+}++test("GET shows an explicit confirmation without redeeming query-string tokens", async () => {+ const before = requests.length;+ const response = await fetch(`${base}/auth/invite?token=valid`);+ assert.equal(response.status, 200);+ assert.equal(response.headers.get("set-cookie"), null);+ assert.ok(response.headers.get("content-security-policy")?.includes(`script-src '${INVITE_LOGIN_SCRIPT_HASH}'`));+ const html = await response.text();+ assert.match(html, /action="\/auth\/invite"/);+ assert.match(html, /id="invite-confirm"[^>]*disabled/);+ assert.ok(html.includes(INVITE_LOGIN_SCRIPT));+ assert.equal(requests.length, before);+});++test("fragment script removes the token from browser history and waits for confirmation", () => {+ const token = `header.${Buffer.from(JSON.stringify({ email: "[email protected]" })).toString("base64url")}.signature`;+ const elements: Record<string, { textContent?: string; value?: string; disabled?: boolean }> = {+ "invite-status": {},+ "invite-token": {},+ "invite-confirm": { disabled: true },+ };+ const replacements: unknown[][] = [];+ runInNewContext(INVITE_LOGIN_SCRIPT, {+ location: { hash: `#token=${token}`, pathname: "/auth/invite" },+ history: { replaceState: (...args: unknown[]) => replacements.push(args) },+ document: { getElementById: (id: string) => elements[id] },+ URLSearchParams,+ TextDecoder,+ Uint8Array,+ atob,+ });+ assert.deepEqual(replacements, [[null, "", "/auth/invite"]]);+ assert.equal(elements["invite-status"]!.textContent, "Sign in as [email protected]");+ assert.equal(elements["invite-token"]!.value, token);+ assert.equal(elements["invite-confirm"]!.disabled, false);+});++test("redemption signs the core request and issues a session for the verified teammate", async () => {+ const response = await redeem("valid");+ assert.equal(response.status, 303);+ assert.equal(response.headers.get("location"), "/");+ const request = requests.at(-1)!;+ assert.equal(new URL(request.path, upstreamUrl).pathname, "/v1/auth/invitations/redeem");+ assert.equal(request.body, JSON.stringify({ token: "valid" }));+ assert.equal(+ request.signature,+ signRequest(coreSecret, Number(request.timestamp), canonicalPayload("POST", request.path, request.body)),+ );+ const cookies = response.headers.getSetCookie();+ const sessionCookie = cookies.find((cookie) => cookie.startsWith("portal_session="))!;+ const token = sessionCookie.split(";")[0]!.slice("portal_session=".length);+ const session = openSession(token, deriveKey(sessionSecret, "portal.session.v1"), Date.now(), "invite-test");+ assert.equal(session?.sub, "[email protected]");+ assert.ok(session?.auth);+ assert.match(sessionCookie, /HttpOnly/);+ assert.ok(cookies.some((cookie) => /^portal_impersonate=;.*Max-Age=0/.test(cookie)));+});++test("cross-origin and missing-origin redemption never reaches core", async () => {+ const before = requests.length;+ for (const requestOrigin of ["https://attacker.example", null]) {+ const response = await redeem("valid", requestOrigin);+ assert.equal(response.status, 403);+ assert.equal(response.headers.get("set-cookie"), null);+ }+ assert.equal(requests.length, before);+});++test("missing and oversized tokens never reach core", async () => {+ const before = requests.length;+ for (const token of ["", "x".repeat(4097)]) {+ const response = await redeem(token);+ assert.equal(response.status, 400);+ assert.equal(response.headers.get("set-cookie"), null);+ }+ assert.equal(requests.length, before);+});++test("invalid, revoked, and unavailable invitations fail without creating sessions", async () => {+ for (const [token, status] of [+ ["invalid", 400],+ ["revoked", 400],+ ["unavailable", 503],+ ["disconnected", 503],+ ] as const) {+ const response = await redeem(token);+ assert.equal(response.status, status);+ assert.equal(response.headers.get("set-cookie"), null);+ assert.equal(response.headers.get("location"), null);+ assert.match(+ await response.text(),+ status === 503 ? /temporarily unavailable/ : /expired, revoked, or already used/,+ );+ }+});diff --git a/scripts/dev/supervisor/main.ts b/scripts/dev/supervisor/main.tsindex 66c7eff1d..441d9c4d6 100644--- a/scripts/dev/supervisor/main.ts+++ b/scripts/dev/supervisor/main.ts@@ -399,7 +399,11 @@ async function assembleAndPrepare(spec: BootSpec): Promise<SpecInputs> {if (!portalDevPrincipal && adminGrantsSeed) portalDevPrincipal = adminGrantsSeed.split(":")[0] ?? "";if (!portalDevPrincipal && durableAdminPrincipal) portalDevPrincipal = durableAdminPrincipal;if (!portalDevPrincipal) portalDevPrincipal = assembled.env.USER || "dev-admin";- log(`portal auth: localhost bypass signs in as ${portalDevPrincipal}`);+ log(+ assembled.env.PORTAL_LOCAL_AUTH_BYPASS === "0"+ ? "portal auth: localhost bypass disabled"+ : `portal auth: localhost bypass signs in as ${portalDevPrincipal}`,+ );const tokens = slackOn(spec) ? slotTokens(slot, store) : null;diff --git a/scripts/dev/supervisor/specs.ts b/scripts/dev/supervisor/specs.tsindex d974f0ca7..67e2fa06c 100644--- a/scripts/dev/supervisor/specs.ts+++ b/scripts/dev/supervisor/specs.ts@@ -94,7 +94,7 @@ export function buildChildSpecs(i: SpecInputs): ChildSpec[] {ADMIN_UPSTREAM: `http://localhost:${i.ports.web}/admin`,PORTAL_SESSION_SECRET: i.portalSessionSecret,NODE_ENV: "development",- PORTAL_LOCAL_AUTH_BYPASS: "1",+ PORTAL_LOCAL_AUTH_BYPASS: i.baseEnv.PORTAL_LOCAL_AUTH_BYPASS ?? "1",PORTAL_DEV_PRINCIPAL: i.portalDevPrincipal,},port: i.ports.portal,diff --git a/src/admin/invite-email.ts b/src/admin/invite-email.tsindex 42caf8c83..2da39663b 100644--- a/src/admin/invite-email.ts+++ b/src/admin/invite-email.ts@@ -38,18 +38,25 @@ export function renderInviteEmail(a: {brandName: string;invitedBy: string;signInUrl: string;- expiresAt: number;+ expiresAt: number | null;+ magicLink?: boolean;}): { subject: string; text: string; html: string } {- const ends = new Date(a.expiresAt).toUTCString();+ const access =+ a.expiresAt === null+ ? "Your access has no expiration date."+ : `Your access ends on ${new Date(a.expiresAt).toUTCString()}.`;+ const instruction = a.magicLink+ ? "Use this single-use link to sign in. The link is valid for 24 hours."+ : `Sign in using this email address (${a.to}).`;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.`,+ `${instruction} ${a.signInUrl}`,"",- `Your access ends on ${ends}.`,+ access,].join("\n");const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="color-scheme" content="light"></head>@@ -59,11 +66,11 @@ export function renderInviteEmail(a: {<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;color:#525252">${escapeHtml(a.invitedBy)} invited you to ${escapeHtml(a.brandName)}. ${escapeHtml(instruction)}</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>+<p style="margin:0;color:#737373;font-size:13px">${escapeHtml(access)}</p></td></tr></table></td></tr></table></body></html>`;diff --git a/src/api/deps.ts b/src/api/deps.tsindex 5c884d600..28eea6d36 100644--- a/src/api/deps.ts+++ b/src/api/deps.ts@@ -135,6 +135,7 @@ export interface ServerDeps {inviteMailer?: InviteMailer;emailAuthPrincipals?: readonly string[];emailAuthDomain?: string;+ slackAllowFrom?: readonly string[];rateLimiter?: RateLimiter;sessions?: SessionStore;screenSecurity?: SecurityScreenProbe;diff --git a/src/api/routes/admin.ts b/src/api/routes/admin.tsindex cfcc5eab1..c9ef9c34c 100644--- a/src/api/routes/admin.ts+++ b/src/api/routes/admin.ts@@ -20,6 +20,7 @@ import {createAdminGrant,getUserDetail,inviteExternalUser,+ inviteTeammate,listKeychainStatus,listUsers,resetUserToBrandNew,@@ -154,6 +155,7 @@ const routes: ReadonlyArray<Route<ApiCtx>> = [{ method: "DELETE", path: "/v1/admin/principal-links/:principalId", auth: "either", handle: deletePrincipalLink },{ 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/users/invite", auth: "either", handle: inviteTeammate },{ 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 },diff --git a/src/api/routes/admin/users.ts b/src/api/routes/admin/users.tsindex 43bdbf2fc..6cfa0fe2c 100644--- a/src/api/routes/admin/users.ts+++ b/src/api/routes/admin/users.ts@@ -1,3 +1,5 @@+import { randomUUID } from "node:crypto";+import { mintSignedPayload } from "../../../auth/signed-token.ts";import { scopeId as makeScopeId } from "../../../types.ts";import { adminStatusFromGrants, AdminError } from "../../../admin/admin-service.ts";import { personKey, samePerson } from "../../../directory/person.ts";@@ -36,14 +38,38 @@ export async function listUsers(ctx: ApiCtx): Promise<void> {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);+ .sort(+ (a, b) =>+ Number(b.status === "active") - Number(a.status === "active") ||+ (a.expiresAt ?? Infinity) - (b.expiresAt ?? Infinity),+ );+ for (const member of externalUsers.filter((m) => m.kind === "teammate" && m.status === "active")) {+ if (!users.some((u) => samePerson(u.principalId, member.email)))+ users.push({+ principalId: member.email,+ sessionCount: 0,+ turnCount: 0,+ lastSeenAt: null,+ admin: adminStatusFromGrants(grants, member.email),+ });+ }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 });+ return sendJson(res, 200, {+ scopeId: scope,+ users,+ grants,+ externalUsers,+ inviteEmail,+ access: {+ emailDomain: deps.emailAuthDomain ?? null,+ slackAllowFrom: deps.slackAllowFrom ?? null,+ },+ });}function signInUrlOf(deps: ApiCtx["deps"]): string | undefined {@@ -70,11 +96,21 @@ async function orgMember(ctx: ApiCtx, email: string, includeSessions: boolean):}export async function inviteExternalUser(ctx: ApiCtx): Promise<void> {+ return inviteUser(ctx, false);+}++export async function inviteTeammate(ctx: ApiCtx): Promise<void> {+ return inviteUser(ctx, true);+}++async function inviteUser(ctx: ApiCtx, teammate: boolean): 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" });+ if (teammate && ctx.capability)+ return sendJson(res, 403, { error: "forbidden", message: "Teammate invitations must be made in Admin." });const bad = (message: string) => sendJson(res, 400, { error: "bad_request", message });const b = isObj(body) ? body : {};const email = String(b.email ?? "")@@ -85,22 +121,34 @@ export async function inviteExternalUser(ctx: ApiCtx): Promise<void> {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);+ if (teammate && (!deps.portalUrl || !deps.portalIdentitySecret || !deps.replayDedupe?.durable))+ return sendJson(res, 503, {+ error: "not_configured",+ message: "Invitation sign-in requires a portal and durable token storage.",+ });const now = Date.now();- if (expiry.value === undefined || expiry.value <= now) return bad("expiresAt is required and must be in the future");+ if ((!teammate && expiry.value === undefined) || (expiry.value !== undefined && expiry.value <= now))+ return bad("expiresAt is required and must be in the future");await deps.identity.refresh(true);+ if (teammate && deps.identity.deactivationSource(email) === "manual")+ return sendJson(res, 409, {+ error: "conflict",+ message: "This account is manually deactivated. Reactivate it before inviting them.",+ });const existing = deps.identity.externalMember(email);+ if (!teammate && existing?.kind === "teammate") return bad("Manage this teammate in Users.");const holdsGrant = adminStatusFromGrants(await deps.admin!.listGrants(), email).isAdmin;const ownsGrant = existing?.role === "org_admin";- if ((!existing && holdsGrant) || (await orgMember(ctx, email, !existing)))+ if (!teammate && ((!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)+ if (!teammate && 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";+ else if (!teammate && role === "member" && holdsGrant) grantChange = "grant.revoke";try {if (grantChange === "grant.create")await deps.admin!.createGrant(actor, { principalId: email, role: "org_admin", scopeId: scope });@@ -114,23 +162,41 @@ export async function inviteExternalUser(ctx: ApiCtx): Promise<void> {const readmitted = existing !== undefined && !externalMemberActive(existing, now);const member: ExternalMember = {email,- role,- expiresAt: expiry.value,+ role: teammate && holdsGrant ? "org_admin" : role,+ expiresAt: expiry.value ?? null,+ ...(teammate ? { kind: "teammate" as const, inviteId: randomUUID() } : {}),invitedBy: existing?.invitedBy ?? actor.id,createdAt: existing?.createdAt ?? now,updatedAt: now,};await deps.identity.putExternalMember(member);+ const action = created || readmitted ? "external_user.invite" : "external_user.update";audit(deps, {principalId: actor.id,- action: created || readmitted ? "external_user.invite" : "external_user.update",+ action: teammate ? "user.invite" : action,resource: email,scopeLabel: scope,});- const signInUrl = signInUrlOf(deps);+ const signInUrl = teammate+ ? `${deps.portalUrl!.replace(/\/+$/, "")}/auth/invite#token=${encodeURIComponent(+ await mintSignedPayload(+ {+ purpose: "teammate-invite",+ inviteId: member.inviteId,+ email,+ org: scope,+ aud: deps.portalUrl!.replace(/\/+$/, ""),+ iat: now,+ exp: now + 24 * 60 * 60 * 1000,+ jti: randomUUID(),+ },+ deps.portalIdentitySecret!,+ ),+ )}`+ : signInUrlOf(deps);let emailSent = false;let emailProblem: string | undefined;- if (created || readmitted || b.resendInvite === true) {+ if (teammate || 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";@@ -145,6 +211,7 @@ export async function inviteExternalUser(ctx: ApiCtx): Promise<void> {invitedBy: actor.id,signInUrl,expiresAt: member.expiresAt,+ magicLink: teammate,}),});emailSent = true;@@ -159,7 +226,7 @@ export async function inviteExternalUser(ctx: ApiCtx): Promise<void> {created,emailSent,...(emailProblem ? { emailProblem } : {}),- ...(signInUrl ? { signInUrl } : {}),+ ...(!emailSent && signInUrl ? { signInUrl } : {}),});}@@ -174,7 +241,7 @@ export async function revokeExternalUser(ctx: ApiCtx): Promise<void> {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)) {+ if (ctx.capability && (existing.kind === "teammate" || 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 });@@ -195,14 +262,15 @@ export async function revokeExternalUser(ctx: ApiCtx): Promise<void> {const tombstone: ExternalMember = {...existing,role: "member",- expiresAt: Math.min(existing.expiresAt, now),+ expiresAt: Math.min(existing.expiresAt ?? now, 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 });+ if (existing.kind === "teammate" || 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 });diff --git a/src/api/routes/auth-broker.ts b/src/api/routes/auth-broker.tsindex aeb486c21..78020a80f 100644--- a/src/api/routes/auth-broker.ts+++ b/src/api/routes/auth-broker.ts@@ -147,7 +147,55 @@ async function trustedAdmin(ctx: ApiCtx): Promise<void> {}}+async function redeemInvitation(ctx: ApiCtx): Promise<void> {+ const { deps, res, body } = ctx;+ if (!deps.portalIdentitySecret || !deps.replayDedupe?.durable || !deps.identity || !deps.portalUrl)+ return sendJson(res, 503, { error: "not_configured" });+ const token = isObj(body) && typeof body.token === "string" ? body.token : "";+ const claims = token.length <= 4096 ? await verifySignedPayload(token, deps.portalIdentitySecret) : null;+ const now = Date.now();+ if (+ !isObj(claims) ||+ claims.purpose !== "teammate-invite" ||+ claims.org !== orgScope(deps) ||+ claims.aud !== deps.portalUrl.replace(/\/+$/, "") ||+ typeof claims.email !== "string" ||+ typeof claims.iat !== "number" ||+ typeof claims.exp !== "number" ||+ !Number.isSafeInteger(claims.iat) ||+ !Number.isSafeInteger(claims.exp) ||+ claims.iat > now + 5000 ||+ claims.exp <= now ||+ claims.exp <= claims.iat ||+ claims.exp - claims.iat > 86400000 ||+ typeof claims.jti !== "string" ||+ !/^[a-f0-9-]{36}$/.test(claims.jti)+ )+ return sendJson(res, 400, { error: "invalid_invitation" });+ await deps.identity.refresh(true);+ const member = deps.identity.externalMember(claims.email);+ if (+ !member ||+ member.kind !== "teammate" ||+ !member.inviteId ||+ member.inviteId !== claims.inviteId ||+ !externalMemberActive(member) ||+ deps.identity.classify(claims.email).type !== "internal"+ )+ return sendJson(res, 403, { error: "invitation_revoked" });+ if (!(await deps.replayDedupe.claim(`teammate-invite:${claims.jti}`, claims.exp)))+ return sendJson(res, 400, { error: "invitation_used" });+ audit(deps, {+ principalId: claims.email,+ action: "user.invite.redeem",+ resource: claims.email,+ scopeLabel: orgScope(deps),+ });+ return sendJson(res, 200, { email: claims.email });+}+export const authBrokerRoutes: ReadonlyArray<Route<ApiCtx>> = [+ { method: "POST", path: "/v1/auth/invitations/redeem", auth: "source", handle: redeemInvitation },{ method: "POST", path: "/v1/auth/trusted/admin", auth: "source", handle: trustedAdmin },{ method: "POST", path: "/v1/auth/broker/sessions", auth: "source", handle: brokerSession },{ method: "POST", path: "/v1/auth/broker/sessions/use", auth: "source", handle: brokerSession },diff --git a/src/api/user-scoped-routes.ts b/src/api/user-scoped-routes.tsindex 7b814442a..b3156bfd8 100644--- a/src/api/user-scoped-routes.ts+++ b/src/api/user-scoped-routes.ts@@ -143,6 +143,7 @@ const SYSTEM: Rule[] = [pat("POST", "/v1/egress-audit"),pat("POST", "/v1/auth/broker/claim"),pat("POST", "/v1/auth/trusted/admin"),+ pat("POST", "/v1/auth/invitations/redeem"),pat("POST", "/v1/auth/broker/sessions"),pat("POST", "/v1/auth/broker/sessions/use"),pat("PUT", "/v1/deployment-layer"),diff --git a/src/identity/external-members.ts b/src/identity/external-members.tsindex fcf46d3ca..2063271a8 100644--- a/src/identity/external-members.ts+++ b/src/identity/external-members.ts@@ -3,14 +3,16 @@ type ExternalRole = "member" | "org_admin";export interface ExternalMember {email: string;role: ExternalRole;- expiresAt: number;+ expiresAt: number | null;+ kind?: "teammate";+ inviteId?: string;invitedBy: string;createdAt: number;updatedAt: number;}export function externalMemberActive(m: ExternalMember, now = Date.now()): boolean {- return m.expiresAt > now;+ return (m.kind === "teammate" && m.expiresAt === null) || (typeof m.expiresAt === "number" && m.expiresAt > now);}export function validEmail(value: string): boolean {diff --git a/src/identity/identity-service.ts b/src/identity/identity-service.tsindex 9633d96c1..1dbad9be6 100644--- a/src/identity/identity-service.ts+++ b/src/identity/identity-service.ts@@ -25,6 +25,7 @@ export interface IdentityService extends IdentityProvider {isInternal(p: Principal): boolean;audienceIsAllInternal(audience: Principal[]): boolean;deactivate(externalId: string, source?: DeactivationSource): Promise<void>;+ deactivationSource(externalId: string): DeactivationSource | undefined;reactivate(externalId: string): Promise<void>;recordDirectorySync(removedIds: string[], presentIds: string[]): Promise<DirectorySyncOutcome>;listExternalMembers(): Promise<ExternalMember[]>;@@ -128,6 +129,9 @@ export function createIdentityService(return {classify,deactivate,+ deactivationSource(externalId: string): DeactivationSource | undefined {+ return deactivated.get(personKey(externalId))?.source;+ },reactivate,async recordDirectorySync(removedIds: string[], presentIds: string[]): Promise<DirectorySyncOutcome> {const outcome: DirectorySyncOutcome = { deactivated: [], reactivated: [] };diff --git a/src/wiring.ts b/src/wiring.tsindex 8e9be8275..3f2d68900 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -2786,6 +2786,7 @@ export function serverDeps(admin: built.admin,...(config.emailAuthPrincipals ? { emailAuthPrincipals: config.emailAuthPrincipals } : {}),...(config.emailAuthDomain ? { emailAuthDomain: config.emailAuthDomain } : {}),+ ...(config.slack ? { slackAllowFrom: config.slack.allowFrom ?? [] } : {}),...(config.resendApiKey && config.emailFrom? { inviteMailer: createResendMailer(config.resendApiKey, config.emailFrom) }: {}),diff --git a/test/admin-external-users.test.ts b/test/admin-external-users.test.tsindex 68bf931f5..29f3833f1 100644--- a/test/admin-external-users.test.ts+++ b/test/admin-external-users.test.ts@@ -1,3 +1,6 @@+import { randomUUID } from "node:crypto";+import { signedHeaders, withSourceAuthNonce } from "../plugins/chassis/src/core-client.ts";+import { mintSignedPayload, verifySignedPayload } from "../src/auth/signed-token.ts";import "./support/auto-fake-sprites.ts";import { test } from "node:test";@@ -55,6 +58,8 @@ function start(directory: built.directory,config: built.config,portalUrl: PORTAL,+ portalIdentitySecret: SECRET,+ replayDedupe: { durable: true, claim: built.replayDedupe!.claim.bind(built.replayDedupe!) },brandingDefault: { selfLabel: "Acme Bot" },...(opts.mailer ? { inviteMailer: opts.mailer } : {}),...(opts.emailAuthDomain ? { emailAuthDomain: opts.emailAuthDomain } : {}),@@ -162,7 +167,7 @@ test("role org_admin grants admin; member revokes it; DELETE drops the grant and);const tomb = s.built.identity.externalMember("[email protected]");assert.equal(tomb?.role, "member");- assert.ok(tomb!.expiresAt <= Date.now());+ assert.ok(typeof tomb?.expiresAt === "number" && tomb.expiresAt <= Date.now());assert.deepEqual((await roster(s.base)).externalUsers.map((m: any) => [m.email, m.status]),[["[email protected]", "expired"]],@@ -563,3 +568,197 @@ test("directory sync never deactivates an external member; manual deactivation sawait s.close();}});++const inviteTeammate = (base: string, body: unknown, headers: Record<string, string> = { "x-admin-actor": ALICE }) =>+ fetch(`${base}/v1/admin/users/invite`, {+ method: "POST",+ headers: { ...headers, "content-type": "application/json" },+ body: JSON.stringify(body),+ });++test("teammates receive permanent access and appear before their first session", async () => {+ const { sent, mailer } = stubMailer();+ const s = start({ mailer, emailAuthDomain: "corp.example" });+ try {+ const r = await inviteTeammate(s.base, { email: " [email protected] " });+ assert.equal(r.status, 200);+ const d: any = await r.json();+ assert.equal(d.member.expiresAt, null);+ assert.equal(d.member.kind, "teammate");+ assert.equal(d.emailSent, true);+ assert.ok(sent[0]);+ assert.match(sent[0].text, /no expiration/);+ assert.doesNotMatch(sent[0].html, /Invalid Date/);+ const list = await roster(s.base);+ assert.ok(list.users.some((u: any) => u.principalId === "[email protected]" && u.sessionCount === 0));+ assert.equal(list.externalUsers[0].status, "active");+ assert.equal(await coreEmailAllowed(s.base, undefined, "[email protected]", "test"), true);+ assert.equal((await inviteTeammate(s.base, { email: "[email protected]" })).status, 200);+ assert.equal(sent.length, 2);+ assert.equal((await roster(s.base)).externalUsers.length, 1);+ assert.equal((await revoke(s.base, "[email protected]")).status, 200);+ assert.equal(await coreEmailAllowed(s.base, undefined, "[email protected]", "test"), false);+ assert.equal(s.built.identity.classify("[email protected]").type, "guest");+ } finally {+ await s.close();+ }+});++test("teammate invitations validate expiry, require admin, and do not demote existing admins", async () => {+ const s = start();+ try {+ assert.equal((await inviteTeammate(s.base, { email: "[email protected]" }, { "x-admin-actor": NOBODY })).status, 403);+ assert.equal((await inviteTeammate(s.base, { email: "invalid" })).status, 400);+ assert.equal(+ (await inviteTeammate(s.base, { email: "[email protected]", expiresAt: Date.now() - DAY_MS })).status,+ 400,+ );+ const first = await inviteTeammate(s.base, { email: "[email protected]", role: "org_admin" });+ assert.equal(first.status, 200);+ const again = await inviteTeammate(s.base, { email: "[email protected]", role: "member" });+ assert.equal(again.status, 200);+ assert.equal(((await again.json()) as any).member.role, "org_admin");+ assert.equal(adminStatusFromGrants(await s.built.admin.listGrants(), "[email protected]").isAdmin, true);+ assert.equal((await invite(s.base, { email: "[email protected]", expiresAt: Date.now() + DAY_MS })).status, 400);+ } finally {+ await s.close();+ }+});++test("agent capabilities cannot create permanent teammate access", async () => {+ const s = start({ signed: true });+ try {+ const r = await inviteTeammate(+ s.base,+ { email: "[email protected]" },+ { "x-agent-capability": await capFor("admin-alice") },+ );+ assert.equal(r.status, 403);+ assert.equal(s.built.identity.externalMember("[email protected]"), undefined);+ } finally {+ await s.close();+ }+});++test("invitation links work without email delivery and are single use, scoped, and revocable", async () => {+ const s = start();+ const redeem = (token: string) =>+ fetch(`${s.base}/v1/auth/invitations/redeem`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ token }),+ });+ const issue = async () => {+ const r = await inviteTeammate(s.base, { email: "[email protected]" });+ assert.equal(r.status, 200);+ const data: any = await r.json();+ assert.equal(data.emailSent, false);+ const url = new URL(data.signInUrl);+ assert.equal(url.pathname, "/auth/invite");+ return new URLSearchParams(url.hash.slice(1)).get("token")!;+ };+ try {+ const token = await issue();+ const claims: any = await verifySignedPayload(token, SECRET);+ assert.equal((await redeem(token + "tampered")).status, 400);+ assert.equal((await redeem(await mintSignedPayload({ ...claims, exp: Date.now() - 1 }, SECRET))).status, 400);+ assert.equal((await redeem(await mintSignedPayload({ ...claims, org: "org:other" }, SECRET))).status, 400);+ assert.equal(+ (await redeem(await mintSignedPayload({ ...claims, aud: "https://elsewhere.example" }, SECRET))).status,+ 400,+ );+ const results = await Promise.all([redeem(token), redeem(token)]);+ assert.deepEqual(results.map((r) => r.status).sort(), [200, 400]);+ const accepted: any = await results.find((r) => r.status === 200)!.json();+ assert.equal(accepted.email, "[email protected]");+ const revoked = await issue();+ assert.equal((await revoke(s.base, "[email protected]")).status, 200);+ assert.equal((await redeem(revoked)).status, 403);+ await issue();+ assert.equal((await redeem(revoked)).status, 403);+ } finally {+ await s.close();+ }+});++test("invitation redemption requires source authentication before consuming a valid invitation", async () => {+ const s = start({ signed: true });+ try {+ const now = Date.now();+ const inviteId = randomUUID();+ const email = "[email protected]";+ await s.built.identity.putExternalMember({+ email,+ role: "member",+ expiresAt: null,+ kind: "teammate",+ inviteId,+ invitedBy: "admin-alice",+ createdAt: now,+ updatedAt: now,+ });+ const token = await mintSignedPayload(+ {+ purpose: "teammate-invite",+ org: ORG,+ aud: PORTAL,+ email,+ inviteId,+ iat: now,+ exp: now + DAY_MS,+ jti: randomUUID(),+ },+ SECRET,+ );+ const body = JSON.stringify({ token });+ const path = withSourceAuthNonce("/v1/auth/invitations/redeem", SECRET);+ const unsigned = await fetch(`${s.base}${path}`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body,+ });+ assert.equal(unsigned.status, 401);+ const signed = await fetch(`${s.base}${path}`, {+ method: "POST",+ headers: signedHeaders(SECRET, "POST", path, body),+ body,+ });+ assert.equal(signed.status, 200);+ assert.deepEqual(await signed.json(), { email });+ const reusedPath = withSourceAuthNonce("/v1/auth/invitations/redeem", SECRET);+ const reused = await fetch(`${s.base}${reusedPath}`, {+ method: "POST",+ headers: signedHeaders(SECRET, "POST", reusedPath, body),+ body,+ });+ assert.equal(reused.status, 400);+ assert.deepEqual(await reused.json(), { error: "invitation_used" });+ } finally {+ await s.close();+ }+});++test("teammate invites reject manual deactivation before changing access or sending mail", async () => {+ const { sent, mailer } = stubMailer();+ const s = start({ mailer });+ const email = "[email protected]";+ try {+ await s.built.identity.deactivate(email);+ const denied = await inviteTeammate(s.base, { email, role: "org_admin" });+ assert.equal(denied.status, 409);+ assert.match(((await denied.json()) as any).message, /Reactivate/);+ assert.equal(s.built.identity.externalMember(email), undefined);+ assert.equal(adminStatusFromGrants(await s.built.admin.listGrants(), email).isAdmin, false);+ assert.equal(sent.length, 0);+ assert.equal(s.built.identity.classify(email).type, "guest");++ await s.built.identity.reactivate(email);+ assert.equal((await inviteTeammate(s.base, { email })).status, 200);+ assert.equal((await revoke(s.base, email)).status, 200);+ assert.equal((await inviteTeammate(s.base, { email })).status, 200);+ assert.equal(s.built.identity.classify(email).type, "internal");+ assert.equal(sent.length, 2);+ } finally {+ await s.close();+ }+});diff --git a/test/dev-cli-lib.test.ts b/test/dev-cli-lib.test.tsindex 530173333..c7b05c42a 100644--- a/test/dev-cli-lib.test.ts+++ b/test/dev-cli-lib.test.ts@@ -440,6 +440,9 @@ test("supervised children share the selected dev org", () => {assert.equal(spec.env.CODEX_HOME, undefined);}for (const spec of specs) assert.equal(spec.env.CORE_ORG_ID, "beta");+ assert.equal(specs.find((spec) => spec.name === "portal")!.env.PORTAL_LOCAL_AUTH_BYPASS, "1");+ inputs.baseEnv.PORTAL_LOCAL_AUTH_BYPASS = "0";+ assert.equal(buildChildSpecs(inputs).find((spec) => spec.name === "portal")!.env.PORTAL_LOCAL_AUTH_BYPASS, "0");inputs.baseEnv = {};assert.equal(buildChildSpecs(inputs).find((spec) => spec.name === "core")!.env.ORG_ID, "acme");});