create-ailk 0.40.0 → 0.40.2
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.
- package/README.md +26 -4
- package/component-catalog.json +1 -1
- package/component-catalog.md +1 -1
- package/dist/add-module.d.ts +2 -1
- package/dist/add-module.js +17 -1
- package/dist/cutover.d.ts +7 -3
- package/dist/cutover.js +8 -3
- package/dist/lib/declared-env.d.ts +5 -1
- package/dist/lib/declared-env.js +6 -1
- package/dist/lib/env-catalog.d.ts +3 -2
- package/dist/lib/env-catalog.js +4 -8
- package/dist/module-architecture.js +0 -1
- package/dist/programmatic.js +18 -9
- package/dist/remove-module.js +1 -1
- package/dist/seam-refresh.d.ts +60 -0
- package/dist/seam-refresh.js +214 -0
- package/dist/spoke-checkout.d.ts +12 -3
- package/dist/spoke-checkout.js +14 -5
- package/dist/sync-routes.d.ts +10 -1
- package/dist/sync-routes.js +61 -6
- package/dist/template-record.d.ts +14 -2
- package/dist/template-record.js +60 -22
- package/dist/topology.js +3 -4
- package/dist/update.d.ts +13 -1
- package/dist/update.js +100 -8
- package/package.json +3 -3
- package/templates/.env.example +6 -0
- package/templates/.github/workflows/ci.yml +3 -0
- package/templates/apps/api/.env.example +12 -0
- package/templates/apps/api/CLAUDE.md +10 -7
- package/templates/apps/mcp/CLAUDE.md +25 -5
- package/templates/apps/web/.env.example +7 -1
- package/templates/apps/web/CLAUDE.md +40 -13
- package/templates/apps/web/app/[locale]/(authed)/account/connect/__tests__/page.test.tsx +1 -1
- package/templates/apps/web/app/[locale]/layout.tsx +41 -24
- package/templates/apps/web/app/api/revalidate/__tests__/route.test.ts +56 -1
- package/templates/apps/web/app/api/revalidate/route.ts +45 -4
- package/templates/apps/web/app/llms.txt/__tests__/site-listing.test.ts +60 -0
- package/templates/apps/web/app/llms.txt/route.ts +17 -4
- package/templates/apps/web/app/openapi.json/__tests__/route.test.ts +15 -7
- package/templates/apps/web/auth.config.tsx +2 -0
- package/templates/apps/web/auth.ts +28 -4
- package/templates/apps/web/jest.config.cjs +1 -1
- package/templates/apps/web/lib/__tests__/auth-email.test.ts +21 -0
- package/templates/apps/web/lib/__tests__/docs-path.test.ts +20 -2
- package/templates/apps/web/lib/__tests__/hub-site-config.test.ts +246 -0
- package/templates/apps/web/lib/__tests__/profile-back-link.test.ts +58 -0
- package/templates/apps/web/lib/__tests__/relay.test.ts +127 -12
- package/templates/apps/web/lib/__tests__/served-pages.test.ts +163 -20
- package/templates/apps/web/lib/__tests__/server-api.test.ts +72 -7
- package/templates/apps/web/lib/__tests__/services-path.test.ts +22 -1
- package/templates/apps/web/lib/__tests__/site-brand.test.ts +77 -0
- package/templates/apps/web/lib/__tests__/site-contact-lines.test.ts +64 -0
- package/templates/apps/web/lib/__tests__/site-identity-feature-list.test.ts +144 -4
- package/templates/apps/web/lib/auth-email.ts +19 -0
- package/templates/apps/web/lib/docs-path.ts +1 -1
- package/templates/apps/web/lib/hub-site-config.ts +154 -0
- package/templates/apps/web/lib/mcp-oauth.ts +123 -17
- package/templates/apps/web/lib/profile-back-link.ts +49 -12
- package/templates/apps/web/lib/relay.ts +48 -9
- package/templates/apps/web/lib/served-pages.ts +144 -39
- package/templates/apps/web/lib/server-api.ts +37 -4
- package/templates/apps/web/lib/services-path.ts +1 -1
- package/templates/apps/web/lib/site-brand.tsx +66 -0
- package/templates/apps/web/lib/site-contact-email.ts +24 -4
- package/templates/apps/web/lib/site-contact-lines.ts +20 -4
- package/templates/apps/web/lib/site-identity.ts +38 -2
- package/templates/apps/web/messages/en.json +13 -8
- package/templates/apps/web/middleware.ts +4 -2
- package/templates/apps/web/src/lib/routes.ts +13 -0
- package/templates/tools/declared-env.ts +6 -1
- package/versions.json +51 -51
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* through the content adapter when a page's JSON-LD is composed, never from a
|
|
8
8
|
* directory scan. Under the mdx adapter no reader is registered.
|
|
9
9
|
*/
|
|
10
|
-
import { mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
11
11
|
import { tmpdir } from "node:os";
|
|
12
12
|
import { join } from "node:path";
|
|
13
13
|
|
|
@@ -24,9 +24,26 @@ jest.mock("node:fs", () => {
|
|
|
24
24
|
});
|
|
25
25
|
|
|
26
26
|
const mockGetContentAdapter = jest.fn<Pick<ContentAdapter, "listPages">, []>();
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
27
|
+
// #11456 — the two registrations site-identity.ts makes, recorded per module
|
|
28
|
+
// registry (spies passing through to that registry's real renderer).
|
|
29
|
+
jest.mock("@working-theory/page-renderer", () => {
|
|
30
|
+
const actual = jest.requireActual<PageRenderer>("@working-theory/page-renderer");
|
|
31
|
+
return {
|
|
32
|
+
...actual,
|
|
33
|
+
getContentAdapter: () => mockGetContentAdapter(),
|
|
34
|
+
setSiteIdentity: jest.fn(actual.setSiteIdentity),
|
|
35
|
+
setSiteIdentityReader: jest.fn(actual.setSiteIdentityReader),
|
|
36
|
+
};
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
// #11456 — the hub read's HTTP call; the rest of the client stays real.
|
|
40
|
+
const mockSiteConfigGet = jest.fn();
|
|
41
|
+
jest.mock("@working-theory/api-client", () => ({
|
|
42
|
+
...jest.requireActual("@working-theory/api-client"),
|
|
43
|
+
siteConfig: { get: (...args: unknown[]) => mockSiteConfigGet(...args) },
|
|
44
|
+
}));
|
|
45
|
+
jest.mock("next/cache", () => ({
|
|
46
|
+
unstable_cache: (fn: () => Promise<unknown>) => fn,
|
|
30
47
|
}));
|
|
31
48
|
|
|
32
49
|
type Row = { type: string; slug: string; title: string; sections?: unknown[] };
|
|
@@ -143,6 +160,7 @@ describe("the featureList registration with no content directory (#10644 AC-2)",
|
|
|
143
160
|
|
|
144
161
|
afterEach(() => {
|
|
145
162
|
renderer?.setSiteFeatureListReader(undefined);
|
|
163
|
+
renderer?.setSiteIdentityReader(undefined);
|
|
146
164
|
renderer?.setSiteIdentity(undefined);
|
|
147
165
|
renderer = undefined;
|
|
148
166
|
rmSync(root, { recursive: true, force: true });
|
|
@@ -193,4 +211,126 @@ describe("the featureList registration with no content directory (#10644 AC-2)",
|
|
|
193
211
|
expect(appNode(result as Record<string, unknown>)).not.toHaveProperty("featureList");
|
|
194
212
|
expect(mockGetContentAdapter).toHaveBeenCalledTimes(0);
|
|
195
213
|
});
|
|
214
|
+
|
|
215
|
+
describe("the hub identity reader (#11456 D4, AC-2)", () => {
|
|
216
|
+
const HUB_IDENTITY = {
|
|
217
|
+
kind: "Organization",
|
|
218
|
+
name: "Hub Co",
|
|
219
|
+
// Another origin: no workspace value may move an `@id` (SEC-11456-6).
|
|
220
|
+
url: "https://elsewhere.example",
|
|
221
|
+
description: "The hub's description.",
|
|
222
|
+
sameAs: ["https://social.example/hub"],
|
|
223
|
+
};
|
|
224
|
+
const savedHub = {
|
|
225
|
+
key: process.env.AILK_SPOKE_KEY,
|
|
226
|
+
api: process.env.AILK_API_URL,
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
function hubConnect(): void {
|
|
230
|
+
process.env.AILK_SPOKE_KEY = "ailk_spk_TESTKEYxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
|
|
231
|
+
process.env.AILK_API_URL = "https://hub.example";
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** The registrations the last `loadSiteIdentity()` made. */
|
|
235
|
+
const calls = (name: "setSiteIdentity" | "setSiteIdentityReader") =>
|
|
236
|
+
jest.mocked(loadedRenderer![name]).mock.calls;
|
|
237
|
+
let loadedRenderer: PageRenderer | undefined;
|
|
238
|
+
const load = (): PageRenderer => {
|
|
239
|
+
// The mocked renderer is one instance across registries: forget the
|
|
240
|
+
// registrations earlier loads made.
|
|
241
|
+
const shared = jest.requireMock<PageRenderer>("@working-theory/page-renderer");
|
|
242
|
+
jest.mocked(shared.setSiteIdentity).mockClear();
|
|
243
|
+
jest.mocked(shared.setSiteIdentityReader).mockClear();
|
|
244
|
+
return (loadedRenderer = loadSiteIdentity());
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
beforeEach(() => {
|
|
248
|
+
mockSiteConfigGet.mockReset();
|
|
249
|
+
mockSiteConfigGet.mockResolvedValue({ ok: true, body: { identity: HUB_IDENTITY, seo: null } });
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
afterEach(() => {
|
|
253
|
+
restore("AILK_SPOKE_KEY", savedHub.key);
|
|
254
|
+
restore("AILK_API_URL", savedHub.api);
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
it("hub-connected: registers a reader carrying the hub identity on the file's baseUrl; every @id stays on the file's origin", async () => {
|
|
258
|
+
hubConnect();
|
|
259
|
+
delete process.env.NEXT_PUBLIC_SITE_URL;
|
|
260
|
+
const renderer = load();
|
|
261
|
+
|
|
262
|
+
expect(calls("setSiteIdentityReader")).toHaveLength(1);
|
|
263
|
+
const reader = calls("setSiteIdentityReader")[0]![0] as () => Promise<unknown>;
|
|
264
|
+
await expect(reader()).resolves.toEqual({
|
|
265
|
+
siteName: "Hub Co",
|
|
266
|
+
baseUrl: ORIGIN,
|
|
267
|
+
identity: HUB_IDENTITY,
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
const result = (await renderer.pageToJsonLd(
|
|
271
|
+
{ type: "AboutPage", slug: "about", title: "About" } as Parameters<PageRenderer["pageToJsonLd"]>[0],
|
|
272
|
+
"en",
|
|
273
|
+
)) as Record<string, unknown>;
|
|
274
|
+
const graph = (result["@graph"] ?? []) as Array<Record<string, unknown>>;
|
|
275
|
+
expect(graph.find((n) => n["@type"] === "Organization")).toMatchObject({
|
|
276
|
+
"@id": `${ORIGIN}/#organization`,
|
|
277
|
+
name: "Hub Co",
|
|
278
|
+
description: "The hub's description.",
|
|
279
|
+
sameAs: ["https://social.example/hub"],
|
|
280
|
+
});
|
|
281
|
+
const ids = graph.map((n) => n["@id"]).filter((id): id is string => typeof id === "string");
|
|
282
|
+
expect(ids.length).toBeGreaterThan(0);
|
|
283
|
+
for (const id of ids) expect(id.startsWith(`${ORIGIN}/`)).toBe(true);
|
|
284
|
+
expect(JSON.stringify(result)).not.toContain("elsewhere.example/#");
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
it("hub-connected with no hub identity row: the reader answers undefined, so the file registration composes", async () => {
|
|
288
|
+
hubConnect();
|
|
289
|
+
mockSiteConfigGet.mockResolvedValue({ ok: true, body: { identity: null, seo: null } });
|
|
290
|
+
load();
|
|
291
|
+
const reader = calls("setSiteIdentityReader")[0]![0] as () => Promise<unknown>;
|
|
292
|
+
await expect(reader()).resolves.toBeUndefined();
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
// #11515 — a file-content site with a key reads the hub, and the file's
|
|
296
|
+
// scanned featureList rides a hub identity that carries a product.
|
|
297
|
+
const HUB_PRODUCT_IDENTITY = {
|
|
298
|
+
...HUB_IDENTITY,
|
|
299
|
+
secondary: { kind: "SoftwareApplication", name: "Hub App", url: `${ORIGIN}/app` },
|
|
300
|
+
};
|
|
301
|
+
it.each([
|
|
302
|
+
["a product: the file's featureList rides it", HUB_PRODUCT_IDENTITY, ["File A", "File B"]],
|
|
303
|
+
["no product: no featureList", HUB_IDENTITY, undefined],
|
|
304
|
+
])("hub-connected with a spoke key and CONTENT_ADAPTER unset, a hub identity with %s (#11515)", async (_label, identity, featureList) => {
|
|
305
|
+
hubConnect();
|
|
306
|
+
delete process.env.CONTENT_ADAPTER;
|
|
307
|
+
mkdirSync(join(root, "en", "Feature"), { recursive: true });
|
|
308
|
+
writeFileSync(join(root, "en", "Feature", "b.mdx"), "---\ntitle: File B\n---\n");
|
|
309
|
+
writeFileSync(join(root, "en", "Feature", "a.mdx"), "---\ntitle: File A\n---\n");
|
|
310
|
+
mockSiteConfigGet.mockResolvedValue({ ok: true, body: { identity, seo: null } });
|
|
311
|
+
load();
|
|
312
|
+
expect(calls("setSiteIdentityReader")).toHaveLength(1);
|
|
313
|
+
const reader = calls("setSiteIdentityReader")[0]![0] as () => Promise<unknown>;
|
|
314
|
+
await expect(reader()).resolves.toEqual({
|
|
315
|
+
siteName: "Hub Co",
|
|
316
|
+
baseUrl: ORIGIN,
|
|
317
|
+
identity,
|
|
318
|
+
...(featureList === undefined ? {} : { featureList }),
|
|
319
|
+
});
|
|
320
|
+
expect(mockSiteConfigGet).toHaveBeenCalledTimes(1);
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
it.each([
|
|
324
|
+
["CONTENT_ADAPTER unset", () => delete process.env.CONTENT_ADAPTER],
|
|
325
|
+
["CONTENT_ADAPTER=database", () => (process.env.CONTENT_ADAPTER = "database")],
|
|
326
|
+
])("not hub-connected (no AILK_SPOKE_KEY, %s): registers no reader, and setSiteIdentity receives the file registration", (_label, arrange) => {
|
|
327
|
+
hubConnect();
|
|
328
|
+
delete process.env.AILK_SPOKE_KEY;
|
|
329
|
+
arrange();
|
|
330
|
+
load();
|
|
331
|
+
expect(calls("setSiteIdentityReader")).toEqual([]);
|
|
332
|
+
expect(calls("setSiteIdentity")).toEqual([[readSiteIdentity(root)]]);
|
|
333
|
+
expect(mockSiteConfigGet).not.toHaveBeenCalled();
|
|
334
|
+
});
|
|
335
|
+
});
|
|
196
336
|
});
|
|
@@ -67,6 +67,8 @@ export interface AuthEmailPayload {
|
|
|
67
67
|
expiresInMinutes?: number;
|
|
68
68
|
agreements?: string[];
|
|
69
69
|
locale?: string;
|
|
70
|
+
/** The workspace a hub-sign-in site's link is sent for (workspace-email-sender-name). */
|
|
71
|
+
workspaceId?: string;
|
|
70
72
|
}
|
|
71
73
|
|
|
72
74
|
export interface AuthEmailRequest {
|
|
@@ -137,6 +139,9 @@ export function buildAuthEmailRequest(
|
|
|
137
139
|
? { agreements: payload.agreements }
|
|
138
140
|
: {}),
|
|
139
141
|
...(payload.locale !== undefined ? { locale: payload.locale } : {}),
|
|
142
|
+
...(payload.workspaceId !== undefined
|
|
143
|
+
? { workspaceId: payload.workspaceId }
|
|
144
|
+
: {}),
|
|
140
145
|
});
|
|
141
146
|
const timestamp = String(Math.floor(Date.now() / 1000));
|
|
142
147
|
const signature = `sha256=${createHmac("sha256", secret)
|
|
@@ -496,6 +501,16 @@ export interface PurchaseCaptureStore {
|
|
|
496
501
|
*/
|
|
497
502
|
export const purchaseCapture = new AsyncLocalStorage<PurchaseCaptureStore>();
|
|
498
503
|
|
|
504
|
+
/**
|
|
505
|
+
* The workspace a magic link is sent for (workspace-email-sender-name). The
|
|
506
|
+
* hub web's spoke-hosted email route runs `signInMagicLink` inside
|
|
507
|
+
* `senderWorkspace.run(workspaceId, …)` with the workspace the hub API read
|
|
508
|
+
* from the spoke's key, never a visitor value; `sendMagicLink` puts it on the
|
|
509
|
+
* signed payload, so the relay sends the link as "<workspace> via
|
|
510
|
+
* <organization>". Outside a run nothing changes.
|
|
511
|
+
*/
|
|
512
|
+
export const senderWorkspace = new AsyncLocalStorage<string>();
|
|
513
|
+
|
|
499
514
|
/**
|
|
500
515
|
* Magic-link token lifetime (#7435 § D2). Five minutes — the library default,
|
|
501
516
|
* and the number `packages/email`'s magic-link template already promises ("This
|
|
@@ -613,6 +628,8 @@ function makeSendMagicLink(deps: MagicLinkDeps) {
|
|
|
613
628
|
// A new address has no user yet; the relay only logs `userId`, so a
|
|
614
629
|
// sign-up link carries the fixed sentinel and the binding's ids, never
|
|
615
630
|
// the request's (#9720 D6).
|
|
631
|
+
const workspaceId = senderWorkspace.getStore();
|
|
632
|
+
const sender = workspaceId === undefined ? {} : { workspaceId };
|
|
616
633
|
let payload: AuthEmailPayload;
|
|
617
634
|
if (found) {
|
|
618
635
|
payload = {
|
|
@@ -620,6 +637,7 @@ function makeSendMagicLink(deps: MagicLinkDeps) {
|
|
|
620
637
|
userId: found.user.id,
|
|
621
638
|
to: found.user.email,
|
|
622
639
|
url: data.url,
|
|
640
|
+
...sender,
|
|
623
641
|
};
|
|
624
642
|
} else if (binding) {
|
|
625
643
|
payload = {
|
|
@@ -629,6 +647,7 @@ function makeSendMagicLink(deps: MagicLinkDeps) {
|
|
|
629
647
|
url: data.url,
|
|
630
648
|
agreements: binding.agreements,
|
|
631
649
|
locale: binding.locale,
|
|
650
|
+
...sender,
|
|
632
651
|
};
|
|
633
652
|
} else {
|
|
634
653
|
// No address in the line — the PII boundary holds for unknown addresses
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The hub read of the site's identity and seo (#11456, spec
|
|
3
|
+
* docs/specs/11456-a-hub-connected-site-reads-spec.md D3).
|
|
4
|
+
*
|
|
5
|
+
* A HUB-CONNECTED site — one with a spoke key that would go on the wire
|
|
6
|
+
* (`sendsSpokeKey()`), whatever its content adapter (#11515) — reads its
|
|
7
|
+
* identity and seo from `GET /v1/content/site-config`, which answers its own
|
|
8
|
+
* workspace's rows; a site serving file content with a key reads them too. A
|
|
9
|
+
* site with no key makes no call and keeps reading `content/_site.mdx`:
|
|
10
|
+
* without a key the route can only answer 401.
|
|
11
|
+
*
|
|
12
|
+
* Cached with Next's `unstable_cache` under `siteConfigTag()` for at most
|
|
13
|
+
* `HUB_SITE_REVALIDATE_SECONDS`. The `site-config` revalidate event an Admin
|
|
14
|
+
* save fires purges the tag (`app/api/revalidate/route.ts`); the expiry is the
|
|
15
|
+
* safety net for a spoke with no `revalidateUrl`. The key parts carry a
|
|
16
|
+
* digest of the spoke key — never the key — so two deployments with different
|
|
17
|
+
* keys sharing one data cache never share an entry (SEC-11456-2).
|
|
18
|
+
*
|
|
19
|
+
* Inside the cached callback a non-2xx, a throw, a read slower than
|
|
20
|
+
* `HUB_SITE_TIMEOUT_MS` or a body without the two keys THROWS, so nothing is
|
|
21
|
+
* written and Next keeps serving the last entry (`page-renderer`'s
|
|
22
|
+
* `api-source.ts` failure rule). Outside, a failure answers this instance's
|
|
23
|
+
* last good value, else `undefined` — so a hub outage never reaches a page.
|
|
24
|
+
* The timeout does not abort the request (`http.ts`'s `get` takes no signal).
|
|
25
|
+
*
|
|
26
|
+
* One read per request: `readHubSite` is wrapped in React's `cache()`, so
|
|
27
|
+
* the layout's metadata, its render and every page's JSON-LD share it.
|
|
28
|
+
*
|
|
29
|
+
* `site-brand.tsx`, `site-identity.ts`, `site-contact-email.ts` and
|
|
30
|
+
* `site-contact-lines.ts` import this module; it imports none of them.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
import { createHash } from "node:crypto";
|
|
34
|
+
|
|
35
|
+
import { sendsSpokeKey, siteConfig } from "@working-theory/api-client";
|
|
36
|
+
import {
|
|
37
|
+
siteConfigTag,
|
|
38
|
+
siteWorkspaceSegment,
|
|
39
|
+
} from "@working-theory/page-renderer/edge";
|
|
40
|
+
import {
|
|
41
|
+
SEOSchema,
|
|
42
|
+
SiteIdentitySchema,
|
|
43
|
+
type SEO,
|
|
44
|
+
type SiteIdentity,
|
|
45
|
+
} from "@working-theory/site-config/schema";
|
|
46
|
+
import { cache } from "react";
|
|
47
|
+
import type { ZodType } from "zod";
|
|
48
|
+
|
|
49
|
+
/** The workspace's identity and seo rows as the site reads them; each `null` when absent or unreadable. */
|
|
50
|
+
export interface HubSite {
|
|
51
|
+
identity: SiteIdentity | null;
|
|
52
|
+
seo: SEO | null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** How long one hub read is served before it is read again. */
|
|
56
|
+
export const HUB_SITE_REVALIDATE_SECONDS = 300;
|
|
57
|
+
/** A read slower than this is a failed read. */
|
|
58
|
+
export const HUB_SITE_TIMEOUT_MS = 3_000;
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Whether this site reads its identity and seo from the hub: a spoke key on
|
|
62
|
+
* the wire, whatever the content adapter (#11515).
|
|
63
|
+
*/
|
|
64
|
+
export function hubConnected(): boolean {
|
|
65
|
+
return sendsSpokeKey();
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The last value `readHubSite` resolved on this instance. */
|
|
69
|
+
let held: HubSite | undefined;
|
|
70
|
+
|
|
71
|
+
function parsedOrNull<T>(schema: ZodType<T>, value: unknown): T | null {
|
|
72
|
+
const parsed = schema.safeParse(value);
|
|
73
|
+
return parsed.success ? parsed.data : null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** One hub read. Throws on any failure, so the cache writes nothing. */
|
|
77
|
+
async function fetchHubSite(): Promise<HubSite> {
|
|
78
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
79
|
+
const timeout = new Promise<never>((_resolve, reject) => {
|
|
80
|
+
timer = setTimeout(
|
|
81
|
+
() => reject(new Error("hub site-config read timed out")),
|
|
82
|
+
HUB_SITE_TIMEOUT_MS,
|
|
83
|
+
);
|
|
84
|
+
timer.unref?.();
|
|
85
|
+
});
|
|
86
|
+
try {
|
|
87
|
+
const res = await Promise.race([siteConfig.get(), timeout]);
|
|
88
|
+
if (!res.ok) throw new Error(`hub site-config read answered ${res.status}`);
|
|
89
|
+
const body: unknown = res.body;
|
|
90
|
+
if (
|
|
91
|
+
typeof body !== "object" ||
|
|
92
|
+
body === null ||
|
|
93
|
+
!("identity" in body) ||
|
|
94
|
+
!("seo" in body)
|
|
95
|
+
) {
|
|
96
|
+
throw new Error("hub site-config read answered no rows");
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
identity: parsedOrNull(SiteIdentitySchema, body.identity),
|
|
100
|
+
seo: parsedOrNull(SEOSchema, body.seo),
|
|
101
|
+
};
|
|
102
|
+
} finally {
|
|
103
|
+
clearTimeout(timer);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The first 16 hex of the spoke key's SHA-256 — a cache-key part, never the key. */
|
|
108
|
+
function spokeKeyDigest(): string {
|
|
109
|
+
return createHash("sha256")
|
|
110
|
+
.update((process.env.AILK_SPOKE_KEY ?? "").trim(), "utf8")
|
|
111
|
+
.digest("hex")
|
|
112
|
+
.slice(0, 16);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* The hub's identity and seo for this site, or `undefined` when the site is
|
|
117
|
+
* not hub-connected (no call made) or no read has ever succeeded here.
|
|
118
|
+
* Never rejects. Shared within one request (React `cache()`).
|
|
119
|
+
*/
|
|
120
|
+
export const readHubSite = cache(async function readHubSite(): Promise<
|
|
121
|
+
HubSite | undefined
|
|
122
|
+
> {
|
|
123
|
+
if (!hubConnected()) return undefined;
|
|
124
|
+
try {
|
|
125
|
+
// Loaded only on the hub-connected path, so a site that is not one loads
|
|
126
|
+
// nothing it did not load before.
|
|
127
|
+
const { unstable_cache } = await import("next/cache");
|
|
128
|
+
const read = unstable_cache(
|
|
129
|
+
fetchHubSite,
|
|
130
|
+
["ailk-hub-site-config", siteWorkspaceSegment(), spokeKeyDigest()],
|
|
131
|
+
{ tags: [siteConfigTag()], revalidate: HUB_SITE_REVALIDATE_SECONDS },
|
|
132
|
+
);
|
|
133
|
+
held = await read();
|
|
134
|
+
} catch (err) {
|
|
135
|
+
console.warn(
|
|
136
|
+
`[hub-site-config] read failed (${err instanceof Error ? err.name : typeof err}); serving the last good value`,
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
return held;
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* The last value `readHubSite` resolved on this instance (synchronous), for
|
|
144
|
+
* the readers whose seam is synchronous — the contact email and contact
|
|
145
|
+
* lines. `undefined` on a cold instance's first render.
|
|
146
|
+
*/
|
|
147
|
+
export function heldHubSite(): HubSite | undefined {
|
|
148
|
+
return hubConnected() ? held : undefined;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Test seam: forget the held value. */
|
|
152
|
+
export function __resetHubSiteForTests(): void {
|
|
153
|
+
held = undefined;
|
|
154
|
+
}
|
|
@@ -20,7 +20,13 @@
|
|
|
20
20
|
* - one issuer per token (#10912 D4): a server given an `issuerTag` binds
|
|
21
21
|
* `ailk:issuer:<tag>` beside the workspace, and every server's code
|
|
22
22
|
* exchange, refresh and token-info accept only their own tokens — none
|
|
23
|
-
* for a server with no tag, as a site's apps/web has
|
|
23
|
+
* for a server with no tag, as a site's apps/web has;
|
|
24
|
+
* - one sign-in for every workspace (#11607 D1a): a server given
|
|
25
|
+
* `allWorkspaces` (the Admin) binds `ailk:all-workspaces` in place of the
|
|
26
|
+
* one workspace, after a confirmation naming every workspace it reaches,
|
|
27
|
+
* and its token-info answers the person's live memberships at each call
|
|
28
|
+
* (D2). A server without it never binds one and treats such a token as
|
|
29
|
+
* another server's.
|
|
24
30
|
*
|
|
25
31
|
* Every refusal is code-shaped: no English string reaches a client. No answer
|
|
26
32
|
* or log line carries a token, code, verifier or client secret.
|
|
@@ -28,6 +34,7 @@
|
|
|
28
34
|
import { createHash, timingSafeEqual } from "node:crypto";
|
|
29
35
|
|
|
30
36
|
import {
|
|
37
|
+
ALL_WORKSPACES_SCOPE,
|
|
31
38
|
ISSUER_SCOPE_PREFIX,
|
|
32
39
|
lowerRole,
|
|
33
40
|
MCP_SCOPES,
|
|
@@ -76,6 +83,12 @@ export interface McpOAuthDeps {
|
|
|
76
83
|
* entry, and only such tokens are this server's.
|
|
77
84
|
*/
|
|
78
85
|
issuerTag?: string;
|
|
86
|
+
/**
|
|
87
|
+
* Bind `ailk:all-workspaces` at consent in place of one workspace (#11607
|
|
88
|
+
* D1a) — the Admin's. Absent: today's one-workspace consent, and a token
|
|
89
|
+
* carrying the entry is not this server's. Requires `issuerTag`.
|
|
90
|
+
*/
|
|
91
|
+
allWorkspaces?: boolean;
|
|
79
92
|
}
|
|
80
93
|
|
|
81
94
|
/** The scopes `/mcp/authorize` accepts a request for. */
|
|
@@ -228,6 +241,8 @@ interface OAuthApplicationRow {
|
|
|
228
241
|
createdAt: Date;
|
|
229
242
|
}
|
|
230
243
|
|
|
244
|
+
// The plugin stores both tokens as it is given them and validates by lookup on
|
|
245
|
+
// those columns; hashing them would mean patching it. Accepted (#10459 D7).
|
|
231
246
|
interface OAuthAccessTokenRow {
|
|
232
247
|
accessToken: string;
|
|
233
248
|
refreshToken: string;
|
|
@@ -248,6 +263,12 @@ function parseValue(raw: string): AuthorizationValue | null {
|
|
|
248
263
|
}
|
|
249
264
|
|
|
250
265
|
export function mcpOAuthPlugin(deps: McpOAuthDeps) {
|
|
266
|
+
// An untagged server's all-workspaces token is one no API honours (#11607
|
|
267
|
+
// D1a): refuse to build it at all.
|
|
268
|
+
if (deps.allWorkspaces === true && !deps.issuerTag) {
|
|
269
|
+
throw new Error("mcp_oauth_all_workspaces_requires_issuer_tag");
|
|
270
|
+
}
|
|
271
|
+
const allWorkspaces = deps.allWorkspaces === true;
|
|
251
272
|
type AuthCtx = Parameters<Parameters<typeof createAuthMiddleware>[0]>[0]["context"];
|
|
252
273
|
/** What the helpers below need of an endpoint's or a hook's context. */
|
|
253
274
|
interface Ctx {
|
|
@@ -295,7 +316,7 @@ export function mcpOAuthPlugin(deps: McpOAuthDeps) {
|
|
|
295
316
|
});
|
|
296
317
|
}
|
|
297
318
|
|
|
298
|
-
/** Bounded cleanup
|
|
319
|
+
/** Bounded cleanup after an accepted consent (SEC-10357-03, #10459 D4). */
|
|
299
320
|
async function sweep(ctx: Ctx): Promise<void> {
|
|
300
321
|
const adapter = ctx.context.adapter;
|
|
301
322
|
await adapter.deleteMany({
|
|
@@ -333,9 +354,29 @@ export function mcpOAuthPlugin(deps: McpOAuthDeps) {
|
|
|
333
354
|
}
|
|
334
355
|
}
|
|
335
356
|
|
|
336
|
-
/**
|
|
357
|
+
/**
|
|
358
|
+
* Whether a token or code's scopes are this server's own (#10912 D4): its
|
|
359
|
+
* issuer entry, and an `ailk:all-workspaces` entry only on a server that
|
|
360
|
+
* binds one (#11607 D1a).
|
|
361
|
+
*/
|
|
337
362
|
function ownsScopes(scopes: string | readonly string[]): boolean {
|
|
338
|
-
|
|
363
|
+
const joined = typeof scopes === "string" ? scopes : scopes.join(" ");
|
|
364
|
+
return (
|
|
365
|
+
tokenIssuedBy(joined, deps.issuerTag) && (allWorkspaces || !joined.split(" ").includes(ALL_WORKSPACES_SCOPE))
|
|
366
|
+
);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* The all-workspaces consent's union (#11607 D1a): every workspace, and the
|
|
371
|
+
* requested scopes any of the person's roles may approve, in `MCP_SCOPES` order.
|
|
372
|
+
*/
|
|
373
|
+
async function offeredReach(userId: string, requested: string[]) {
|
|
374
|
+
const workspaces = await offeredWorkspaces(userId, requested);
|
|
375
|
+
const union = new Set(workspaces.flatMap((w) => w.offered));
|
|
376
|
+
return {
|
|
377
|
+
workspaces: workspaces.map(({ id, name, organizationName, role }) => ({ id, name, organizationName, role })),
|
|
378
|
+
offered: MCP_SCOPES.filter((s) => union.has(s)),
|
|
379
|
+
};
|
|
339
380
|
}
|
|
340
381
|
|
|
341
382
|
async function deleteTokensOf(ctx: Ctx, where: Array<{ field: string; value: string }>): Promise<number> {
|
|
@@ -359,6 +400,8 @@ export function mcpOAuthPlugin(deps: McpOAuthDeps) {
|
|
|
359
400
|
}
|
|
360
401
|
const scopes = typeof query.scope === "string" ? query.scope.split(" ").filter(Boolean) : [];
|
|
361
402
|
if (scopes.some((s) => !REQUESTABLE_SCOPES.has(s))) throw refuse("BAD_REQUEST", "invalid_scope");
|
|
403
|
+
// The plugin never reads the consent row, so this forced prompt is
|
|
404
|
+
// what makes a revoked client ask the person again (#10459 D2).
|
|
362
405
|
return { context: { query: { ...query, prompt: "consent" } } };
|
|
363
406
|
}),
|
|
364
407
|
},
|
|
@@ -387,12 +430,19 @@ export function mcpOAuthPlugin(deps: McpOAuthDeps) {
|
|
|
387
430
|
) {
|
|
388
431
|
throw refuse("BAD_REQUEST", "invalid_client_metadata");
|
|
389
432
|
}
|
|
390
|
-
// The register endpoint answers with a raw Response, which skips
|
|
391
|
-
// every after-hook, so the sweep runs here.
|
|
392
|
-
await sweep(ctx);
|
|
393
433
|
return { context: { body: { ...body, client_name: normaliseClientName(body.client_name) } } };
|
|
394
434
|
}),
|
|
395
435
|
},
|
|
436
|
+
{
|
|
437
|
+
matcher: (ctx) => ctx.path === "/change-password",
|
|
438
|
+
// A changed password signs the person's other devices out; the
|
|
439
|
+
// caller gets a new session (#10459 D5). The after-hook below then
|
|
440
|
+
// ends their MCP tokens, so no surviving session can approve a
|
|
441
|
+
// code in between.
|
|
442
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
443
|
+
return { context: { body: { ...bodyOf(ctx.body), revokeOtherSessions: true } } };
|
|
444
|
+
}),
|
|
445
|
+
},
|
|
396
446
|
{
|
|
397
447
|
matcher: (ctx) => ctx.path === "/mcp/token",
|
|
398
448
|
handler: createAuthMiddleware(async (ctx) => {
|
|
@@ -488,8 +538,19 @@ export function mcpOAuthPlugin(deps: McpOAuthDeps) {
|
|
|
488
538
|
model: "oauthAccessToken",
|
|
489
539
|
where: [{ field: "refreshToken", value: body.refresh_token }],
|
|
490
540
|
});
|
|
491
|
-
|
|
492
|
-
|
|
541
|
+
// The delete is the check: only the refresh that removes the used
|
|
542
|
+
// row keeps its pair. A row already gone — deleted after the
|
|
543
|
+
// plugin read it by a revoke, a password change or a concurrent
|
|
544
|
+
// refresh of the same token — refuses, and the pair the plugin
|
|
545
|
+
// just minted is deleted, so the client never holds it
|
|
546
|
+
// (SEC-10393-01, #10459 D1).
|
|
547
|
+
const rotated = used
|
|
548
|
+
? await deleteTokensOf(ctx, [{ field: "refreshToken", value: body.refresh_token }])
|
|
549
|
+
: 0;
|
|
550
|
+
if (!used || rotated === 0) {
|
|
551
|
+
await deleteTokensOf(ctx, [{ field: "accessToken", value: returned.access_token }]);
|
|
552
|
+
throw refuse("BAD_REQUEST", "invalid_grant");
|
|
553
|
+
}
|
|
493
554
|
await ctx.context.internalAdapter.createVerificationValue({
|
|
494
555
|
identifier: ROTATED_PREFIX + sha256(body.refresh_token),
|
|
495
556
|
value: JSON.stringify({ userId: used.userId, clientId: used.clientId }),
|
|
@@ -550,8 +611,12 @@ export function mcpOAuthPlugin(deps: McpOAuthDeps) {
|
|
|
550
611
|
where: [{ field: "clientId", value: value.clientId }],
|
|
551
612
|
});
|
|
552
613
|
if (!client) throw refuse("NOT_FOUND", "invalid_request");
|
|
614
|
+
const shown = { name: normaliseClientName(client.name), redirectOrigin: redirectOriginOf(value.redirectURI) };
|
|
615
|
+
if (allWorkspaces) {
|
|
616
|
+
return ctx.json({ client: shown, allWorkspaces: true, ...(await offeredReach(userId, value.scope)) });
|
|
617
|
+
}
|
|
553
618
|
return ctx.json({
|
|
554
|
-
client:
|
|
619
|
+
client: shown,
|
|
555
620
|
workspaces: await offeredWorkspaces(userId, value.scope),
|
|
556
621
|
});
|
|
557
622
|
},
|
|
@@ -583,12 +648,25 @@ export function mcpOAuthPlugin(deps: McpOAuthDeps) {
|
|
|
583
648
|
return ctx.json({ redirectURI: redirect.toString() });
|
|
584
649
|
}
|
|
585
650
|
|
|
586
|
-
const workspace = (await offeredWorkspaces(userId, value.scope)).find(
|
|
587
|
-
(w) => w.id === ctx.body.workspace_id,
|
|
588
|
-
);
|
|
589
651
|
const chosen = ctx.body.scopes ?? [];
|
|
590
|
-
|
|
591
|
-
|
|
652
|
+
let binding: string;
|
|
653
|
+
if (allWorkspaces) {
|
|
654
|
+
// The reach is every workspace, so naming one is a client of the
|
|
655
|
+
// single-workspace consent (#11607 D1a).
|
|
656
|
+
if (ctx.body.workspace_id !== undefined) throw refuse("BAD_REQUEST", "invalid_request");
|
|
657
|
+
const reach = await offeredReach(userId, value.scope);
|
|
658
|
+
if (reach.workspaces.length === 0 || chosen.some((s) => !(reach.offered as string[]).includes(s))) {
|
|
659
|
+
throw refuse("BAD_REQUEST", "invalid_scope");
|
|
660
|
+
}
|
|
661
|
+
binding = ALL_WORKSPACES_SCOPE;
|
|
662
|
+
} else {
|
|
663
|
+
const workspace = (await offeredWorkspaces(userId, value.scope)).find(
|
|
664
|
+
(w) => w.id === ctx.body.workspace_id,
|
|
665
|
+
);
|
|
666
|
+
if (!workspace || chosen.some((s) => !(workspace.offered as string[]).includes(s))) {
|
|
667
|
+
throw refuse("BAD_REQUEST", "invalid_scope");
|
|
668
|
+
}
|
|
669
|
+
binding = WORKSPACE_SCOPE_PREFIX + workspace.id;
|
|
592
670
|
}
|
|
593
671
|
|
|
594
672
|
// The plugin's token endpoint treats anything but "public" as
|
|
@@ -611,9 +689,11 @@ export function mcpOAuthPlugin(deps: McpOAuthDeps) {
|
|
|
611
689
|
|
|
612
690
|
// `openid`, `profile` and `email` are never bound: no id_token.
|
|
613
691
|
const scope = [
|
|
692
|
+
// Always bound: the plugin issues and refreshes only for it, and
|
|
693
|
+
// AILK's refresh tokens rotate and are revocable. Accepted (#10459 D6).
|
|
614
694
|
"offline_access",
|
|
615
695
|
...new Set(chosen),
|
|
616
|
-
|
|
696
|
+
binding,
|
|
617
697
|
// The issuer entry, only on a server that has a tag (#10912 D4).
|
|
618
698
|
...(deps.issuerTag ? [ISSUER_SCOPE_PREFIX + deps.issuerTag] : []),
|
|
619
699
|
];
|
|
@@ -640,6 +720,10 @@ export function mcpOAuthPlugin(deps: McpOAuthDeps) {
|
|
|
640
720
|
updatedAt: new Date(),
|
|
641
721
|
},
|
|
642
722
|
});
|
|
723
|
+
// The register endpoint answers a raw Response, which skips every
|
|
724
|
+
// after-hook, and is anonymous; so the sweep runs here, after a
|
|
725
|
+
// signed-in approval, in the background (#10459 D4).
|
|
726
|
+
await ctx.context.runInBackgroundOrAwait(sweep(ctx));
|
|
643
727
|
expireCookie(ctx, { name: CONSENT_COOKIE, attributes: { path: "/" } });
|
|
644
728
|
redirect.searchParams.set("code", code);
|
|
645
729
|
if (value.state) redirect.searchParams.set("state", value.state);
|
|
@@ -724,7 +808,29 @@ export function mcpOAuthPlugin(deps: McpOAuthDeps) {
|
|
|
724
808
|
if (!row || new Date(row.accessTokenExpiresAt) < new Date() || !row.userId) throw invalid();
|
|
725
809
|
// Another issuer's token answers as an unknown one (#10912 D4).
|
|
726
810
|
if (!ownsScopes(row.scopes)) throw invalid();
|
|
727
|
-
const
|
|
811
|
+
const granted = parseGrantedScopes(row.scopes);
|
|
812
|
+
if (granted.allWorkspaces) {
|
|
813
|
+
// The reach is the live membership set, read now — never a list
|
|
814
|
+
// held from consent (#11607 D2). None left: nothing to reach.
|
|
815
|
+
const memberships = await deps.readMemberships(row.userId);
|
|
816
|
+
if (memberships.length === 0) throw invalid();
|
|
817
|
+
return ctx.json({
|
|
818
|
+
active: true,
|
|
819
|
+
userId: row.userId,
|
|
820
|
+
clientId: row.clientId,
|
|
821
|
+
allWorkspaces: true,
|
|
822
|
+
workspaces: memberships.map((m) => ({
|
|
823
|
+
workspaceId: m.workspaceId,
|
|
824
|
+
workspaceName: m.workspaceName,
|
|
825
|
+
organizationName: m.organizationName,
|
|
826
|
+
role: m.role,
|
|
827
|
+
actingRole: lowerRole(m.role as MembershipRole, "member"),
|
|
828
|
+
grants: grantsForWorkspace(row.scopes, m.workspaceId, m.role) ?? [],
|
|
829
|
+
})),
|
|
830
|
+
expiresAt: new Date(row.accessTokenExpiresAt).toISOString(),
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
const { workspaceId } = granted;
|
|
728
834
|
if (!workspaceId) throw invalid();
|
|
729
835
|
const membership = (await deps.readMemberships(row.userId)).find((m) => m.workspaceId === workspaceId);
|
|
730
836
|
if (!membership) throw invalid();
|