@app-vitals/agent-admin 1.107.5 → 1.108.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/e2e/real/admin-access.real.e2e.ts +77 -68
  2. package/e2e/real/agent-management.real.e2e.ts +165 -143
  3. package/e2e/real/owner-access.real.e2e.ts +228 -212
  4. package/openapi.platform.json +127 -6
  5. package/package.json +2 -2
  6. package/src/account-created-notifier.ts +1 -1
  7. package/src/account-onboarding.integration.test.ts +69 -0
  8. package/src/account-onboarding.ts +29 -3
  9. package/src/account-repo-lookup-api.integration.test.ts +163 -0
  10. package/src/account-repo-lookup-api.ts +106 -0
  11. package/src/account-repo-lookup.ts +89 -0
  12. package/src/account-trial-expiry-sweeper.ts +1 -1
  13. package/src/accounts-api.integration.test.ts +5 -2
  14. package/src/accounts-api.smoke.test.ts +21 -5
  15. package/src/accounts-api.ts +12 -15
  16. package/src/admin-boot-config.ts +2 -0
  17. package/src/admin-boot-config.unit.test.ts +27 -0
  18. package/src/admin-boot.ts +18 -10
  19. package/src/admin-spec.ts +6 -0
  20. package/src/admin-ui-account.smoke.test.ts +7 -3
  21. package/src/admin-ui-account.ts +10 -15
  22. package/src/admin-ui-accounts.smoke.test.ts +4 -4
  23. package/src/admin-ui-accounts.ts +7 -11
  24. package/src/admin-ui-settings-nav-context.smoke.test.ts +24 -0
  25. package/src/admin-ui-settings.smoke.test.ts +17 -1
  26. package/src/admin-ui.smoke.test.ts +168 -2
  27. package/src/admin-ui.ts +39 -26
  28. package/src/agent-management-access.integration.test.ts +18 -6
  29. package/src/agent-manifest.ts +2 -1
  30. package/src/agent-provisioner.integration.test.ts +10 -10
  31. package/src/agent-provisioner.ts +10 -1
  32. package/src/agent-provisioner.unit.test.ts +110 -36
  33. package/src/agent-templates-api.integration.test.ts +23 -5
  34. package/src/agent-templates-api.ts +11 -8
  35. package/src/caller-scope.integration.test.ts +8 -6
  36. package/src/caller-scope.ts +32 -26
  37. package/src/caller-scope.unit.test.ts +15 -11
  38. package/src/openapi-schemas.ts +22 -0
  39. package/src/platform-routes.ts +14 -2
  40. package/src/platform-routes.unit.test.ts +2 -0
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * admin/src/account-created-notifier.ts
3
- * Best-effort operator notification when self-serve sign-in auto-creates an
3
+ * Best-effort operator notification when self-serve signup auto-creates an
4
4
  * account (SSP-3.3). Reuses the existing web-push wiring — no new integration.
5
5
  * When push isn't configured, the structured `account_created` log emitted by
6
6
  * the Google callback (SSP-3.1) is the only signal.
@@ -98,4 +98,73 @@ describeOrSkip("AccountOnboardingService (integration)", () => {
98
98
  expect(results.every((r) => r.accountId === owner.id)).toBe(true);
99
99
  expect(results.filter((r) => r.kind === "joined")).toHaveLength(1);
100
100
  });
101
+
102
+ describe("joinForEmail (signup off)", () => {
103
+ it("returns null for an unknown email and creates nothing", async () => {
104
+ expect(await onboarding.joinForEmail("Stranger@x.com")).toBeNull();
105
+ expect(await prisma.account.count()).toBe(0);
106
+ expect(await prisma.accountMember.count()).toBe(0);
107
+ });
108
+
109
+ it("joins the invited account as member and marks the invite accepted", async () => {
110
+ const owner = await new AccountService(prisma).create(
111
+ "Acme",
112
+ "o@acme.com",
113
+ );
114
+ await new AccountInviteService(prisma).create(
115
+ owner.id,
116
+ "invitee@acme.com",
117
+ "o@acme.com",
118
+ );
119
+ expect(await onboarding.joinForEmail("Invitee@Acme.com")).toEqual({
120
+ kind: "joined",
121
+ accountId: owner.id,
122
+ });
123
+ expect(await prisma.account.count()).toBe(1);
124
+ const member = await prisma.accountMember.findUniqueOrThrow({
125
+ where: { email: "invitee@acme.com" },
126
+ });
127
+ expect(member.role).toBe("member");
128
+ const invite = await prisma.accountInvite.findFirstOrThrow({
129
+ where: { email: "invitee@acme.com" },
130
+ });
131
+ expect(invite.acceptedAt).not.toBeNull();
132
+ });
133
+
134
+ it("returns existing for an account owner with no agents", async () => {
135
+ const owner = await new AccountService(prisma).create(
136
+ "Acme",
137
+ "o@acme.com",
138
+ );
139
+ expect(await onboarding.joinForEmail("O@acme.com")).toEqual({
140
+ kind: "existing",
141
+ accountId: owner.id,
142
+ });
143
+ expect(await prisma.account.count()).toBe(1);
144
+ });
145
+
146
+ it("concurrent joins with a pending invite join once", async () => {
147
+ const owner = await new AccountService(prisma).create(
148
+ "Acme",
149
+ "o@acme.com",
150
+ );
151
+ await new AccountInviteService(prisma).create(
152
+ owner.id,
153
+ "race@acme.com",
154
+ "o@acme.com",
155
+ );
156
+ const results = await Promise.all(
157
+ Array.from({ length: 6 }, () =>
158
+ onboarding.joinForEmail("race@acme.com"),
159
+ ),
160
+ );
161
+ expect(new Set(results.map((r) => r?.accountId))).toEqual(
162
+ new Set([owner.id]),
163
+ );
164
+ expect(await prisma.account.count()).toBe(1);
165
+ expect(
166
+ await prisma.accountMember.count({ where: { email: "race@acme.com" } }),
167
+ ).toBe(1);
168
+ });
169
+ });
101
170
  });
@@ -4,7 +4,9 @@
4
4
  * agent provisioning (SSP-3.1).
5
5
  *
6
6
  * A verified email with no account yet either joins the account that invited
7
- * it (as 'member') or gets a brand-new account (as 'owner'). Everything runs
7
+ * it (as 'member') or, when signup is open, gets a brand-new account (as
8
+ * 'owner'). joinForEmail() is the signup-off variant: it never creates an
9
+ * account. Everything runs
8
10
  * in one transaction, and concurrent first logins for the same email are made
9
11
  * idempotent by UNIQUE(AccountMember.email): the losing transaction rolls back
10
12
  * entirely (including any account it created) and re-reads the winner's row.
@@ -36,12 +38,29 @@ export class AccountOnboardingService {
36
38
  * does, else join via pending invite ("joined"), else create ("created").
37
39
  */
38
40
  async provisionForEmail(rawEmail: string): Promise<OnboardingResult> {
41
+ // With allowCreate the result is never null (the last step creates).
42
+ return (await this.resolve(rawEmail, true)) as OnboardingResult;
43
+ }
44
+
45
+ /**
46
+ * Signup-off sign-in: "existing" if the email already belongs to an
47
+ * account, else join via pending invite ("joined"), else null. Never
48
+ * creates an account.
49
+ */
50
+ async joinForEmail(rawEmail: string): Promise<OnboardingResult | null> {
51
+ return this.resolve(rawEmail, false);
52
+ }
53
+
54
+ private async resolve(
55
+ rawEmail: string,
56
+ allowCreate: boolean,
57
+ ): Promise<OnboardingResult | null> {
39
58
  const email = normalizeEmail(rawEmail);
40
59
  let lastErr: unknown;
41
60
  for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
42
61
  try {
43
62
  return await this.prisma.$transaction((tx) =>
44
- this.provisionInTx(tx, email),
63
+ this.provisionInTx(tx, email, allowCreate),
45
64
  );
46
65
  } catch (err) {
47
66
  if (!isUniqueViolation(err)) throw err;
@@ -59,7 +78,8 @@ export class AccountOnboardingService {
59
78
  private async provisionInTx(
60
79
  tx: Parameters<Parameters<PrismaClient["$transaction"]>[0]>[0],
61
80
  email: string,
62
- ): Promise<OnboardingResult> {
81
+ allowCreate: boolean,
82
+ ): Promise<OnboardingResult | null> {
63
83
  const existing = await tx.accountMember.findUnique({ where: { email } });
64
84
  if (existing) return { kind: "existing", accountId: existing.accountId };
65
85
 
@@ -79,6 +99,12 @@ export class AccountOnboardingService {
79
99
  return { kind: "joined", accountId: invite.accountId };
80
100
  }
81
101
  }
102
+ if (!allowCreate) {
103
+ // A concurrent login may have claimed the invite and committed since
104
+ // the first read (read committed: this statement sees its member row).
105
+ const winner = await tx.accountMember.findUnique({ where: { email } });
106
+ return winner ? { kind: "existing", accountId: winner.accountId } : null;
107
+ }
82
108
 
83
109
  const account = await tx.account.create({
84
110
  data: {
@@ -0,0 +1,163 @@
1
+ /**
2
+ * admin/src/account-repo-lookup-api.integration.test.ts
3
+ * POST /account-lookup/by-repos against real Postgres (MA-2.5).
4
+ *
5
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
6
+ */
7
+
8
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
9
+ import type { PrismaClient } from "../prisma/client/client.ts";
10
+ import { createAccountRepoLookupApp } from "./account-repo-lookup-api.ts";
11
+ import { AccountRepoLookupService } from "./account-repo-lookup.ts";
12
+ import { createAdminPrismaClient } from "./prisma-client.ts";
13
+
14
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
15
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
16
+
17
+ describeOrSkip("/account-lookup/by-repos API (integration)", () => {
18
+ let prisma: PrismaClient;
19
+ let app: ReturnType<typeof createAccountRepoLookupApp>;
20
+ const headers = {
21
+ Authorization: "Bearer k",
22
+ "Content-Type": "application/json",
23
+ };
24
+
25
+ const lookup = async (repos: string[]) => {
26
+ const res = await app.request("/account-lookup/by-repos", {
27
+ method: "POST",
28
+ headers,
29
+ body: JSON.stringify({ repos }),
30
+ });
31
+ expect(res.status).toBe(200);
32
+ return (await res.json()) as {
33
+ repos: { repo: string; accountIds: string[] }[];
34
+ singleAccount: boolean;
35
+ singleAccountId: string | null;
36
+ };
37
+ };
38
+
39
+ const account = (name: string) =>
40
+ prisma.account.create({ data: { name } }).then((a) => a.id);
41
+
42
+ beforeEach(async () => {
43
+ prisma = createAdminPrismaClient(TEST_DB as string);
44
+ await prisma.agentMember.deleteMany();
45
+ await prisma.accountMember.deleteMany();
46
+ await prisma.agent.deleteMany();
47
+ await prisma.account.deleteMany();
48
+ app = createAccountRepoLookupApp({
49
+ lookup: new AccountRepoLookupService(prisma),
50
+ sessionSecret: "s".repeat(32),
51
+ adminApiKeys: new Map([
52
+ ["k", { name: "t", scope: "*" }],
53
+ ["scoped", { name: "s", scope: "agent-1" }],
54
+ ]),
55
+ agentTokenService: { validate: async () => null } as never,
56
+ });
57
+ });
58
+
59
+ afterEach(async () => {
60
+ await prisma.$disconnect();
61
+ });
62
+
63
+ it("returns zero, one and several accounts per repo", async () => {
64
+ const a = await account("A");
65
+ const b = await account("B");
66
+ await prisma.agent.create({
67
+ data: { name: "x", accountId: a, repos: ["acme/widgets", "acme/one"] },
68
+ });
69
+ await prisma.agent.create({
70
+ data: { name: "y", accountId: b, repos: ["acme/widgets"] },
71
+ });
72
+ await prisma.agent.create({
73
+ data: { name: "z", accountId: a, repos: ["acme/widgets"] },
74
+ });
75
+
76
+ const body = await lookup(["acme/widgets", "acme/one", "acme/none"]);
77
+ expect(body.repos).toEqual([
78
+ { repo: "acme/widgets", accountIds: [a, b].sort() },
79
+ { repo: "acme/one", accountIds: [a] },
80
+ { repo: "acme/none", accountIds: [] },
81
+ ]);
82
+ expect(body.singleAccount).toBe(false);
83
+ expect(body.singleAccountId).toBeNull();
84
+ });
85
+
86
+ it("ignores deleted agents", async () => {
87
+ const a = await account("A");
88
+ const b = await account("B");
89
+ await prisma.agent.create({
90
+ data: { name: "x", accountId: a, repos: ["acme/widgets"] },
91
+ });
92
+ const gone = await prisma.agent.create({
93
+ data: { name: "y", accountId: b, repos: ["acme/widgets"] },
94
+ });
95
+ await prisma.agent.delete({ where: { id: gone.id } });
96
+
97
+ const body = await lookup(["acme/widgets"]);
98
+ expect(body.repos).toEqual([{ repo: "acme/widgets", accountIds: [a] }]);
99
+ });
100
+
101
+ it("matches case-insensitively in both directions", async () => {
102
+ const a = await account("A");
103
+ await prisma.agent.create({
104
+ data: { name: "x", accountId: a, repos: ["Acme/Widgets"] },
105
+ });
106
+ const body = await lookup(["acme/WIDGETS"]);
107
+ expect(body.repos).toEqual([{ repo: "acme/WIDGETS", accountIds: [a] }]);
108
+ });
109
+
110
+ it("counts an agent with no account as the default (oldest) account", async () => {
111
+ const a = await account("A");
112
+ await new Promise((r) => setTimeout(r, 5));
113
+ await account("B");
114
+ await prisma.agent.create({
115
+ data: { name: "x", repos: ["acme/widgets"] },
116
+ });
117
+ const body = await lookup(["acme/widgets"]);
118
+ expect(body.repos).toEqual([{ repo: "acme/widgets", accountIds: [a] }]);
119
+ });
120
+
121
+ it("reports the single-account case and resolves no-account agents to it", async () => {
122
+ const a = await account("A");
123
+ await prisma.agent.create({
124
+ data: { name: "x", repos: ["acme/widgets"] },
125
+ });
126
+ const body = await lookup(["acme/widgets"]);
127
+ expect(body.singleAccount).toBe(true);
128
+ expect(body.singleAccountId).toBe(a);
129
+ expect(body.repos).toEqual([{ repo: "acme/widgets", accountIds: [a] }]);
130
+ });
131
+
132
+ it("reports no single account when the deployment has no accounts", async () => {
133
+ expect(await lookup([])).toEqual({
134
+ repos: [],
135
+ singleAccount: false,
136
+ singleAccountId: null,
137
+ });
138
+ });
139
+
140
+ it("refuses unauthenticated (401) and non-admin (403) callers, and validates the body", async () => {
141
+ const init = (h: Record<string, string>) => ({
142
+ method: "POST",
143
+ headers: h,
144
+ body: JSON.stringify({ repos: ["acme/widgets"] }),
145
+ });
146
+ const anon = await app.request(
147
+ "/account-lookup/by-repos",
148
+ init({ "Content-Type": "application/json" }),
149
+ );
150
+ expect(anon.status).toBe(401);
151
+ const scoped = await app.request(
152
+ "/account-lookup/by-repos",
153
+ init({ ...headers, Authorization: "Bearer scoped" }),
154
+ );
155
+ expect(scoped.status).toBe(403);
156
+ const bad = await app.request("/account-lookup/by-repos", {
157
+ method: "POST",
158
+ headers,
159
+ body: JSON.stringify({ repos: "nope" }),
160
+ });
161
+ expect(bad.status).toBe(400);
162
+ });
163
+ });
@@ -0,0 +1,106 @@
1
+ /**
2
+ * admin/src/account-repo-lookup-api.ts
3
+ * Admin-only account lookup by repo (MA-2.5):
4
+ * POST /account-lookup/by-repos {repos} ->
5
+ * {repos:[{repo,accountIds}], singleAccount, singleAccountId}
6
+ * Auth: admin cookie or scope "*" key (service credential); every other
7
+ * caller class gets 403, unauthenticated callers 401.
8
+ */
9
+
10
+ import { createRoute, OpenAPIHono } from "@hono/zod-openapi";
11
+ import { HTTPException } from "hono/http-exception";
12
+ import type { AccountRepoLookupService } from "./account-repo-lookup.ts";
13
+ import type { AgentTokenService } from "./agent-tokens.ts";
14
+ import {
15
+ type AdminApiKey,
16
+ type AdminAuthEnv,
17
+ createAdminAuthMiddleware,
18
+ } from "./api-auth.ts";
19
+ import { ApiError, ForbiddenError } from "./errors.ts";
20
+ import {
21
+ AccountRepoLookupBodySchema,
22
+ AccountRepoLookupResponseSchema,
23
+ ErrorSchema,
24
+ } from "./openapi-schemas.ts";
25
+
26
+ interface AccountRepoLookupApiDeps {
27
+ lookup: Pick<AccountRepoLookupService, "lookupByRepos">;
28
+ sessionSecret: string;
29
+ adminApiKeys?: Map<string, AdminApiKey>;
30
+ agentTokenService: Pick<AgentTokenService, "validate">;
31
+ }
32
+
33
+ const jsonError = { content: { "application/json": { schema: ErrorSchema } } };
34
+
35
+ const lookupRoute = createRoute({
36
+ method: "post",
37
+ path: "/account-lookup/by-repos",
38
+ tags: ["accounts"],
39
+ summary: "Resolve repos to the accounts of the agents that list them",
40
+ description:
41
+ "Admin-only. For each repo, the distinct accounts of the agents that list it, matched case-insensitively. An agent with no account counts as the default account. Also reports whether the deployment has exactly one account and its id.",
42
+ request: {
43
+ body: {
44
+ content: { "application/json": { schema: AccountRepoLookupBodySchema } },
45
+ },
46
+ },
47
+ responses: {
48
+ 200: {
49
+ description: "Accounts per repo and the single-account report",
50
+ content: {
51
+ "application/json": { schema: AccountRepoLookupResponseSchema },
52
+ },
53
+ },
54
+ 400: { description: "Bad request", ...jsonError },
55
+ 401: { description: "Unauthorized", ...jsonError },
56
+ 403: { description: "Forbidden (non-admin caller)", ...jsonError },
57
+ },
58
+ });
59
+
60
+ export function createAccountRepoLookupApp(
61
+ deps: AccountRepoLookupApiDeps,
62
+ ): OpenAPIHono<AdminAuthEnv> {
63
+ const app = new OpenAPIHono<AdminAuthEnv>({
64
+ defaultHook: (result, c) => {
65
+ if (!result.success) {
66
+ const message = result.error.issues
67
+ .map((i) => `${i.path.join(".")}: ${i.message}`)
68
+ .join(", ");
69
+ return c.json({ error: message }, 400);
70
+ }
71
+ },
72
+ });
73
+
74
+ app.onError((err, c) => {
75
+ if (err instanceof ApiError && err.statusCode < 500) {
76
+ return c.json(
77
+ { error: err.message },
78
+ err.statusCode as 400 | 401 | 403 | 404 | 409 | 422,
79
+ );
80
+ }
81
+ if (err instanceof HTTPException && err.status < 500) {
82
+ return c.json({ error: err.message }, err.status as 400 | 415);
83
+ }
84
+ console.error("[account-repo-lookup-api] unhandled error:", err);
85
+ return c.json({ error: "Internal server error" }, 500);
86
+ });
87
+
88
+ app.use(
89
+ "/account-lookup/*",
90
+ createAdminAuthMiddleware({
91
+ sessionSecret: deps.sessionSecret,
92
+ agentTokenService: deps.agentTokenService,
93
+ adminApiKeys: deps.adminApiKeys,
94
+ }),
95
+ );
96
+
97
+ app.openapi(lookupRoute, async (c) => {
98
+ if (c.get("isAdmin") !== true) {
99
+ throw new ForbiddenError("Admin access required");
100
+ }
101
+ const { repos } = c.req.valid("json");
102
+ return c.json(await deps.lookup.lookupByRepos(repos), 200);
103
+ });
104
+
105
+ return app;
106
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * admin/src/account-repo-lookup.ts
3
+ * AccountRepoLookupService: for each requested repo, the distinct accounts of
4
+ * the agents that list it (case-insensitive), plus whether the deployment has
5
+ * exactly one account.
6
+ *
7
+ * Agents are hard-deleted, so every existing Agent row is a live agent. An
8
+ * agent with no account counts as the default account: the only account when
9
+ * there is exactly one, otherwise the oldest account (createdAt, then id).
10
+ * With no accounts at all, an account-less agent contributes nothing.
11
+ */
12
+
13
+ import type { PrismaClient } from "../prisma/client/client.ts";
14
+
15
+ export interface RepoAccountIds {
16
+ repo: string;
17
+ accountIds: string[];
18
+ }
19
+
20
+ export interface AccountRepoLookupResult {
21
+ repos: RepoAccountIds[];
22
+ singleAccount: boolean;
23
+ singleAccountId: string | null;
24
+ }
25
+
26
+ export class AccountRepoLookupService {
27
+ constructor(private prisma: PrismaClient) {}
28
+
29
+ /** Results follow first-seen request order; duplicate repos collapse. */
30
+ async lookupByRepos(repos: string[]): Promise<AccountRepoLookupResult> {
31
+ const accounts = await this.prisma.account.findMany({
32
+ select: { id: true },
33
+ orderBy: [{ createdAt: "asc" }, { id: "asc" }],
34
+ });
35
+ const singleAccount = accounts.length === 1;
36
+ const singleAccountId = singleAccount ? (accounts[0]?.id ?? null) : null;
37
+ const defaultAccountId = accounts[0]?.id ?? null;
38
+
39
+ const unique: string[] = [];
40
+ const seen = new Set<string>();
41
+ for (const repo of repos) {
42
+ if (seen.has(repo)) continue;
43
+ seen.add(repo);
44
+ unique.push(repo);
45
+ }
46
+ if (unique.length === 0) {
47
+ return { repos: [], singleAccount, singleAccountId };
48
+ }
49
+
50
+ const wanted = new Set(unique.map((r) => r.toLowerCase()));
51
+ const agents = await this.prisma.agent.findMany({
52
+ where: { repos: { hasSome: await this.matchingCases(wanted) } },
53
+ select: { accountId: true, repos: true },
54
+ });
55
+
56
+ const byRepo = new Map<string, Set<string>>();
57
+ for (const agent of agents) {
58
+ const accountId = agent.accountId ?? defaultAccountId;
59
+ if (accountId === null) continue;
60
+ for (const r of agent.repos) {
61
+ const key = r.toLowerCase();
62
+ if (!wanted.has(key)) continue;
63
+ const set = byRepo.get(key) ?? new Set<string>();
64
+ set.add(accountId);
65
+ byRepo.set(key, set);
66
+ }
67
+ }
68
+
69
+ return {
70
+ repos: unique.map((repo) => ({
71
+ repo,
72
+ accountIds: [...(byRepo.get(repo.toLowerCase()) ?? [])].sort(),
73
+ })),
74
+ singleAccount,
75
+ singleAccountId,
76
+ };
77
+ }
78
+
79
+ /**
80
+ * Prisma's `hasSome` is case-sensitive, so prefilter with the exact stored
81
+ * spellings found via a case-insensitive raw match.
82
+ */
83
+ private async matchingCases(wanted: Set<string>): Promise<string[]> {
84
+ const rows = await this.prisma.$queryRaw<{ repo: string }[]>`
85
+ SELECT DISTINCT r AS repo FROM "Agent", unnest("repos") AS r
86
+ WHERE lower(r) = ANY(${[...wanted]}::text[])`;
87
+ return rows.map((row) => row.repo);
88
+ }
89
+ }
@@ -18,7 +18,7 @@
18
18
  * Idempotent by construction: once an account is trial_expired and its crons
19
19
  * are disabled, neither query matches anything, so a re-run writes nothing.
20
20
  * Never deletes anything (no deleteAgentFully call). Registered via setInterval
21
- * in main.ts, flag-gated on self-serve.
21
+ * in admin-boot.ts; always runs (independent of the self-serve setting).
22
22
  */
23
23
 
24
24
  import type { AccountLifecycle } from "./account-lifecycle.ts";
@@ -24,7 +24,10 @@ import { createAdminPrismaClient } from "./prisma-client.ts";
24
24
  const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
25
25
  const describeOrSkip = TEST_DB ? describe : describe.skip;
26
26
 
27
- describeOrSkip("/accounts API (integration)", () => {
27
+ /** Run with the self-serve setting off and on; the outcome must not differ. */
28
+ const SELF_SERVE = [false, true];
29
+
30
+ describeOrSkip.each(SELF_SERVE)("/accounts API, self-serve=%p", (enabled) => {
28
31
  let prisma: PrismaClient;
29
32
  let accounts: AccountService;
30
33
  let app: ReturnType<typeof createAccountsApp>;
@@ -43,7 +46,7 @@ describeOrSkip("/accounts API (integration)", () => {
43
46
  accounts = new AccountService(prisma);
44
47
  app = createAccountsApp({
45
48
  selfServe: {
46
- enabled: true,
49
+ enabled,
47
50
  defaultMaxAgents: 0,
48
51
  contactEmail: "c@x.com",
49
52
  },
@@ -120,11 +120,27 @@ function req(
120
120
  });
121
121
  }
122
122
 
123
- describe("flag off", () => {
124
- it.each(ROUTES)("%s %s -> 404", async (method, path, body) => {
125
- const { app } = build(false);
126
- const res = await req(app, method, path, adminHeaders, body);
127
- expect(res.status).toBe(404);
123
+ describe("self-serve flag off", () => {
124
+ it.each(ROUTES)(
125
+ "%s %s answers exactly as with the flag on",
126
+ async (method, path, body) => {
127
+ const off = await req(build(false).app, method, path, adminHeaders, body);
128
+ const on = await req(build(true).app, method, path, adminHeaders, body);
129
+ expect(off.status).not.toBe(404);
130
+ expect(off.status).toBe(on.status);
131
+ expect(await off.json()).toEqual(await on.json());
132
+ },
133
+ );
134
+
135
+ it.each(ROUTES)("%s %s: non-admin cookie -> 403", async (m, p, b) => {
136
+ const res = await req(
137
+ build(false).app,
138
+ m,
139
+ p,
140
+ { Cookie: `admin_session=${await cookie(false)}` },
141
+ b,
142
+ );
143
+ expect(res.status).toBe(403);
128
144
  });
129
145
  });
130
146
 
@@ -1,9 +1,8 @@
1
1
  /**
2
2
  * admin/src/accounts-api.ts
3
3
  * Admin-only /accounts API (SSP-5.1): list/get/create/patch self-serve
4
- * accounts. Flag-gated (404 when SHIPWRIGHT_SELF_SERVE_ENABLED is off, checked
5
- * before auth) and admin-only (admin cookie or scope "*" key); every other
6
- * caller class gets 403.
4
+ * accounts. Admin-only (admin cookie or scope "*" key); every other caller
5
+ * class gets 403. Available whether or not self-serve signup is enabled.
7
6
  *
8
7
  * POST /accounts goes through AccountService.create(), which seeds the owner
9
8
  * AccountMember row — so that owner's first login joins this account instead
@@ -50,6 +49,10 @@ interface AccountsApiDeps {
50
49
  * lockdown/restore side effect (SSP-8.2).
51
50
  */
52
51
  accountLifecycle: Pick<AccountLifecycle, "update">;
52
+ /**
53
+ * @deprecated Ignored: the accounts API no longer depends on the self-serve
54
+ * setting. Kept optional so existing callers keep compiling.
55
+ */
53
56
  selfServe?: SelfServeConfig;
54
57
  sessionSecret: string;
55
58
  adminApiKeys?: Map<string, AdminApiKey>;
@@ -61,7 +64,7 @@ const jsonError = { content: { "application/json": { schema: ErrorSchema } } };
61
64
  const errorResponses = {
62
65
  401: { description: "Unauthorized", ...jsonError },
63
66
  403: { description: "Forbidden (non-admin caller)", ...jsonError },
64
- 404: { description: "Not found (or self-serve disabled)", ...jsonError },
67
+ 404: { description: "Not found", ...jsonError },
65
68
  };
66
69
 
67
70
  const listAccountsRoute = createRoute({
@@ -70,7 +73,7 @@ const listAccountsRoute = createRoute({
70
73
  tags: ["accounts"],
71
74
  summary: "List accounts",
72
75
  description:
73
- "Admin-only, flag-gated. Returns every account with agentCount and memberCount.",
76
+ "Admin-only. Returns every account with agentCount and memberCount.",
74
77
  responses: {
75
78
  200: {
76
79
  description: "Accounts",
@@ -85,7 +88,7 @@ const getAccountRoute = createRoute({
85
88
  path: "/accounts/{id}",
86
89
  tags: ["accounts"],
87
90
  summary: "Get an account",
88
- description: "Admin-only, flag-gated.",
91
+ description: "Admin-only.",
89
92
  request: { params: AccountIdParamSchema },
90
93
  responses: {
91
94
  200: {
@@ -102,7 +105,7 @@ const createAccountRoute = createRoute({
102
105
  tags: ["accounts"],
103
106
  summary: "Create an account",
104
107
  description:
105
- "Admin-only, flag-gated. Creates the account and seeds ownerEmail as its owner member, so that owner's first login joins this account. 409 if ownerEmail already belongs to an account.",
108
+ "Admin-only. Creates the account and seeds ownerEmail as its owner member, so that owner's first login joins this account. 409 if ownerEmail already belongs to an account.",
106
109
  request: {
107
110
  body: {
108
111
  content: { "application/json": { schema: CreateAccountBodySchema } },
@@ -125,7 +128,7 @@ const patchAccountRoute = createRoute({
125
128
  tags: ["accounts"],
126
129
  summary: "Update an account",
127
130
  description:
128
- "Admin-only, flag-gated. Updates name, maxAgents, plan, status and/or trialExpiresAt. status=suspended (or trial_expired) disables every enabled cron of the account's agents with a lockdown marker; status=active re-enables exactly those, and requires trialExpiresAt to be cleared or in the future (422 otherwise). Nothing is deleted.",
131
+ "Admin-only. Updates name, maxAgents, plan, status and/or trialExpiresAt. status=suspended (or trial_expired) disables every enabled cron of the account's agents with a lockdown marker; status=active re-enables exactly those, and requires trialExpiresAt to be cleared or in the future (422 otherwise). Nothing is deleted.",
129
132
  request: {
130
133
  params: AccountIdParamSchema,
131
134
  body: {
@@ -175,7 +178,7 @@ function serialize(a: {
175
178
  export function createAccountsApp(
176
179
  deps: AccountsApiDeps,
177
180
  ): OpenAPIHono<AdminAuthEnv> {
178
- const { accountService, selfServe } = deps;
181
+ const { accountService } = deps;
179
182
 
180
183
  const app = new OpenAPIHono<AdminAuthEnv>({
181
184
  defaultHook: (result, c) => {
@@ -208,13 +211,7 @@ export function createAccountsApp(
208
211
  adminApiKeys: deps.adminApiKeys,
209
212
  });
210
213
 
211
- // Flag gate runs before auth so a disabled deployment reveals nothing.
212
- const flagGate: Parameters<typeof app.use>[1] = async (c, next) => {
213
- if (selfServe?.enabled !== true) return c.json({ error: "Not found" }, 404);
214
- return next();
215
- };
216
214
  // "/accounts/*" also matches the bare "/accounts" path in Hono.
217
- app.use("/accounts/*", flagGate);
218
215
  app.use("/accounts/*", authMiddleware);
219
216
 
220
217
  const requireAdmin = (c: { get: (k: "isAdmin") => unknown }) => {
@@ -204,6 +204,8 @@ export function buildProvisioner(
204
204
 
205
205
  return new KubernetesAgentProvisioner(k8s, agentTokenService, {
206
206
  namespace,
207
+ // Tenant pod label + CPU limit only on deployments with open signup.
208
+ tenantPodRestrictions: env.SHIPWRIGHT_SELF_SERVE_ENABLED === "enabled",
207
209
  image,
208
210
  imageTag,
209
211
  ...(images ? { images } : {}),