create-ailk 0.45.0 → 0.46.0

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 (42) hide show
  1. package/README.md +6 -3
  2. package/component-catalog.json +24 -1
  3. package/component-catalog.md +6 -5
  4. package/dist/lib/env-catalog.js +1 -1
  5. package/dist/lib/import-mdx.js +10 -2
  6. package/dist/seed-workspace.d.ts +1 -1
  7. package/dist/seed-workspace.js +10 -3
  8. package/dist/surfaces.js +1 -1
  9. package/package.json +3 -3
  10. package/templates/apps/api/.env.example +23 -0
  11. package/templates/apps/api/CLAUDE.md +13 -6
  12. package/templates/apps/api/src/lib/__mocks__/prisma.ts +11 -0
  13. package/templates/apps/mcp/.env.example +8 -0
  14. package/templates/apps/mcp/CLAUDE.md +22 -6
  15. package/templates/apps/web/.env.example +1 -1
  16. package/templates/apps/web/CLAUDE.md +47 -16
  17. package/templates/apps/web/app/.well-known/mcp.json/route.ts +6 -7
  18. package/templates/apps/web/app/[locale]/layout.tsx +10 -7
  19. package/templates/apps/web/app/api/site-status/__tests__/route.test.ts +120 -0
  20. package/templates/apps/web/app/api/site-status/route.ts +62 -0
  21. package/templates/apps/web/app/llms.txt/route.ts +3 -3
  22. package/templates/apps/web/app/openapi.json/__tests__/route.test.ts +21 -4
  23. package/templates/apps/web/app/openapi.json/route.ts +10 -9
  24. package/templates/apps/web/app/sitemap.xml/route.ts +3 -3
  25. package/templates/apps/web/auth.ts +25 -1
  26. package/templates/apps/web/lib/__tests__/fixtures/mcp-stub-server.ts +10 -3
  27. package/templates/apps/web/lib/__tests__/mcp-served-tools.test.ts +61 -0
  28. package/templates/apps/web/lib/__tests__/offerings-pricing.test.ts +112 -0
  29. package/templates/apps/web/lib/__tests__/pricing-page.test.ts +280 -0
  30. package/templates/apps/web/lib/__tests__/site-brand.test.ts +5 -6
  31. package/templates/apps/web/lib/__tests__/site-visibility.test.ts +64 -0
  32. package/templates/apps/web/lib/mcp-oauth.ts +64 -0
  33. package/templates/apps/web/lib/mcp-served-tools.ts +51 -9
  34. package/templates/apps/web/lib/offerings-pricing.ts +30 -6
  35. package/templates/apps/web/lib/pricing-page.ts +142 -35
  36. package/templates/apps/web/lib/site-brand.tsx +1 -7
  37. package/templates/apps/web/lib/site-visibility.ts +45 -0
  38. package/templates/apps/web/messages/en.json +8 -0
  39. package/templates/apps/web/middleware.ts +16 -1
  40. package/templates/apps/web/src/lib/routes.ts +3 -3
  41. package/versions.json +51 -51
  42. package/templates/apps/web/app/.well-known/ai-plugin.json/route.ts +0 -93
@@ -1,18 +1,31 @@
1
1
  /**
2
2
  * The shared Pricing render (#10044 D5, AC-4): which offering pages `/pricing`
3
3
  * lists, the card it lists each with, and `plans: []` reading no Stripe data.
4
+ * #12103: plan groups (AC-2), the default Recommended's pill (AC-3) and the
5
+ * authored card layout (AC-5), through the pure `offeringsFragments` and
6
+ * `withOfferings`.
4
7
  */
5
8
  import {
6
9
  PageSectionsSchema,
10
+ workspaceShownSetSchema,
11
+ type OfferingsPrice,
12
+ type OfferingsProduct,
7
13
  type PageSection,
14
+ type WorkspaceShownSet,
8
15
  } from "@working-theory/validation";
9
16
 
17
+ import {
18
+ offeringsPricing,
19
+ type OfferingsPricingLabels,
20
+ } from "../offerings-pricing";
10
21
  import {
11
22
  offeringPricingPages,
23
+ offeringsFragments,
12
24
  pagePlans,
13
25
  PRICING_HUB_SLUG,
14
26
  pricingPageCard,
15
27
  pricingSections,
28
+ withOfferings,
16
29
  } from "../pricing-page";
17
30
  import type { DetailPage } from "@working-theory/site-pages/lib/route-family";
18
31
 
@@ -140,3 +153,270 @@ describe("pricingSections (#10044 AC-4)", () => {
140
153
  );
141
154
  });
142
155
  });
156
+
157
+ // ─── #12103 — plan groups, the default Recommended, the card layout ─────────
158
+
159
+ const LABELS: OfferingsPricingLabels = {
160
+ cta: "CTA⟪",
161
+ recommended: "REC⟪",
162
+ monthly: (amount) => "M⟪" + amount,
163
+ annual: (amount) => "Y⟪" + amount,
164
+ oneTime: (amount) => "O⟪" + amount,
165
+ withRequired: (plan, required) => "W⟪" + plan + "⟫" + required,
166
+ depositNote: (deposit) => "D⟪" + deposit,
167
+ };
168
+ const RECOMMENDED_LABEL = "FOR-YOU⟪";
169
+ const ADDONS_HEADLINE = "ADDONS⟪";
170
+
171
+ function stripePrice(
172
+ plan: string,
173
+ period: "monthly" | "yearly",
174
+ amount: number,
175
+ ): OfferingsPrice {
176
+ return {
177
+ priceId: `price_${plan}${period}`,
178
+ lookupKey: `${plan}_${period}`,
179
+ plan,
180
+ period,
181
+ interval: period === "monthly" ? "month" : "year",
182
+ amount,
183
+ currency: "usd",
184
+ };
185
+ }
186
+
187
+ function stripeProduct(
188
+ plan: string,
189
+ ailkGroup: "plan" | "addon",
190
+ prices: OfferingsPrice[],
191
+ extra: Partial<OfferingsProduct> = {},
192
+ ): OfferingsProduct {
193
+ return {
194
+ productId: `prod_${plan}`,
195
+ plan,
196
+ name: plan,
197
+ description: null,
198
+ marketingFeatures: [],
199
+ unitLabel: null,
200
+ note: null,
201
+ termsNote: null,
202
+ ailkGroup,
203
+ ailkOrder: null,
204
+ prices,
205
+ recommended: false,
206
+ ...extra,
207
+ };
208
+ }
209
+
210
+ /** essentials, growth (plans, monthly only), writing (monthly + yearly), seo (add-on). */
211
+ function stripeSet(
212
+ recommended: { growth?: boolean } = {},
213
+ ): WorkspaceShownSet {
214
+ const offerings = [
215
+ stripeProduct("essentials", "plan", [stripePrice("essentials", "monthly", 1000)]),
216
+ stripeProduct("growth", "plan", [stripePrice("growth", "monthly", 2000)], {
217
+ recommended: recommended.growth ?? false,
218
+ }),
219
+ stripeProduct("writing", "plan", [
220
+ stripePrice("writing", "monthly", 3000),
221
+ stripePrice("writing", "yearly", 30000),
222
+ ]),
223
+ stripeProduct("seo", "addon", [stripePrice("seo", "monthly", 900)]),
224
+ ];
225
+ return workspaceShownSetSchema.parse({
226
+ workspaceId: "wksp_01890a5d-ac96-774b-bcce-b302099a8057",
227
+ organizationId: "org_01890a5d-ac96-774b-bcce-b302099a8058",
228
+ productIds: offerings.map((o) => o.productId),
229
+ recommended: { plan: recommended.growth ? "prod_growth" : null, addon: null },
230
+ offerings,
231
+ state: "current",
232
+ snapshotAt: "2026-11-20T00:00:00.000Z",
233
+ });
234
+ }
235
+
236
+ type Pricing = Extract<PageSection, { type: "pricing" }>;
237
+
238
+ function pricingSection(id: string, data: Record<string, unknown> = {}): Pricing {
239
+ return { id, type: "pricing", data: { plans: [], ...data } } as Pricing;
240
+ }
241
+
242
+ const HERO = {
243
+ id: "hero",
244
+ type: "hero",
245
+ data: { headline: "Pricing" },
246
+ } as PageSection;
247
+ const EXTRAS = pricingSection("extras", { variant: "addons", headline: "Extras" });
248
+
249
+ /** `offeringsFragments` then `withOfferings`, as `pricingSections` runs them. */
250
+ function render(
251
+ sections: PageSection[],
252
+ options: {
253
+ plans?: readonly string[];
254
+ plan?: string;
255
+ set?: WorkspaceShownSet;
256
+ } = {},
257
+ ) {
258
+ const fragments = offeringsFragments(sections, options.set ?? stripeSet(), {
259
+ locale: "en-US",
260
+ labels: LABELS,
261
+ plans: options.plans,
262
+ });
263
+ const placed = withOfferings(
264
+ sections,
265
+ fragments.pricing!,
266
+ options.plan,
267
+ RECOMMENDED_LABEL,
268
+ ADDONS_HEADLINE,
269
+ fragments.groups,
270
+ );
271
+ return { placed, groups: fragments.groups };
272
+ }
273
+
274
+ function dataOf(placed: PageSection[], id: string) {
275
+ const found = placed.find((s) => s.id === id);
276
+ if (!found || found.type !== "pricing") throw new Error(`no pricing ${id}`);
277
+ return found.data as Pricing["data"] & { recommended?: string };
278
+ }
279
+
280
+ const keysOf = (placed: PageSection[], id: string) =>
281
+ dataOf(placed, id).plans.map((card) => card.key);
282
+
283
+ const allKeys = (placed: PageSection[]) =>
284
+ placed.flatMap((s) =>
285
+ s.type === "pricing" ? s.data.plans.map((card) => card.key) : [],
286
+ );
287
+
288
+ describe("plan groups — offeringPlans on a pricing section (#12103 D2, AC-2)", () => {
289
+ it("two listed groups each show their own plans, with their own toggle, and none is removed", () => {
290
+ const { placed } = render([
291
+ HERO,
292
+ pricingSection("retainers", { offeringPlans: ["essentials", "growth"] }),
293
+ pricingSection("writing-skills", { offeringPlans: ["writing"] }),
294
+ EXTRAS,
295
+ ]);
296
+ expect(placed.map((s) => s.id)).toEqual(["hero", "retainers", "writing-skills", "extras"]);
297
+ expect(keysOf(placed, "retainers")).toEqual(["essentials", "growth"]);
298
+ expect(dataOf(placed, "retainers").billingToggle).toBe(false);
299
+ expect(keysOf(placed, "writing-skills")).toEqual(["writing"]);
300
+ expect(dataOf(placed, "writing-skills").billingToggle).toBe(true);
301
+ expect(dataOf(placed, "extras").addons?.map((t) => t.name)).toEqual(["seo"]);
302
+ });
303
+
304
+ it("an unlisted plans section shows the page's plans less the listed ones", () => {
305
+ const { placed } = render([
306
+ HERO,
307
+ pricingSection("retainers"),
308
+ pricingSection("writing-skills", { offeringPlans: ["writing"] }),
309
+ EXTRAS,
310
+ ]);
311
+ expect(keysOf(placed, "retainers")).toEqual(["essentials", "growth"]);
312
+ expect(keysOf(placed, "writing-skills")).toEqual(["writing"]);
313
+ });
314
+
315
+ it("removes a listed group with nothing shown, and its plan appears nowhere", () => {
316
+ const { placed } = render([
317
+ HERO,
318
+ pricingSection("retainers", { offeringPlans: ["essentials", "growth"] }),
319
+ pricingSection("writing-skills", { offeringPlans: ["absent"] }),
320
+ EXTRAS,
321
+ ]);
322
+ expect(placed.map((s) => s.id)).toEqual(["hero", "retainers", "extras"]);
323
+ expect(allKeys(placed)).not.toContain("writing");
324
+ });
325
+
326
+ it("inserts no section for the leftover plans when every plans section is listed", () => {
327
+ const { placed } = render([
328
+ HERO,
329
+ pricingSection("retainers", { offeringPlans: ["essentials"] }),
330
+ pricingSection("writing-skills", { offeringPlans: ["writing"] }),
331
+ EXTRAS,
332
+ ]);
333
+ expect(placed.map((s) => s.id)).toEqual(["hero", "retainers", "writing-skills", "extras"]);
334
+ expect(allKeys(placed)).not.toContain("growth");
335
+ expect(placed.some((s) => s.id === "offerings-plans")).toBe(false);
336
+ });
337
+
338
+ it("a page with no offeringPlans renders exactly as today (FR-3)", () => {
339
+ const a = pricingSection("a", { headline: "A", eyebrow: "Plans" });
340
+ const { placed, groups } = render([HERO, a, pricingSection("b"), EXTRAS]);
341
+ expect(placed.map((s) => s.id)).toEqual(["hero", "a", "extras"]);
342
+ expect(groups.size).toBe(0);
343
+ const cards = offeringsPricing(stripeSet(), { locale: "en-US", labels: LABELS })!.plans!.plans;
344
+ expect(dataOf(placed, "a")).toEqual({
345
+ headline: "A",
346
+ eyebrow: "Plans",
347
+ variant: "three-tiers-with-toggle",
348
+ cardLayout: "centered",
349
+ billingToggle: true,
350
+ plans: cards,
351
+ recommendedLabel: RECOMMENDED_LABEL,
352
+ });
353
+ });
354
+
355
+ it("applies ?plan= in the group whose cards carry it; the other keeps its default", () => {
356
+ const { placed } = render(
357
+ [
358
+ pricingSection("retainers", { offeringPlans: ["essentials", "growth"] }),
359
+ pricingSection("writing-skills", { offeringPlans: ["writing"] }),
360
+ ],
361
+ { plan: "writing", set: stripeSet({ growth: true }) },
362
+ );
363
+ expect(dataOf(placed, "writing-skills").plans[0]).not.toHaveProperty("highlightLabel");
364
+ const growth = dataOf(placed, "retainers").plans.find((c) => c.key === "growth");
365
+ expect(growth?.highlightLabel).toBe(LABELS.recommended);
366
+ });
367
+
368
+ it("makes no shown-offerings read for page `plans: []`, whatever a section lists", async () => {
369
+ const declared = [pricingSection("writing-skills", { offeringPlans: ["writing"] })];
370
+ const sections = await pricingSections(declared, {
371
+ plans: [],
372
+ plan: undefined,
373
+ locale: "en",
374
+ });
375
+ expect(fetchMock).not.toHaveBeenCalled();
376
+ expect(sections).toBe(declared);
377
+ });
378
+ });
379
+
380
+ describe("the default Recommended's pill (#12103 D3, AC-3)", () => {
381
+ it("shows the pill on the workspace's Recommended plan with no ?plan=", () => {
382
+ const { placed } = render([pricingSection("plans")], { set: stripeSet({ growth: true }) });
383
+ const growth = dataOf(placed, "plans").plans.find((c) => c.key === "growth");
384
+ expect(growth).toMatchObject({
385
+ highlighted: true,
386
+ highlightStyle: "pill",
387
+ highlightLabel: LABELS.recommended,
388
+ });
389
+ expect(dataOf(placed, "plans").recommended).toBeUndefined();
390
+ });
391
+
392
+ it("lets ?plan= move it for that visit", () => {
393
+ const { placed } = render([pricingSection("plans")], {
394
+ set: stripeSet({ growth: true }),
395
+ plan: "essentials",
396
+ });
397
+ const data = dataOf(placed, "plans");
398
+ expect(data.plans.some((c) => c.highlightLabel !== undefined)).toBe(false);
399
+ expect(data.recommended).toBe("essentials");
400
+ });
401
+ });
402
+
403
+ describe("the authored card layout survives (#12103 D6, AC-5)", () => {
404
+ it("keeps a plans slot's cardLayout over the mapper's, and the mapper's when the slot sets none", () => {
405
+ expect(dataOf(render([pricingSection("plans", { cardLayout: "default" })]).placed, "plans").cardLayout).toBe("default");
406
+ expect(dataOf(render([pricingSection("plans")]).placed, "plans").cardLayout).toBe("centered");
407
+ });
408
+
409
+ it("keeps a listed group's cardLayout", () => {
410
+ const { placed } = render([
411
+ pricingSection("writing-skills", { offeringPlans: ["writing"], cardLayout: "default" }),
412
+ ]);
413
+ expect(dataOf(placed, "writing-skills").cardLayout).toBe("default");
414
+ });
415
+
416
+ it("keeps the mapper's billingToggle over an authored one", () => {
417
+ const { placed } = render([
418
+ pricingSection("retainers", { offeringPlans: ["essentials", "growth"], billingToggle: true }),
419
+ ]);
420
+ expect(dataOf(placed, "retainers").billingToggle).toBe(false);
421
+ });
422
+ });
@@ -310,14 +310,13 @@ describe("resolveSiteBrand() (#11456 D4)", () => {
310
310
  const hub = (identity: unknown, seo: unknown = null) =>
311
311
  mockReadHubSite.mockResolvedValue({ identity, seo });
312
312
 
313
- it("with no hub site, answers the module's constants and indexable", async () => {
313
+ it("with no hub site, answers the module's constants", async () => {
314
314
  mockReadHubSite.mockResolvedValue(undefined);
315
315
  const brand = await loadSiteBrand();
316
316
  await expect(brand.resolveSiteBrand()).resolves.toEqual({
317
317
  siteName: brand.SITE_NAME,
318
318
  description: brand.SITE_DESCRIPTION,
319
319
  copyrightHolder: brand.COPYRIGHT_HOLDER,
320
- indexable: true,
321
320
  });
322
321
  });
323
322
 
@@ -331,7 +330,6 @@ describe("resolveSiteBrand() (#11456 D4)", () => {
331
330
  siteName: "Hub Co",
332
331
  description: "Seo description.",
333
332
  copyrightHolder: "Hub Co",
334
- indexable: true,
335
333
  });
336
334
  });
337
335
 
@@ -358,12 +356,13 @@ describe("resolveSiteBrand() (#11456 D4)", () => {
358
356
  await expect(resolveSiteBrand()).resolves.toMatchObject({ siteName: "Env Name" });
359
357
  });
360
358
 
361
- it("indexable reads the seo row even with no identity row", async () => {
359
+ it("a stored seo robots.index false gives a brand with no indexing field (#11978 D7)", async () => {
362
360
  hub(null, { version: "1", robots: { index: false } });
363
361
  const brand = await loadSiteBrand();
364
- await expect(brand.resolveSiteBrand()).resolves.toMatchObject({
362
+ await expect(brand.resolveSiteBrand()).resolves.toEqual({
365
363
  siteName: brand.SITE_NAME,
366
- indexable: false,
364
+ description: brand.SITE_DESCRIPTION,
365
+ copyrightHolder: brand.COPYRIGHT_HOLDER,
367
366
  });
368
367
  });
369
368
  });
@@ -0,0 +1,64 @@
1
+ /**
2
+ * #11978 D2 — the site's one rule for Hidden (AC-2 (d), AC-3 (a)).
3
+ */
4
+
5
+ import { StealthValueError } from "@working-theory/web-i18n/stealth";
6
+
7
+ const mockSiteDiscoverable = jest.fn();
8
+ jest.mock("@working-theory/api-client", () => ({
9
+ siteDiscoverable: () => mockSiteDiscoverable(),
10
+ }));
11
+
12
+ import { HIDDEN_ROBOTS_HEADER, siteHidden, siteLock } from "../site-visibility";
13
+
14
+ const saved = process.env["STEALTH"];
15
+
16
+ beforeEach(() => {
17
+ mockSiteDiscoverable.mockReset().mockResolvedValue(true);
18
+ delete process.env["STEALTH"];
19
+ });
20
+
21
+ afterAll(() => {
22
+ if (saved === undefined) delete process.env["STEALTH"];
23
+ else process.env["STEALTH"] = saved;
24
+ });
25
+
26
+ describe("siteHidden() (#11978 D2)", () => {
27
+ it("is true under STEALTH, with no hub read", async () => {
28
+ process.env["STEALTH"] = "true";
29
+ await expect(siteHidden()).resolves.toBe(true);
30
+ expect(mockSiteDiscoverable).not.toHaveBeenCalled();
31
+ });
32
+
33
+ it("is true with STEALTH unset and the switch off", async () => {
34
+ mockSiteDiscoverable.mockResolvedValue(false);
35
+ await expect(siteHidden()).resolves.toBe(true);
36
+ });
37
+
38
+ it("is false with both off", async () => {
39
+ process.env["STEALTH"] = "false";
40
+ await expect(siteHidden()).resolves.toBe(false);
41
+ expect(mockSiteDiscoverable).toHaveBeenCalledTimes(1);
42
+ });
43
+
44
+ it("throws StealthValueError on a bogus STEALTH", async () => {
45
+ process.env["STEALTH"] = "maybe";
46
+ await expect(siteHidden()).rejects.toBeInstanceOf(StealthValueError);
47
+ });
48
+ });
49
+
50
+ describe("siteLock() (#11978 D2)", () => {
51
+ it.each([
52
+ ["true", "hosting"],
53
+ ["1", "hosting"],
54
+ ["off", null],
55
+ [undefined, null],
56
+ ])("STEALTH=%s → %s", (raw, lock) => {
57
+ if (raw !== undefined) process.env["STEALTH"] = raw;
58
+ expect(siteLock()).toBe(lock);
59
+ });
60
+
61
+ it("is STEALTH's own header value", () => {
62
+ expect(HIDDEN_ROBOTS_HEADER).toBe("noindex, nofollow, noarchive");
63
+ });
64
+ });
@@ -89,6 +89,16 @@ export interface McpOAuthDeps {
89
89
  * carrying the entry is not this server's. Requires `issuerTag`.
90
90
  */
91
91
  allWorkspaces?: boolean;
92
+ /**
93
+ * #12063 FR7 — clear outside-send switches, in every workspace: one
94
+ * person's for one client, or (no `applicationId`) every client of theirs.
95
+ * A switch never outlives the connection it was given to, so this runs when
96
+ * the person's line for a client ends (`/mcp/revoke`, `/mcp/revoke-client`,
97
+ * a changed password) and when a client and person with no live token
98
+ * consent again, which also covers a lapsed refresh and a disabled client.
99
+ * Absent: nothing is cleared.
100
+ */
101
+ clearOutsideSendSwitches?(target: { userId: string; applicationId?: string }): Promise<void>;
92
102
  }
93
103
 
94
104
  /** The scopes `/mcp/authorize` accepts a request for. */
@@ -234,6 +244,7 @@ interface AuthorizationValue {
234
244
  }
235
245
 
236
246
  interface OAuthApplicationRow {
247
+ id: string;
237
248
  clientId: string;
238
249
  clientSecret?: string | null;
239
250
  type?: string | null;
@@ -572,6 +583,14 @@ export function mcpOAuthPlugin(deps: McpOAuthDeps) {
572
583
  `[auth-email] ${JSON.stringify({ userId, kind: "password-change", reason: "mcp_token_revocation_failed" })}`,
573
584
  );
574
585
  }
586
+ // #12063 FR7 — and their outside-send switches with them.
587
+ try {
588
+ await deps.clearOutsideSendSwitches?.({ userId });
589
+ } catch {
590
+ console.warn(
591
+ `[auth-email] ${JSON.stringify({ userId, kind: "password-change", reason: "outside_send_clear_failed" })}`,
592
+ );
593
+ }
575
594
  }),
576
595
  },
577
596
  ],
@@ -691,6 +710,22 @@ export function mcpOAuthPlugin(deps: McpOAuthDeps) {
691
710
  });
692
711
  }
693
712
 
713
+ // #12063 FR7 — a client and person with no live token are a new
714
+ // connection, so it starts off: whatever ended the last one (a
715
+ // lapsed refresh, a disabled client, a revoke elsewhere), an owner
716
+ // who let that one send did not let this one.
717
+ if (deps.clearOutsideSendSwitches) {
718
+ const live = await ctx.context.adapter.findOne({
719
+ model: "oauthAccessToken",
720
+ where: [
721
+ { field: "clientId", value: value.clientId },
722
+ { field: "userId", value: userId },
723
+ { field: "refreshTokenExpiresAt", value: new Date(), operator: "gt" },
724
+ ],
725
+ });
726
+ if (!live) await deps.clearOutsideSendSwitches({ applicationId: client.id, userId });
727
+ }
728
+
694
729
  // `openid`, `profile` and `email` are never bound: no id_token.
695
730
  const scope = [
696
731
  // Always bound: the plugin issues and refreshes only for it, and
@@ -773,6 +808,22 @@ export function mcpOAuthPlugin(deps: McpOAuthDeps) {
773
808
  throw refuse("UNAUTHORIZED", "invalid_client");
774
809
  }
775
810
  if (!token) throw refuse("BAD_REQUEST", "invalid_request");
811
+ // #12063 FR7 — whose line this token is, read before it goes.
812
+ const held =
813
+ (await ctx.context.adapter.findOne<{ userId?: string | null }>({
814
+ model: "oauthAccessToken",
815
+ where: [
816
+ { field: "clientId", value: clientId },
817
+ { field: "accessToken", value: token },
818
+ ],
819
+ })) ??
820
+ (await ctx.context.adapter.findOne<{ userId?: string | null }>({
821
+ model: "oauthAccessToken",
822
+ where: [
823
+ { field: "clientId", value: clientId },
824
+ { field: "refreshToken", value: token },
825
+ ],
826
+ }));
776
827
  await deleteTokensOf(ctx, [
777
828
  { field: "clientId", value: clientId },
778
829
  { field: "accessToken", value: token },
@@ -781,6 +832,9 @@ export function mcpOAuthPlugin(deps: McpOAuthDeps) {
781
832
  { field: "clientId", value: clientId },
782
833
  { field: "refreshToken", value: token },
783
834
  ]);
835
+ if (held?.userId && deps.clearOutsideSendSwitches) {
836
+ await deps.clearOutsideSendSwitches({ applicationId: client.id, userId: held.userId });
837
+ }
784
838
  return ctx.json({});
785
839
  },
786
840
  ),
@@ -794,6 +848,16 @@ export function mcpOAuthPlugin(deps: McpOAuthDeps) {
794
848
  { field: "clientId", value: ctx.body.client_id },
795
849
  { field: "userId", value: ctx.context.session.user.id },
796
850
  ]);
851
+ // #12063 FR7 — the person's switches for this client go with it.
852
+ if (deps.clearOutsideSendSwitches) {
853
+ const app = await ctx.context.adapter.findOne<OAuthApplicationRow>({
854
+ model: "oauthApplication",
855
+ where: [{ field: "clientId", value: ctx.body.client_id }],
856
+ });
857
+ if (app) {
858
+ await deps.clearOutsideSendSwitches({ applicationId: app.id, userId: ctx.context.session.user.id });
859
+ }
860
+ }
797
861
  return ctx.json({ revoked });
798
862
  },
799
863
  ),
@@ -21,6 +21,15 @@
21
21
  * inside the window share it, a failure included, so an outage never adds the
22
22
  * deadline to every manifest request.
23
23
  *
24
+ * #11978 D3 — `readMcpServer(url)` is the same one exchange and the same
25
+ * shared answer, told apart for the site's status report: `answering` (with
26
+ * the tools, and the loaded packs' tool names the server reports in its
27
+ * `initialize` answer under `capabilities.experimental["ailk/installed"]`, or
28
+ * `null` from a server that reports none), `refused` when `initialize`
29
+ * answered HTTP 404 (the server is hidden, #10510), and `unreachable` for
30
+ * every other failure below. `readServedMcpTools(url)` is its tools when
31
+ * answering, else `null`, so mcp.json's answers are unchanged.
32
+ *
24
33
  * A failed read is `null` — a throw, the deadline, a non-2xx `initialize` or
25
34
  * `tools/list`, no JSON-RPC answer with the request's `id`, an `error`
26
35
  * answer, a `result.tools` that is not an array, an entry with no string
@@ -30,6 +39,8 @@
30
39
  * It never rejects.
31
40
  */
32
41
 
42
+ import { MCP_INSTALLED_CAPABILITY } from "@working-theory/validation";
43
+
33
44
  /** Names this caller and its purpose to the server's user-agent guard. */
34
45
  export const MCP_DISCOVERY_USER_AGENT = "ailk-web/mcp-discovery";
35
46
  /** The MCP protocol version this site speaks and its manifest advertises. */
@@ -48,6 +59,15 @@ export interface ServedMcpTool {
48
59
  inputSchema: Record<string, unknown>;
49
60
  }
50
61
 
62
+ /** #11978 D3 — what the MCP server at a URL answered. */
63
+ export type McpServerAnswer =
64
+ | { state: "answering"; tools: ServedMcpTool[]; installed: string[] | null }
65
+ | { state: "refused" }
66
+ | { state: "unreachable" };
67
+
68
+ const REFUSED: McpServerAnswer = { state: "refused" };
69
+ const UNREACHABLE: McpServerAnswer = { state: "unreachable" };
70
+
51
71
  type JsonRpcMessage = { id?: unknown; result?: unknown; error?: unknown };
52
72
 
53
73
  function isRecord(value: unknown): value is Record<string, unknown> {
@@ -94,13 +114,25 @@ function toServedTool(entry: unknown): ServedMcpTool | null {
94
114
  };
95
115
  }
96
116
 
97
- async function exchange(url: string): Promise<ServedMcpTool[] | null> {
117
+ /** #11978 D4 — the loaded packs' tool names from an `initialize` result, or `null`. */
118
+ function installedOf(result: Record<string, unknown>): string[] | null {
119
+ const capabilities = result["capabilities"];
120
+ const experimental = isRecord(capabilities) ? capabilities["experimental"] : undefined;
121
+ const entry = isRecord(experimental) ? experimental[MCP_INSTALLED_CAPABILITY] : undefined;
122
+ const tools = isRecord(entry) ? entry["tools"] : undefined;
123
+ return Array.isArray(tools) && tools.every((name) => typeof name === "string")
124
+ ? (tools as string[])
125
+ : null;
126
+ }
127
+
128
+ async function exchange(url: string): Promise<McpServerAnswer> {
98
129
  const signal = AbortSignal.timeout(MCP_TOOLS_TIMEOUT_MS);
99
130
  const headers: Record<string, string> = {
100
131
  "user-agent": MCP_DISCOVERY_USER_AGENT,
101
132
  accept: "application/json, text/event-stream",
102
133
  };
103
134
  let nextId = 1;
135
+ let lastStatus = 0;
104
136
 
105
137
  const post = (body: Record<string, unknown>): Promise<Response> =>
106
138
  fetch(url, {
@@ -119,6 +151,7 @@ async function exchange(url: string): Promise<ServedMcpTool[] | null> {
119
151
  ): Promise<{ result: Record<string, unknown>; res: Response } | null> => {
120
152
  const id = nextId++;
121
153
  const res = await post({ id, method, params });
154
+ lastStatus = res.status;
122
155
  if (!res.ok) {
123
156
  await res.body?.cancel();
124
157
  return null;
@@ -133,7 +166,8 @@ async function exchange(url: string): Promise<ServedMcpTool[] | null> {
133
166
  capabilities: {},
134
167
  clientInfo: { name: "ailk-web", version: "1" },
135
168
  });
136
- if (init === null) return null;
169
+ // #11978 D3 — a hidden server answers `initialize` with Fastify's 404.
170
+ if (init === null) return lastStatus === 404 ? REFUSED : UNREACHABLE;
137
171
  const sessionId = init.res.headers.get("mcp-session-id");
138
172
  const version = init.result["protocolVersion"];
139
173
  headers["mcp-protocol-version"] =
@@ -148,17 +182,19 @@ async function exchange(url: string): Promise<ServedMcpTool[] | null> {
148
182
  let cursor: string | undefined;
149
183
  for (let page = 0; page < MAX_PAGES; page++) {
150
184
  const listed = await call("tools/list", cursor === undefined ? {} : { cursor });
151
- if (listed === null || !Array.isArray(listed.result["tools"])) return null;
185
+ if (listed === null || !Array.isArray(listed.result["tools"])) return UNREACHABLE;
152
186
  for (const entry of listed.result["tools"] as unknown[]) {
153
187
  const tool = toServedTool(entry);
154
- if (tool === null) return null;
188
+ if (tool === null) return UNREACHABLE;
155
189
  tools.push(tool);
156
190
  }
157
191
  const next = listed.result["nextCursor"];
158
192
  cursor = typeof next === "string" ? next : undefined;
159
193
  if (cursor === undefined) break;
160
194
  }
161
- return cursor === undefined ? tools : null;
195
+ return cursor === undefined
196
+ ? { state: "answering", tools, installed: installedOf(init.result) }
197
+ : UNREACHABLE;
162
198
  } finally {
163
199
  if (sessionId) {
164
200
  // End the stateful session, whatever the list's outcome. No
@@ -171,18 +207,24 @@ async function exchange(url: string): Promise<ServedMcpTool[] | null> {
171
207
  }
172
208
  }
173
209
 
174
- const held = new Map<string, { at: number; answer: Promise<ServedMcpTool[] | null> }>();
210
+ const held = new Map<string, { at: number; answer: Promise<McpServerAnswer> }>();
175
211
 
176
- /** #11951 D2 — the tools the MCP server at `url` serves, or `null`. Never rejects. */
177
- export function readServedMcpTools(url: string): Promise<ServedMcpTool[] | null> {
212
+ /** #11978 D3 — what the MCP server at `url` answered. Never rejects. */
213
+ export function readMcpServer(url: string): Promise<McpServerAnswer> {
178
214
  const now = Date.now();
179
215
  const hit = held.get(url);
180
216
  if (hit !== undefined && now - hit.at < MCP_TOOLS_TTL_MS) return hit.answer;
181
- const answer = exchange(url).catch(() => null);
217
+ const answer = exchange(url).catch(() => UNREACHABLE);
182
218
  held.set(url, { at: now, answer });
183
219
  return answer;
184
220
  }
185
221
 
222
+ /** #11951 D2 — the tools the MCP server at `url` serves, or `null`. Never rejects. */
223
+ export async function readServedMcpTools(url: string): Promise<ServedMcpTool[] | null> {
224
+ const answer = await readMcpServer(url);
225
+ return answer.state === "answering" ? answer.tools : null;
226
+ }
227
+
186
228
  /** Test seam: forget every held answer. */
187
229
  export function __resetServedMcpToolsForTests(): void {
188
230
  held.clear();