akanjs 3.1.0-rc.21 → 3.1.0-rc.22

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 (109) hide show
  1. package/client/cookie.ts +5 -0
  2. package/client/csrLocation.ts +17 -72
  3. package/client/csrTypes.ts +17 -4
  4. package/client/route/PageDefinition.ts +103 -10
  5. package/client/route/RouteDefinition.ts +44 -3
  6. package/client/route/RouteGuards.ts +64 -0
  7. package/client/route/index.ts +1 -0
  8. package/client/route/resolveRouteModule.ts +8 -0
  9. package/client/route/routeArgs.ts +9 -0
  10. package/client/router.ts +11 -0
  11. package/common/authCookie.ts +13 -0
  12. package/common/authToken.ts +1 -12
  13. package/common/index.ts +2 -8
  14. package/common/routeConvention.ts +2 -0
  15. package/constant/inputParser.ts +1 -1
  16. package/dictionary/base.dictionary.ts +8 -0
  17. package/fetch/appScope.ts +54 -0
  18. package/fetch/client/fetchClient.ts +46 -29
  19. package/fetch/index.ts +1 -0
  20. package/package.json +1 -1
  21. package/server/mcp/McpApps.ts +44 -50
  22. package/server/mcp/McpPages.ts +93 -19
  23. package/server/mcp/McpRouter.ts +14 -11
  24. package/server/ops/migrateJobs.ts +145 -0
  25. package/server/ops/opsRoute.ts +39 -7
  26. package/server/ops/opsToken.ts +7 -2
  27. package/server/routeElementComposer.tsx +33 -6
  28. package/server/routeTreeBuilder.ts +5 -0
  29. package/server/rscClient.tsx +20 -0
  30. package/server/rscPagePrompts.ts +66 -16
  31. package/server/rscWorker.tsx +33 -11
  32. package/server/rscWorkerHost.ts +12 -1
  33. package/server/webRouter.ts +31 -27
  34. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +12 -1
  35. package/service/predefinedAdaptor/sql/dialect/postgres.ts +4 -3
  36. package/service/predefinedAdaptor/sql/dialect/sqlite.ts +2 -2
  37. package/service/predefinedAdaptor/sql/types.ts +2 -0
  38. package/service/predefinedAdaptor/sql/values.ts +19 -0
  39. package/signal/mcp/mcpProtocol.ts +7 -0
  40. package/signal/mcp/pagePrompt.ts +18 -1
  41. package/types/client/csrLocation.d.ts +3 -7
  42. package/types/client/csrTypes.d.ts +20 -3
  43. package/types/client/route/PageDefinition.d.ts +21 -4
  44. package/types/client/route/RouteDefinition.d.ts +4 -0
  45. package/types/client/route/RouteGuards.d.ts +15 -0
  46. package/types/client/route/index.d.ts +1 -0
  47. package/types/client/route/resolveRouteModule.d.ts +2 -0
  48. package/types/client/route/routeArgs.d.ts +5 -0
  49. package/types/client/route/routeBuilders.d.ts +1 -1
  50. package/types/client/router.d.ts +3 -0
  51. package/types/common/authCookie.d.ts +5 -0
  52. package/types/common/authToken.d.ts +0 -5
  53. package/types/common/index.d.ts +2 -1
  54. package/types/dictionary/base.dictionary.d.ts +1 -1
  55. package/types/dictionary/dictionary.d.ts +3 -3
  56. package/types/fetch/appScope.d.ts +18 -0
  57. package/types/fetch/client/fetchClient.d.ts +1 -1
  58. package/types/fetch/index.d.ts +1 -0
  59. package/types/server/mcp/McpApps.d.ts +14 -8
  60. package/types/server/mcp/McpPages.d.ts +6 -3
  61. package/types/server/ops/migrateJobs.d.ts +36 -0
  62. package/types/server/ops/opsRoute.d.ts +4 -1
  63. package/types/server/ops/opsToken.d.ts +3 -0
  64. package/types/server/routeElementComposer.d.ts +10 -1
  65. package/types/server/rscPagePrompts.d.ts +3 -1
  66. package/types/server/rscWorkerHost.d.ts +2 -1
  67. package/types/server/webRouter.d.ts +3 -0
  68. package/types/service/predefinedAdaptor/sql/dialect/postgres.d.ts +1 -1
  69. package/types/service/predefinedAdaptor/sql/dialect/sqlite.d.ts +1 -1
  70. package/types/service/predefinedAdaptor/sql/types.d.ts +2 -0
  71. package/types/service/predefinedAdaptor/sql/values.d.ts +1 -0
  72. package/types/signal/mcp/mcpProtocol.d.ts +6 -0
  73. package/types/signal/mcp/pagePrompt.d.ts +16 -0
  74. package/types/ui/Layout/FrameSlotPortal.d.ts +1 -1
  75. package/types/ui/System/App.d.ts +17 -0
  76. package/types/ui/System/index.d.ts +2 -0
  77. package/types/ui/recipe/badgeRecipe.d.ts +2 -2
  78. package/types/ui/recipe/buttonRecipe.d.ts +2 -2
  79. package/types/vendor/@akanjs/native/packages/cli/src/lib/toolchains.d.ts +1 -1
  80. package/types/webkit/CsrGuards.d.ts +25 -0
  81. package/types/webkit/CsrStack.d.ts +6 -0
  82. package/types/webkit/McpAppBoot.d.ts +32 -0
  83. package/types/webkit/McpAppBridge.d.ts +10 -1
  84. package/types/webkit/McpAppFetchBridge.d.ts +3 -1
  85. package/types/webkit/McpAppView.d.ts +4 -1
  86. package/types/webkit/RenderLayer.d.ts +1 -3
  87. package/types/webkit/index.d.ts +1 -0
  88. package/ui/Layout/BottomInset.tsx +2 -11
  89. package/ui/Layout/FrameSlotPortal.tsx +1 -3
  90. package/ui/Layout/Navbar.tsx +7 -22
  91. package/ui/Layout/TopInset.tsx +3 -4
  92. package/ui/System/App.tsx +43 -0
  93. package/ui/System/CSR.tsx +1 -10
  94. package/ui/System/index.tsx +3 -0
  95. package/vendor/@akanjs/native/packages/cli/src/lib/toolchains.ts +1 -1
  96. package/webkit/CsrGuards.ts +112 -0
  97. package/webkit/CsrRouteTable.ts +8 -12
  98. package/webkit/CsrStack.ts +29 -1
  99. package/webkit/McpAppBoot.tsx +129 -0
  100. package/webkit/McpAppBridge.ts +30 -6
  101. package/webkit/McpAppFetchBridge.ts +6 -1
  102. package/webkit/McpAppView.ts +39 -28
  103. package/webkit/RenderLayer.tsx +98 -41
  104. package/webkit/bootCsr.tsx +4 -43
  105. package/webkit/index.ts +1 -0
  106. package/webkit/useCsrValues.ts +55 -6
  107. package/webkit/useLocation.ts +1 -2
  108. package/types/webkit/EmbeddedLayout.d.ts +0 -10
  109. package/webkit/EmbeddedLayout.tsx +0 -82
@@ -106,8 +106,8 @@ export class McpRouter {
106
106
 
107
107
  this.#dispatcher = new McpDispatcher({ ...props, legacyTextBlock, language: props.language ?? defaultLanguage });
108
108
  this.#auth = new McpAuth({ ...props.auth, path: props.path ?? "/mcp" });
109
-
110
- this.#apps = props.apps && props.pagePrompts && !props.readOnly ? new McpApps(props.appShell ?? null) : null;
109
+ this.#apps =
110
+ props.apps && props.pagePrompts ? new McpApps(props.appShell ?? null, { readOnly: props.readOnly }) : null;
111
111
  const cache = props.registry.adaptor.get(CacheAdaptorRole) as (McpSharedCounter & McpUiSessionStore) | undefined;
112
112
  this.#pages = new McpPages({
113
113
  source: props.pagePrompts,
@@ -119,13 +119,14 @@ export class McpRouter {
119
119
  logger: McpRouter.logger,
120
120
  promptBudget: props.promptBudget,
121
121
  language: props.language,
122
+ readOnly: props.readOnly,
122
123
  });
123
124
  this.#limiter = props.rateLimit === false ? null : new McpRateLimiter(props.rateLimit, cache ?? null);
124
125
  }
125
126
 
126
127
  get #versions(): readonly McpProtocolVersion[] {
127
128
  const listed = this.#pages.listed;
128
- const views = !!this.#apps?.rendersUi && (listed === null || listed.length > 0);
129
+ const views = !!this.#apps?.rendersUi && (listed === null || listed.some((entry) => entry.kind === "app"));
129
130
  const modern = this.#props.modern ?? !views;
130
131
  return modern ? MCP_SUPPORTED_VERSIONS : McpRouter.#legacyVersions;
131
132
  }
@@ -167,10 +168,6 @@ export class McpRouter {
167
168
  McpRouter.logger.warn(
168
169
  "MCP is enabled but published nothing. Every candidate was refused; see the reasons below.",
169
170
  );
170
- if (this.#props.apps && this.#props.pagePrompts && this.#props.readOnly)
171
- McpRouter.logger.debug(
172
- "MCP Apps is off in this read-only deployment: a page tool would run the page's own `fetch.*` calls, mutations included.",
173
- );
174
171
  this.#pages.report();
175
172
  this.#reportUnverifiable(tools.map((tool) => tool.name));
176
173
  for (const { key, reason } of refusals) McpRouter.logger.verbose(`MCP did not expose "${key}": ${reason}`);
@@ -306,13 +303,19 @@ export class McpRouter {
306
303
  discoverCache,
307
304
  );
308
305
  case "tools/list":
309
- return await this.#list(call, "tools", [...document.tools, ...(await this.#pages.tools(call.ui, document))]);
306
+ return await this.#list(call, "tools", [
307
+ ...document.tools,
308
+ ...(await this.#pages.tools(call.ui, document, call.req)),
309
+ ]);
310
310
  case "resources/list":
311
- return await this.#list(call, "resources", [...document.resources, ...(await this.#pages.resources(call.ui))]);
311
+ return await this.#list(call, "resources", [
312
+ ...document.resources,
313
+ ...(await this.#pages.resources(call.ui, call.req)),
314
+ ]);
312
315
  case "resources/templates/list":
313
316
  return await this.#list(call, "resourceTemplates", document.resourceTemplates);
314
317
  case "prompts/list":
315
- return await this.#list(call, "prompts", await this.#pages.prompts());
318
+ return await this.#list(call, "prompts", await this.#pages.prompts(call.req));
316
319
  case "tools/call": {
317
320
  const slot = await this.#acquire(call);
318
321
  if ("refused" in slot) return slot.refused;
@@ -485,7 +488,7 @@ export class McpRouter {
485
488
  async #promptsGet(call: McpCall, document: McpDocument) {
486
489
  const name = call.params.name;
487
490
  if (typeof name !== "string") return McpRouter.#error(call.id, McpErrorCode.invalidParams, "Missing prompt name.");
488
- const entry = await this.#pages.entry(name);
491
+ const entry = await this.#pages.prompt(name);
489
492
  if (!entry) return McpRouter.#error(call.id, McpErrorCode.invalidParams, `Unknown prompt: ${name}.`);
490
493
  const page = await this.#pages.run(call, document, entry, McpRouter.#arguments(call.params));
491
494
  if ("badArguments" in page) return McpRouter.#error(call.id, McpErrorCode.invalidParams, McpRouter.#badArguments);
@@ -0,0 +1,145 @@
1
+ import { Logger } from "akanjs/common";
2
+ import { type MigrationAction, type MigrationCommandResult, migrationActions } from "../migration/migrationCommand";
3
+
4
+ export interface MigrateJobRequest {
5
+ id: string;
6
+ action: MigrationAction;
7
+ argv: string[];
8
+ }
9
+
10
+ export interface MigrateJobState {
11
+ id: string;
12
+ action: MigrationAction;
13
+ /** `done`: the command answered, and `result.ok` says how its run went; `failed`: it printed no result. */
14
+ status: "running" | "done" | "failed";
15
+ startedAt: string;
16
+ finishedAt?: string;
17
+ exitCode?: number;
18
+ result?: MigrationCommandResult;
19
+ error?: string;
20
+ }
21
+
22
+ export interface MigrateProcessOutput {
23
+ code: number;
24
+ stdout: string;
25
+ stderr: string;
26
+ }
27
+
28
+ /** `ops migrate` over the ops channel: one child at a time, its last line the job's result. */
29
+ export class MigrateJobs {
30
+ static readonly maxRemembered = 20;
31
+ static readonly idPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
32
+ static readonly targetPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
33
+ static readonly paramNamePattern = /^[A-Za-z][A-Za-z0-9_]*$/;
34
+ static readonly planHashPattern = /^[0-9a-f]{64}$/;
35
+ static readonly #fields = new Set(["id", "action", "target", "params", "expect", "items"]);
36
+
37
+ readonly #logger = new Logger("MigrateJobs");
38
+ readonly #jobs = new Map<string, MigrateJobState>();
39
+ readonly #run: (argv: string[]) => Promise<MigrateProcessOutput>;
40
+ #running: Promise<void> | null = null;
41
+
42
+ constructor(run: (argv: string[]) => Promise<MigrateProcessOutput>) {
43
+ this.#run = run;
44
+ }
45
+
46
+ static requestOf(body: unknown, actor: string | undefined): MigrateJobRequest | string {
47
+ if (!body || typeof body !== "object" || Array.isArray(body)) return "the body must be a JSON object";
48
+ const fields = body as Record<string, unknown>;
49
+ if ("actor" in fields) return "actor comes from the token's sub, never the body";
50
+ const unknown = Object.keys(fields).filter((key) => !MigrateJobs.#fields.has(key));
51
+ if (unknown.length) return `unknown fields: ${unknown.join(", ")}`;
52
+ const { id, action, target, params = {}, expect, items } = fields;
53
+ if (typeof id !== "string" || !MigrateJobs.idPattern.test(id))
54
+ return `id must match ${MigrateJobs.idPattern.source}`;
55
+ if (typeof action !== "string" || !migrationActions.includes(action as MigrationAction))
56
+ return `action must be one of ${migrationActions.join(", ")}`;
57
+ if ((action === "apply" || action === "rollback") && !actor)
58
+ return `${action} needs the token's sub, the person it runs for`;
59
+ if (target !== undefined && (typeof target !== "string" || !MigrateJobs.targetPattern.test(target)))
60
+ return `target must match ${MigrateJobs.targetPattern.source}`;
61
+ if (!params || typeof params !== "object" || Array.isArray(params)) return "params must map names to strings";
62
+ const entries = Object.entries(params);
63
+ if (entries.some(([name, value]) => !MigrateJobs.paramNamePattern.test(name) || typeof value !== "string"))
64
+ return "params must map names to strings";
65
+ if (expect !== undefined && (typeof expect !== "string" || !MigrateJobs.planHashPattern.test(expect)))
66
+ return "expect must be a planHash";
67
+ if (items !== undefined && (typeof items !== "number" || !Number.isInteger(items) || items < 0))
68
+ return "items must be a whole number";
69
+ const argv = [
70
+ action,
71
+ ...(target ? [target] : []),
72
+ ...entries.map(([name, value]) => `--param=${name}=${value as string}`),
73
+ ...(expect ? [`--expect=${expect}`] : []),
74
+ ...(items === undefined ? [] : [`--items=${items}`]),
75
+ ...(actor && action !== "list" ? [`--actor=${actor}`] : []),
76
+ "--json",
77
+ ];
78
+ return { id, action: action as MigrationAction, argv };
79
+ }
80
+
81
+ get(id: string) {
82
+ return this.#jobs.get(id) ?? null;
83
+ }
84
+
85
+ start(request: MigrateJobRequest): MigrateJobState | "busy" | "exists" {
86
+ if (this.#jobs.has(request.id)) return "exists";
87
+ if (this.#running) return "busy";
88
+ const job: MigrateJobState = {
89
+ id: request.id,
90
+ action: request.action,
91
+ status: "running",
92
+ startedAt: new Date().toISOString(),
93
+ };
94
+ this.#remember(job);
95
+ this.#running = this.#execute(job, request.argv).finally(() => {
96
+ this.#running = null;
97
+ });
98
+ return { ...job };
99
+ }
100
+
101
+ async idle() {
102
+ await this.#running;
103
+ }
104
+
105
+ async #execute(job: MigrateJobState, argv: string[]) {
106
+ try {
107
+ const { code, stdout, stderr } = await this.#run(argv);
108
+ const result = MigrateJobs.#resultOf(stdout);
109
+ if (!result)
110
+ throw new Error(MigrateJobs.#lastLine(stderr) || `ops migrate exited with ${code} and printed no result`);
111
+ job.exitCode = code;
112
+ job.result = result;
113
+ job.status = "done";
114
+ } catch (error) {
115
+ job.status = "failed";
116
+ job.error = error instanceof Error ? error.message : String(error);
117
+ this.#logger.error(`Migrate job ${job.id} failed: ${job.error}`);
118
+ } finally {
119
+ job.finishedAt = new Date().toISOString();
120
+ }
121
+ }
122
+
123
+ static #resultOf(stdout: string): MigrationCommandResult | null {
124
+ try {
125
+ const result = JSON.parse(MigrateJobs.#lastLine(stdout)) as unknown;
126
+ if (!result || typeof result !== "object" || typeof (result as { ok?: unknown }).ok !== "boolean") return null;
127
+ return result as MigrationCommandResult;
128
+ } catch {
129
+ return null;
130
+ }
131
+ }
132
+
133
+ static #lastLine(text: string) {
134
+ return text.trim().split("\n").at(-1)?.trim() ?? "";
135
+ }
136
+
137
+ #remember(job: MigrateJobState) {
138
+ this.#jobs.set(job.id, job);
139
+ while (this.#jobs.size > MigrateJobs.maxRemembered) {
140
+ const oldest = this.#jobs.keys().next().value;
141
+ if (oldest === undefined) break;
142
+ this.#jobs.delete(oldest);
143
+ }
144
+ }
145
+ }
@@ -2,7 +2,8 @@ import { Logger } from "akanjs/common";
2
2
  import { getEnv } from "../../base/baseEnv";
3
3
  import { SelfExec } from "../selfExec";
4
4
  import type { AppDetailInfo } from "./appInfo";
5
- import { OpsTokenVerifier } from "./opsToken";
5
+ import { MigrateJobs, type MigrateProcessOutput } from "./migrateJobs";
6
+ import { type OpsTokenClaims, OpsTokenVerifier } from "./opsToken";
6
7
  import { type SnapshotJobRequest, SnapshotJobs } from "./snapshotJobs";
7
8
  import type { SnapshotSources } from "./snapshotTypes";
8
9
  import { SqliteFiles } from "./sqliteFiles";
@@ -12,6 +13,7 @@ export interface OpsRouteOptions {
12
13
  verifier: OpsTokenVerifier;
13
14
  detail: () => AppDetailInfo;
14
15
  jobs: SnapshotJobs;
16
+ migrateJobs: MigrateJobs;
15
17
  rateLimitPerMinute?: number;
16
18
  }
17
19
 
@@ -27,13 +29,15 @@ export class OpsRoute {
27
29
  readonly #verifier: OpsTokenVerifier;
28
30
  readonly #detail: () => AppDetailInfo;
29
31
  readonly #jobs: SnapshotJobs;
32
+ readonly #migrateJobs: MigrateJobs;
30
33
  readonly #rateLimit: number;
31
34
  #window: number[] = [];
32
35
 
33
- constructor({ verifier, detail, jobs, rateLimitPerMinute = 30 }: OpsRouteOptions) {
36
+ constructor({ verifier, detail, jobs, migrateJobs, rateLimitPerMinute = 30 }: OpsRouteOptions) {
34
37
  this.#verifier = verifier;
35
38
  this.#detail = detail;
36
39
  this.#jobs = jobs;
40
+ this.#migrateJobs = migrateJobs;
37
41
  this.#rateLimit = rateLimitPerMinute;
38
42
  }
39
43
 
@@ -59,7 +63,8 @@ export class OpsRoute {
59
63
  capture: (request) => OpsRoute.captureInChild(request, sources(), snapshotDir),
60
64
  });
61
65
  logger.info(`Ops channel enabled for audience ${verifier.audience}`);
62
- return new OpsRoute({ verifier, detail, jobs });
66
+ const migrateJobs = new MigrateJobs((argv) => OpsRoute.migrateInChild(argv));
67
+ return new OpsRoute({ verifier, detail, jobs, migrateJobs });
63
68
  }
64
69
 
65
70
  static async captureInChild(request: SnapshotJobRequest, sources: SnapshotSources, dir: string) {
@@ -81,6 +86,20 @@ export class OpsRoute {
81
86
  return JSON.parse(lastLine) as SnapshotCapture;
82
87
  }
83
88
 
89
+ static async migrateInChild(argv: string[], script = Bun.main): Promise<MigrateProcessOutput> {
90
+ const proc = Bun.spawn(SelfExec.command(script, "ops", "migrate", ...argv), {
91
+ env: SelfExec.env(),
92
+ stdout: "pipe",
93
+ stderr: "pipe",
94
+ });
95
+ const [stdout, stderr, code] = await Promise.all([
96
+ new Response(proc.stdout).text(),
97
+ new Response(proc.stderr).text(),
98
+ proc.exited,
99
+ ]);
100
+ return { code, stdout, stderr };
101
+ }
102
+
84
103
  matches(pathname: string) {
85
104
  return pathname.startsWith(OpsRoute.prefix);
86
105
  }
@@ -96,14 +115,27 @@ export class OpsRoute {
96
115
  const route = url.pathname.slice(OpsRoute.prefix.length);
97
116
  if (route === "info" && req.method === "GET") return OpsRoute.#json(this.#detail(), 200);
98
117
  if (route === "snapshot" && req.method === "POST") return await this.#startSnapshot(req);
99
- const jobMatch = /^snapshot\/([^/]+)$/.exec(route);
100
- if (jobMatch?.[1] && req.method === "GET") {
101
- const job = this.#jobs.get(decodeURIComponent(jobMatch[1]));
102
- return job ? OpsRoute.#json(job, 200) : OpsRoute.#json({ error: "unknown snapshot" }, 404);
118
+ if (route === "migrate" && req.method === "POST") return await this.#startMigrate(req, verdict.claims);
119
+ const [kind, jobId, ...extra] = route.split("/");
120
+ if ((kind === "snapshot" || kind === "migrate") && jobId && !extra.length && req.method === "GET") {
121
+ const id = decodeURIComponent(jobId);
122
+ const job = kind === "snapshot" ? this.#jobs.get(id) : this.#migrateJobs.get(id);
123
+ if (job) return OpsRoute.#json(job, 200);
124
+ return OpsRoute.#json({ error: kind === "snapshot" ? "unknown snapshot" : "unknown migrate job" }, 404);
103
125
  }
104
126
  return OpsRoute.#json({ error: "not found" }, 404);
105
127
  }
106
128
 
129
+ async #startMigrate(req: Request, { sub }: OpsTokenClaims) {
130
+ const request = MigrateJobs.requestOf(await req.json().catch(() => null), sub);
131
+ if (typeof request === "string") return OpsRoute.#json({ error: request }, 400);
132
+ const started = this.#migrateJobs.start(request);
133
+ if (started === "exists") return OpsRoute.#json({ error: "migrate job id already used" }, 409);
134
+ if (started === "busy") return OpsRoute.#json({ error: "another migrate job is running" }, 409);
135
+ this.#logger.info(`Migrate job ${request.id} started: ${request.argv.slice(0, -1).join(" ")}`);
136
+ return OpsRoute.#json(started, 202);
137
+ }
138
+
107
139
  async #startSnapshot(req: Request) {
108
140
  const body = (await req.json().catch(() => null)) as {
109
141
  id?: unknown;
@@ -8,6 +8,8 @@ export interface OpsTokenClaims {
8
8
  exp: number;
9
9
  iat: number;
10
10
  jti: string;
11
+ /** Whom the control plane acts for: a migration run records it as its actor. */
12
+ sub?: string;
11
13
  }
12
14
 
13
15
  export type OpsTokenVerdict = { ok: true; claims: OpsTokenClaims } | { ok: false; reason: string };
@@ -16,6 +18,7 @@ export class OpsTokenVerifier {
16
18
  static readonly maxLifetimeSec = 300;
17
19
  static readonly clockSkewSec = 30;
18
20
  static readonly maxRememberedJti = 10_000;
21
+ static readonly subPattern = /^[\x21-\x7e]{1,128}$/;
19
22
 
20
23
  readonly audience: string;
21
24
  readonly #key: KeyObject;
@@ -44,14 +47,16 @@ export class OpsTokenVerifier {
44
47
  verify(token: string, nowSec = Math.floor(Date.now() / 1000)): OpsTokenVerdict {
45
48
  const verdict = EdDsaJwt.verify(token, this.#key, { audience: this.audience });
46
49
  if (!verdict.ok) return verdict;
47
- const { exp, iat, jti } = verdict.claims;
50
+ const { exp, iat, jti, sub } = verdict.claims;
48
51
  if (typeof exp !== "number" || typeof iat !== "number" || typeof jti !== "string" || !jti)
49
52
  return { ok: false, reason: "exp, iat and jti are required" };
53
+ if (sub !== undefined && (typeof sub !== "string" || !OpsTokenVerifier.subPattern.test(sub)))
54
+ return { ok: false, reason: "sub must be 1 to 128 visible ASCII characters" };
50
55
  if (exp <= nowSec) return { ok: false, reason: "expired" };
51
56
  if (iat > nowSec + OpsTokenVerifier.clockSkewSec) return { ok: false, reason: "issued in the future" };
52
57
  if (exp - iat > OpsTokenVerifier.maxLifetimeSec) return { ok: false, reason: "lifetime exceeds 300s" };
53
58
  if (!this.#remember(jti, exp, nowSec)) return { ok: false, reason: "replayed jti" };
54
- return { ok: true, claims: { aud: this.audience, exp, iat, jti } };
59
+ return { ok: true, claims: { aud: this.audience, exp, iat, jti, ...(sub === undefined ? {} : { sub }) } };
55
60
  }
56
61
 
57
62
  #remember(jti: string, exp: number, nowSec: number) {
@@ -10,6 +10,7 @@ import type {
10
10
  } from "akanjs/client";
11
11
  import { Children, cloneElement, isValidElement, type ReactElement, type ReactNode, Suspense } from "react";
12
12
  import { getExplicitPageConfigKeys, resolvePageState } from "../client/frameConfig";
13
+ import { RouteGuards } from "../client/route/RouteGuards";
13
14
  import { resolveHeadResult } from "./head";
14
15
  import {
15
16
  type AkanRouteSegmentState,
@@ -89,7 +90,11 @@ export class RouteElementComposer {
89
90
  });
90
91
  }
91
92
 
92
- static async checkArgs({
93
+ /**
94
+ * Every guard of the route, a patch's included (the layouts it keeps on screen were let in for another URL), then
95
+ * every chain's args. Guards first: a not-found for a bad path value is drawn only under layouts that let the visitor in.
96
+ */
97
+ static async admit({
93
98
  pathRoute,
94
99
  params,
95
100
  searchParams,
@@ -98,11 +103,33 @@ export class RouteElementComposer {
98
103
  params: Record<string, string>;
99
104
  searchParams: Record<string, string | string[]>;
100
105
  }): Promise<void> {
101
- await Promise.all(
102
- RouteElementComposer.#getRenderStack(pathRoute).map((routeRender) =>
103
- routeRender?.checkArgs?.({ params, searchParams }),
104
- ),
105
- );
106
+ const renders = RouteElementComposer.#getRenderStack(pathRoute);
107
+ await RouteGuards.run(renders, { params, searchParams });
108
+ await Promise.all(renders.map((routeRender) => routeRender?.checkArgs?.({ params, searchParams })));
109
+ }
110
+
111
+ static fallbackRouteOf<Route extends LayoutFallbackRoute>(route: Route, error: unknown): Route | LayoutFallbackRoute {
112
+ const refusedAt = RouteGuards.refusedAt(error);
113
+ if (refusedAt === undefined) return route;
114
+ return {
115
+ path: route.path,
116
+ pathSegments: route.pathSegments,
117
+ renderRootLayouts: route.renderRootLayouts.slice(0, refusedAt),
118
+ renderLayouts: route.renderLayouts.slice(0, Math.max(0, refusedAt - route.renderRootLayouts.length)),
119
+ };
120
+ }
121
+
122
+ static async admittedFallbackOf(
123
+ route: LayoutFallbackRoute,
124
+ props: { params: Record<string, string>; searchParams: Record<string, string | string[]> },
125
+ ): Promise<LayoutFallbackRoute> {
126
+ try {
127
+ await RouteGuards.run([...route.renderRootLayouts, ...route.renderLayouts], props);
128
+ return route;
129
+ } catch (error) {
130
+ if ((error as { digest?: unknown } | null)?.digest === "AKAN_REDIRECT") throw error;
131
+ return RouteElementComposer.fallbackRouteOf(route, error);
132
+ }
106
133
  }
107
134
 
108
135
  static composeSuffix({
@@ -24,6 +24,7 @@ import { createElement } from "react";
24
24
  import { defaultPageState, validatePageConfig } from "../client/frameConfig";
25
25
  import { RouteHead } from "../client/route/RouteHead";
26
26
  import {
27
+ assertGuardOnChain,
27
28
  type ResolvedRouteModule,
28
29
  type RouteModuleSource,
29
30
  resolveRouteModule,
@@ -224,6 +225,7 @@ export class RouteTreeBuilder {
224
225
  if (kind === "overrides") return { module: mod as RouteModule };
225
226
  const parsed = parseRouteModuleKey(key);
226
227
  const resolved = resolveRouteModule(mod, key, { kind, pattern: parsed.pattern });
228
+ if (!parsed.isInternalRootLayout) assertGuardOnChain(key, resolved);
227
229
  if (!resolved.definition && !parsed.isInternalRootLayout && !RouteTreeBuilder.#legacyWarned.has(key)) {
228
230
  RouteTreeBuilder.#legacyWarned.add(key);
229
231
  RouteTreeBuilder.logger.warn(
@@ -294,6 +296,9 @@ export class RouteTreeBuilder {
294
296
  checkArgs: async ({ params, searchParams }: PageProps) => {
295
297
  (await loadModule()).definition?.resolveArgs({ params, searchParams });
296
298
  },
299
+ guard: async (props) => {
300
+ await (await loadModule()).module.guard?.(props);
301
+ },
297
302
  };
298
303
  if (kind === "page") {
299
304
  routeRender.getPageConfig = pageConfigOf;
@@ -2,6 +2,7 @@ import { createElement, type ReactNode, startTransition, type Usable, use, useLa
2
2
  import { hydrateRoot } from "react-dom/client";
3
3
  import { createFromReadableStream } from "react-server-dom-webpack/client.browser";
4
4
  import type {} from "../client/rscNavigation";
5
+ import { isAuthTokenKey } from "../common/authCookie";
5
6
  import {
6
7
  type AkanHeadSnapshotV1,
7
8
  type AkanRouterStateV1,
@@ -292,6 +293,12 @@ async function fetchRsc(
292
293
  };
293
294
  }
294
295
 
296
+ const readAuthCookies = () =>
297
+ document.cookie
298
+ .split("; ")
299
+ .filter((entry) => isAuthTokenKey(entry.split("=", 1)[0]))
300
+ .sort()
301
+ .join("; ");
295
302
  const rscCache = new Map<string, RscCacheNode>();
296
303
  const rscPatchCache = new Map<string, RscPatchNavigationCacheNode<RscThenable>>();
297
304
  const initialThenable = createRscThenable(createInitialRscStream());
@@ -308,6 +315,7 @@ let currentFullNode: RscCacheNode = initialNode;
308
315
  let currentCommitKind: "full" | "patch" = "full";
309
316
  let currentCommitFromCache = false;
310
317
  let navigationSeq = 0;
318
+ let cachedAuthCookies = readAuthCookies();
311
319
 
312
320
  globalThis.__AKAN_RSC_IS_FROM_CACHE__ = () => currentCommitFromCache;
313
321
 
@@ -326,6 +334,17 @@ function rememberPatchedRouteState(tree: RscSegmentCacheNode, patchedNode: RscSe
326
334
  currentCommitKind = "patch";
327
335
  }
328
336
 
337
+ function forgetPagesOfAnotherAccount(): void {
338
+ const authCookies = readAuthCookies();
339
+ if (authCookies === cachedAuthCookies) return;
340
+ cachedAuthCookies = authCookies;
341
+ rscCache.clear();
342
+ rscPatchCache.clear();
343
+
344
+ currentRouterState = null;
345
+ currentSegmentTree = null;
346
+ }
347
+
329
348
  function Root(): ReactNode {
330
349
  const [thenable, setThenable] = useState<RscThenable>(initialThenable);
331
350
  const [scrollRequest, setScrollRequest] = useState<{ scrollY: number } | null>(null);
@@ -408,6 +427,7 @@ function Root(): ReactNode {
408
427
 
409
428
  globalThis.__AKAN_RSC_NAVIGATE__ = async (href, options = {}) => {
410
429
  if (options.shallow && navigateShallow(normalizeHref(href), options.replace)) return;
430
+ forgetPagesOfAnotherAccount();
411
431
  const navId = ++navigationSeq;
412
432
  const target = normalizeHref(href);
413
433
  const scrollY = options.scrollY ?? ((options.scrollToTop ?? true) ? 0 : undefined);
@@ -1,7 +1,14 @@
1
- import type { PageDefinition, PathRoute } from "akanjs/client";
1
+ import type { PageDefinition, PathRoute, RoutePromptMeta } from "akanjs/client";
2
2
  import { Logger, parseSearchParams } from "akanjs/common";
3
- import { getRequestStore } from "akanjs/fetch";
4
- import type { PagePromptEntry, PagePromptRecord, PagePromptRun, PagePromptRunInput } from "../signal/mcp/pagePrompt";
3
+ import { AppScope, getRequestStore } from "akanjs/fetch";
4
+ import { RouteGuards } from "../client/route/RouteGuards";
5
+ import type {
6
+ PagePromptEntry,
7
+ PagePromptRecord,
8
+ PagePromptRun,
9
+ PagePromptRunInput,
10
+ PagePromptVisibleInput,
11
+ } from "../signal/mcp/pagePrompt";
5
12
 
6
13
  interface RscPagePromptsProps {
7
14
  routes: () => PathRoute[];
@@ -45,8 +52,9 @@ export class RscPagePrompts {
45
52
  .filter((arg) => arg.kind === "search" && input.arguments[arg.name] !== undefined)
46
53
  .map((arg) => [arg.name, RscPagePrompts.#searchValue(arg.list, input.arguments[arg.name] as string)]),
47
54
  );
55
+ let resolved: Record<string, unknown>;
48
56
  try {
49
- definition.resolveArgs({ params, searchParams }, { strict: true });
57
+ resolved = definition.resolveArgs({ params, searchParams }, { strict: true });
50
58
  } catch (error) {
51
59
  return { ok: false, reason: "argument", message: error instanceof Error ? error.message : String(error) };
52
60
  }
@@ -58,29 +66,71 @@ export class RscPagePrompts {
58
66
  params: { ...params, lang },
59
67
  searchParams: parseSearchParams(new URL(url).search),
60
68
  };
69
+ const renders = RscPagePrompts.#rendersOf(route);
70
+
71
+ let guardReads = 0;
61
72
  try {
62
- for (const render of [...route.renderRootLayouts, ...route.renderLayouts, route.renderPage])
63
- await render.render({ ...props, children: null } as never);
73
+ await RscPagePrompts.#scoped(entry, () => RouteGuards.run(renders, props));
74
+ guardReads = getRequestStore()?.queryLog.length ?? 0;
75
+
76
+ if (entry.kind === "app") await (definition as PageDefinition).loadApp(entry.name, { lang, ...resolved });
77
+ else for (const render of renders) await render.render({ ...props, children: null } as never);
64
78
  } catch (error) {
65
79
  return RscPagePrompts.#refusal(error);
66
80
  }
67
- const records = await Promise.all((getRequestStore()?.queryLog ?? []).map(RscPagePrompts.#settle));
68
- return { ok: true, url, records };
81
+ const records = await Promise.all(
82
+ (getRequestStore()?.queryLog ?? []).slice(guardReads).map(RscPagePrompts.#settle),
83
+ );
84
+ return { ok: true, url, records, route: props };
69
85
  });
70
86
  }
71
87
 
88
+ /** The names whose route guards let this caller see the screen, read with no arguments as a listing has none. */
89
+ async visible({ names, headers, language }: PagePromptVisibleInput): Promise<string[]> {
90
+ const lang = language ?? this.#props.defaultLocale();
91
+ const routes = this.#props.routes();
92
+ const entries = (await this.list()).filter((entry) => names.includes(entry.name));
93
+ const verdicts = await Promise.all(
94
+ entries.map(async (entry) => {
95
+ const route = routes.find((candidate) => candidate.path === entry.pattern);
96
+ if (!route) return false;
97
+ const request = new Request(RscPagePrompts.#urlOf(entry.pattern, { lang }, {}), { headers });
98
+ return await this.#props.run(request, route.path, () =>
99
+ RscPagePrompts.#scoped(entry, () =>
100
+ RouteGuards.admits(RscPagePrompts.#rendersOf(route), { params: { lang }, searchParams: {} }),
101
+ ),
102
+ );
103
+ }),
104
+ );
105
+ return entries.filter((_, idx) => verdicts[idx]).map((entry) => entry.name);
106
+ }
107
+
108
+ static #scoped<T>(entry: PagePromptEntry, run: () => Promise<T>): Promise<T> {
109
+ return entry.kind === "app" ? AppScope.run(entry.name, run) : run();
110
+ }
111
+
112
+ static #rendersOf(route: PathRoute) {
113
+ return [...route.renderRootLayouts, ...route.renderLayouts, route.renderPage];
114
+ }
115
+
72
116
  async #collect(routes: PathRoute[]): Promise<PagePromptEntry[]> {
73
117
  const entries: PagePromptEntry[] = [];
74
- const owners = new Map<string, string>();
75
- for (const route of routes) {
76
- const definition = await route.renderPage.getRouteDefinition?.();
77
- const meta = definition?.kind === "page" ? (definition as PageDefinition).promptMeta : undefined;
78
- if (!meta) continue;
118
+ const owners = new Map<string, { kind: PagePromptEntry["kind"]; path: string }>();
119
+ const claim = (kind: PagePromptEntry["kind"], meta: RoutePromptMeta, path: string) => {
79
120
  const owner = owners.get(meta.name);
80
121
  if (owner)
81
- throw new Error(`[route-convention] prompt "${meta.name}" is declared by both ${owner} and ${route.path}`);
82
- owners.set(meta.name, route.path);
83
- entries.push({ ...meta, pattern: route.path });
122
+ throw new Error(
123
+ `[route-convention] ${kind} "${meta.name}" is declared by both ${owner.path}${owner.kind === kind ? "" : ` (as its ${owner.kind})`} and ${path}`,
124
+ );
125
+ owners.set(meta.name, { kind, path });
126
+ entries.push({ kind, ...meta, pattern: path });
127
+ };
128
+ for (const route of routes) {
129
+ const definition = await route.renderPage.getRouteDefinition?.();
130
+ if (definition?.kind !== "page") continue;
131
+ const page = definition as PageDefinition;
132
+ if (page.promptMeta) claim("prompt", page.promptMeta, route.path);
133
+ for (const meta of page.appMetas) claim("app", meta, route.path);
84
134
  }
85
135
 
86
136
  return entries.sort((a, b) => a.name.localeCompare(b.name));