@mostra/runtime 0.12.0 → 0.14.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 (37) hide show
  1. package/dist/bin.js +2912 -2318
  2. package/dist/bin.js.map +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/{instance-CBUlOmzG.js → instance-CFTw3g-c.js} +227 -25
  5. package/dist/instance-CFTw3g-c.js.map +1 -0
  6. package/dist/reference/diagnostics.json +2 -2
  7. package/dist/reference/errors/MOSTRA_REMOTE_QUEUE_FULL.md +2 -2
  8. package/dist/reference/self-hosting.md +2 -1
  9. package/dist/skill/SKILL.md +2 -2
  10. package/dist/skill/assets/examples/dashboard/styles.css +27 -9
  11. package/dist/skill/assets/examples/decision/styles.css +27 -9
  12. package/dist/skill/assets/examples/inbox/styles.css +27 -9
  13. package/dist/skill/assets/studio.css +27 -9
  14. package/dist/skill/references/mcp.md +2 -2
  15. package/package.json +7 -6
  16. package/src/actions/index.ts +5 -2
  17. package/src/gateway/actions.ts +6 -1
  18. package/src/gateway/capabilities.ts +5 -1
  19. package/src/gateway/http.ts +15 -19
  20. package/src/gateway/index.ts +70 -1
  21. package/src/gateway/listener.ts +10 -5
  22. package/src/gateway/routes.ts +6 -1
  23. package/src/gateway/theme.ts +238 -0
  24. package/src/ledger/migrations.ts +9 -0
  25. package/src/server/api.ts +79 -87
  26. package/src/server/auth.ts +83 -16
  27. package/src/server/authorize.ts +74 -58
  28. package/src/server/config.ts +98 -0
  29. package/src/server/directory.ts +51 -0
  30. package/src/server/hosted-pages.ts +19 -6
  31. package/src/server/hosted.ts +59 -27
  32. package/src/server/index.ts +144 -17
  33. package/src/server/metering.ts +117 -12
  34. package/src/server/pages.ts +242 -0
  35. package/src/server/providers.ts +61 -9
  36. package/src/server/relay.ts +258 -107
  37. package/dist/instance-CBUlOmzG.js.map +0 -1
@@ -0,0 +1,242 @@
1
+ /**
2
+ * The API origin's own pages (INTERFACES §18.5, D171): sign-in with its providers, the development
3
+ * provider's name page, linking a machine (the device grant), consent for a chat app, a page's
4
+ * "Answer as yourself", and every "Sign-in can't continue". They are `@mostra/themes`' pages in the
5
+ * operator's theme and name, with no script; every word they say is in `API_PAGE_WORDS`, and every
6
+ * name a provider, a client or a person supplies lands as text.
7
+ */
8
+ import type { Appearance } from "@mostra/themes";
9
+ import {
10
+ actions,
11
+ alert,
12
+ button,
13
+ field,
14
+ fine,
15
+ html,
16
+ linkButton,
17
+ type SafeHtml,
18
+ } from "@mostra/themes";
19
+ import type { ServerPages } from "../gateway/index.ts";
20
+
21
+ /** Where a person's appearance switch posts on the API origin (D171). */
22
+ export const APPEARANCE_PATH = "/_mostra/appearance";
23
+
24
+ /** Every word the API origin's pages say (D149: Mirza reviews them). */
25
+ export const API_PAGE_WORDS = {
26
+ signInTitle: (name: string | null): string => (name ? `Sign in to ${name}` : "Sign in"),
27
+ signInLede: "Choose how to sign in.",
28
+ continueWith: (label: string): string => `Continue with ${label}`,
29
+ noProviders: "This server has no sign-in set up yet, so nobody can sign in.",
30
+ neverPassword: "You sign in with your provider. This server never sees your password.",
31
+ devTitle: "Development sign-in",
32
+ devNote:
33
+ "This server signs people in with a development provider, which trusts the name you type. Use it only on a server you run for yourself or for tests.",
34
+ yourName: "Your name",
35
+ continue: "Continue",
36
+ cantContinue: "Sign-in can't continue",
37
+ deviceTitle: "Link this machine",
38
+ deviceSignedInAs: (name: string): SafeHtml => html`Signed in as <strong>${name}</strong>.`,
39
+ deviceWarning:
40
+ "Approving links a machine to your account. That machine's Mostra can then host pages under your account and receives their answers. Continue only if you started this sign-in yourself, on that machine.",
41
+ deviceCode: "The code that machine shows",
42
+ approveMachine: "Approve this machine",
43
+ refuse: "Refuse",
44
+ deviceLinked: "The machine is linked to your account.",
45
+ deviceRefused: "The sign-in was refused.",
46
+ deviceClose: "You can close this page.",
47
+ answerTitle: "Answer as yourself",
48
+ answerAs: (who: string, owner: string): string => `Continue as ${who} to answer ${owner}'s page?`,
49
+ answerDetail: "They will see your name with your answers.",
50
+ thisPerson: "this person",
51
+ allowTitle: (client: string): string => `Allow ${client}?`,
52
+ asksToUse: (client: SafeHtml, who: string): SafeHtml =>
53
+ html`${client} asks to use Mostra as <strong>${who}</strong>.`,
54
+ unverifiedName: "a name the app gives itself, not checked",
55
+ grants: ["Read, create and change your hosted pages", "Read their answers"],
56
+ sendsBackTo: (host: string): SafeHtml => html`It will send you back to <strong>${host}</strong>.`,
57
+ loopback: "That is a program on your own computer: continue only if you started this there.",
58
+ allow: "Allow",
59
+ cancel: "Cancel",
60
+ yourAccount: "your account",
61
+ } as const;
62
+
63
+ /** The marks of providers a person recognises, by provider ID. Others show their label alone. */
64
+ const PROVIDER_ICONS: Readonly<Record<string, SafeHtml>> = {
65
+ github: html`<svg viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/></svg>`,
66
+ google: html`<svg viewBox="0 0 18 18" aria-hidden="true"><path fill="#4285F4" d="M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.48h4.84a4.14 4.14 0 0 1-1.8 2.72v2.26h2.92a8.78 8.78 0 0 0 2.68-6.62z"/><path fill="#34A853" d="M9 18c2.43 0 4.47-.8 5.96-2.18l-2.92-2.26c-.8.54-1.84.86-3.04.86-2.34 0-4.33-1.58-5.04-3.7H.96v2.33A9 9 0 0 0 9 18z"/><path fill="#FBBC05" d="M3.96 10.72A5.4 5.4 0 0 1 3.68 9c0-.6.1-1.18.28-1.72V4.95H.96A9 9 0 0 0 0 9c0 1.45.35 2.83.96 4.05l3-2.33z"/><path fill="#EA4335" d="M9 3.58c1.32 0 2.5.45 3.44 1.35l2.58-2.58A8.97 8.97 0 0 0 9 0 9 9 0 0 0 .96 4.95l3 2.33C4.67 5.16 6.66 3.58 9 3.58z"/></svg>`,
67
+ };
68
+
69
+ /** Where a page is and what the person chose, for its appearance switch. */
70
+ export interface PageRequest {
71
+ /** The person's own choice; without one, the operator's default. */
72
+ readonly appearance?: Appearance;
73
+ /** This page's own path and query: where the appearance switch returns. */
74
+ readonly path: string;
75
+ }
76
+
77
+ /** The API origin's pages, as HTML. */
78
+ export interface ApiPages {
79
+ readonly name: string | null;
80
+ signIn(
81
+ request: PageRequest,
82
+ providers: readonly { readonly id: string; readonly label: string }[],
83
+ next: string,
84
+ message?: string,
85
+ ): string;
86
+ developmentName(request: PageRequest, providerId: string, state: string): string;
87
+ problem(request: PageRequest, message: string): string;
88
+ answerAs(request: PageRequest, form: ConsentForm, who: string, owner: string | undefined): string;
89
+ allow(
90
+ request: PageRequest,
91
+ form: ConsentForm,
92
+ client: { readonly name: string; readonly unverified: boolean },
93
+ who: string,
94
+ redirectHost: string,
95
+ loopback: boolean,
96
+ ): string;
97
+ deviceForm(
98
+ request: PageRequest,
99
+ options: {
100
+ readonly code: string;
101
+ readonly message?: string | undefined;
102
+ readonly development?: { readonly id: string; readonly label: string } | undefined;
103
+ readonly signedIn?: { readonly name: string; readonly csrf: string } | undefined;
104
+ },
105
+ ): string;
106
+ deviceDone(request: PageRequest, message: string): string;
107
+ }
108
+
109
+ /** The consent form's target and its CSRF token. */
110
+ export interface ConsentForm {
111
+ readonly action: string;
112
+ readonly csrf: string;
113
+ }
114
+
115
+ /** Makes the API origin's pages from the server's own pages (its theme and name). */
116
+ export function createApiPages(server: ServerPages, name: string | null): ApiPages {
117
+ const W = API_PAGE_WORDS;
118
+ const { pages } = server;
119
+ const consentButtons = (approve: string) =>
120
+ actions(
121
+ button(approve, { name: "decision", value: "approve", primary: true }),
122
+ button(W.cancel, { name: "decision", value: "deny" }),
123
+ );
124
+ return {
125
+ name,
126
+ signIn(request, providers, next, message) {
127
+ const list = providers.map((provider, index) =>
128
+ linkButton(
129
+ `/signin/${encodeURIComponent(provider.id)}/start?next=${encodeURIComponent(next)}`,
130
+ W.continueWith(provider.label),
131
+ {
132
+ primary: index === 0,
133
+ ...(PROVIDER_ICONS[provider.id]
134
+ ? { icon: PROVIDER_ICONS[provider.id] as SafeHtml }
135
+ : {}),
136
+ },
137
+ ),
138
+ );
139
+ return pages.render({
140
+ kind: "task",
141
+ title: W.signInTitle(name),
142
+ lede: W.signInLede,
143
+ body: html`${message ? alert(message) : ""}${
144
+ list.length > 0
145
+ ? html`<div class="m-list">${list}</div>${fine(W.neverPassword)}`
146
+ : alert(W.noProviders, "note")
147
+ }`,
148
+ ...request,
149
+ });
150
+ },
151
+ developmentName(request, providerId, state) {
152
+ return pages.render({
153
+ kind: "task",
154
+ title: W.devTitle,
155
+ body: html`${alert(W.devNote, "note")}<form method="post" action="/signin/${providerId}/name"><input type="hidden" name="state" value="${state}">${field(
156
+ { label: W.yourName, name: "name", required: true, maxLength: 64, autocomplete: "name" },
157
+ )}${actions(button(W.continue, { primary: true }))}</form>`,
158
+ ...request,
159
+ });
160
+ },
161
+ problem(request, message) {
162
+ return pages.render({
163
+ kind: "notice",
164
+ tone: "problem",
165
+ title: W.cantContinue,
166
+ body: html`<p>${message}</p>`,
167
+ ...request,
168
+ });
169
+ },
170
+ answerAs(request, form, who, owner) {
171
+ return pages.render({
172
+ kind: "task",
173
+ title: W.answerTitle,
174
+ lede: W.answerAs(who, owner ?? W.thisPerson),
175
+ body: html`<p>${W.answerDetail}</p><form method="post" action="${form.action}"><input type="hidden" name="csrf" value="${form.csrf}">${consentButtons(W.continue)}</form>`,
176
+ ...request,
177
+ });
178
+ },
179
+ allow(request, form, client, who, redirectHost, loopback) {
180
+ const clientName = client.unverified
181
+ ? html`<strong>${client.name}</strong> <span class="m-hint">(${W.unverifiedName})</span>`
182
+ : html`<strong>${client.name}</strong>`;
183
+ return pages.render({
184
+ kind: "task",
185
+ title: W.allowTitle(client.name),
186
+ lede: W.asksToUse(clientName, who),
187
+ body: html`<ul class="m-grants">${W.grants.map((grant) => html`<li>${grant}</li>`)}</ul><p>${W.sendsBackTo(redirectHost)}</p>${loopback ? alert(W.loopback) : ""}<form method="post" action="${form.action}"><input type="hidden" name="csrf" value="${form.csrf}">${consentButtons(W.allow)}</form>`,
188
+ ...request,
189
+ });
190
+ },
191
+ deviceForm(request, options) {
192
+ const signedIn = options.signedIn;
193
+ const development = options.development;
194
+ const form = signedIn
195
+ ? html`<form method="post" action="/device"><input type="hidden" name="csrf" value="${signedIn.csrf}">${field(
196
+ {
197
+ label: W.deviceCode,
198
+ name: "user_code",
199
+ value: options.code,
200
+ required: true,
201
+ code: true,
202
+ },
203
+ )}${actions(
204
+ button(W.approveMachine, { name: "session_decision", value: "approve", primary: true }),
205
+ button(W.refuse, { name: "session_decision", value: "deny" }),
206
+ )}</form>`
207
+ : development
208
+ ? html`<form method="post" action="/device">${field({
209
+ label: W.deviceCode,
210
+ name: "user_code",
211
+ value: options.code,
212
+ required: true,
213
+ code: true,
214
+ })}${alert(W.devNote, "note")}${field({
215
+ label: W.yourName,
216
+ name: "name",
217
+ required: true,
218
+ maxLength: 64,
219
+ autocomplete: "name",
220
+ })}<input type="hidden" name="provider" value="${development.id}">${actions(
221
+ button(W.approveMachine, { name: "decision", value: "approve", primary: true }),
222
+ button(W.refuse, { name: "decision", value: "deny" }),
223
+ )}</form>`
224
+ : alert(W.noProviders, "note");
225
+ return pages.render({
226
+ kind: "task",
227
+ title: W.deviceTitle,
228
+ ...(signedIn ? { lede: W.deviceSignedInAs(signedIn.name) } : {}),
229
+ body: html`${options.message ? alert(options.message) : ""}${alert(W.deviceWarning, "note")}${form}`,
230
+ ...request,
231
+ });
232
+ },
233
+ deviceDone(request, message) {
234
+ return pages.render({
235
+ kind: "notice",
236
+ title: message,
237
+ body: html`<p>${W.deviceClose}</p>`,
238
+ ...request,
239
+ });
240
+ },
241
+ };
242
+ }
@@ -5,9 +5,10 @@
5
5
  *
6
6
  * - `oidc`: any OpenID Connect provider, by its issuer's discovery document; the authorization
7
7
  * code flow with PKCE (S256) and a nonce, and the ID token checked (signature, issuer, audience,
8
- * expiry, nonce) by `openid-client`.
8
+ * expiry, nonce) by `openid-client`; the claims its entry names (`claims`) go into `facts`.
9
9
  * - `github`: GitHub's OAuth web flow with PKCE, then `GET /user` for the account's stable ID, its
10
- * login and name, and its age (`facts.createdAt`) for an operator's policy.
10
+ * login and name, and for an operator's policy its age (`facts.createdAt`) and public counts
11
+ * (`facts.publicRepos`, `publicGists`, `followers`).
11
12
  * - `development`: a page that asks for a name and trusts it, for tests and a self-hoster's first
12
13
  * run; its names are never shown as verified.
13
14
  *
@@ -24,7 +25,7 @@ import type {
24
25
  } from "@mostra/protocol/operator";
25
26
  import * as oidc from "openid-client";
26
27
  import type { Environment, Log } from "../log.ts";
27
- import type { IdentityProviderConfig } from "./config.ts";
28
+ import { configuredVerifier, type IdentityProviderConfig } from "./config.ts";
28
29
 
29
30
  /** How long a provider's discovery, token exchange or user lookup may take. */
30
31
  const PROVIDER_TIMEOUT_MS = 8_000;
@@ -36,11 +37,17 @@ const GITHUB = {
36
37
  user: "https://api.github.com/user",
37
38
  } as const;
38
39
 
39
- /** A built-in provider: the port's shape, and whether its names are verified. */
40
+ /** A built-in provider: the port's shape, its kind, and its verifier (all but `development`). */
40
41
  export interface BuiltInProvider extends IdentityProvider {
41
42
  readonly kind: IdentityProviderConfig["kind"];
42
- /** Whether the names it gives are verified by someone (all but `development`). */
43
- readonly verifies: boolean;
43
+ }
44
+
45
+ /** The `verifies` of a configured provider: the label its verified names carry, if any. */
46
+ function verifiesOf(config: IdentityProviderConfig): {
47
+ readonly verifies?: { readonly label: string };
48
+ } {
49
+ const label = configuredVerifier(config);
50
+ return label === undefined ? {} : { verifies: { label } };
44
51
  }
45
52
 
46
53
  function invalid(message: string): RpcError {
@@ -69,6 +76,36 @@ async function timedFetch(url: string, init: RequestInit): Promise<Response> {
69
76
  return fetch(url, { ...init, signal: AbortSignal.timeout(PROVIDER_TIMEOUT_MS) });
70
77
  }
71
78
 
79
+ /** The longest a chosen claim's value may be, as JSON: a policy reads names, not documents. */
80
+ const CLAIM_MAX = 4_096;
81
+
82
+ /**
83
+ * The ID token's claims a configuration chose (`claims`), as `facts` under their own names: each
84
+ * one present whose value is JSON of at most 4 KiB (MT-03). A claim the token doesn't carry is left
85
+ * out; with none chosen, nothing is added.
86
+ */
87
+ function chosen(
88
+ claims: Readonly<Record<string, unknown>>,
89
+ names: readonly string[] | undefined,
90
+ ): { readonly facts: Record<string, unknown> } | undefined {
91
+ if (names === undefined) return undefined;
92
+ const facts: Record<string, unknown> = {};
93
+ for (const name of names) {
94
+ if (!Object.hasOwn(claims, name)) continue;
95
+ const value = claims[name];
96
+ const text = JSON.stringify(value);
97
+ if (text === undefined || text.length > CLAIM_MAX) continue;
98
+ // A key of its own, whatever the name (`__proto__` would set the prototype by assignment).
99
+ Object.defineProperty(facts, name, {
100
+ value: JSON.parse(text) as unknown,
101
+ enumerable: true,
102
+ writable: true,
103
+ configurable: true,
104
+ });
105
+ }
106
+ return Object.keys(facts).length > 0 ? { facts } : undefined;
107
+ }
108
+
72
109
  /** The OpenID Connect adapter. Discovery happens at the first sign-in and is kept. */
73
110
  function oidcProvider(config: IdentityProviderConfig, env: Environment): BuiltInProvider {
74
111
  if (config.issuer === undefined || config.clientId === undefined) {
@@ -106,7 +143,7 @@ function oidcProvider(config: IdentityProviderConfig, env: Environment): BuiltIn
106
143
  id: config.id,
107
144
  label: config.label ?? config.id,
108
145
  kind: "oidc",
109
- verifies: true,
146
+ ...verifiesOf(config),
110
147
  async authorize(state: string, pkce: SignInPkce, context: SignInContext) {
111
148
  const url = oidc.buildAuthorizationUrl(await configuration(), {
112
149
  redirect_uri: context.redirectUri,
@@ -143,12 +180,18 @@ function oidcProvider(config: IdentityProviderConfig, env: Environment): BuiltIn
143
180
  ? { emailVerified: claims["email_verified"] }
144
181
  : {}),
145
182
  ...(name !== undefined ? { name } : {}),
183
+ ...(chosen(claims, config.claims) ?? {}),
146
184
  };
147
185
  return identity;
148
186
  },
149
187
  };
150
188
  }
151
189
 
190
+ /** A count GitHub gave, under its name in `facts`: a non-negative integer, or nothing. */
191
+ function count(name: string, value: unknown): Record<string, number> {
192
+ return Number.isSafeInteger(value) && (value as number) >= 0 ? { [name]: value as number } : {};
193
+ }
194
+
152
195
  /** The GitHub adapter: an OAuth app's web flow with PKCE (VERIFIED_FACTS, WP-30). */
153
196
  function githubProvider(config: IdentityProviderConfig, env: Environment): BuiltInProvider {
154
197
  if (config.clientId === undefined) {
@@ -169,7 +212,7 @@ function githubProvider(config: IdentityProviderConfig, env: Environment): Built
169
212
  id: config.id,
170
213
  label: config.label ?? "GitHub",
171
214
  kind: "github",
172
- verifies: true,
215
+ ...verifiesOf(config),
173
216
  authorize(state, pkce, context) {
174
217
  const url = new URL(endpoints.authorize);
175
218
  url.searchParams.set("client_id", config.clientId as string);
@@ -221,6 +264,9 @@ function githubProvider(config: IdentityProviderConfig, env: Environment): Built
221
264
  name?: string | null;
222
265
  email?: string | null;
223
266
  created_at?: string;
267
+ public_repos?: number;
268
+ public_gists?: number;
269
+ followers?: number;
224
270
  };
225
271
  if (!user.ok || typeof found.id !== "number") {
226
272
  throw new Error(`GitHub's user lookup failed (${user.status}).`);
@@ -231,9 +277,16 @@ function githubProvider(config: IdentityProviderConfig, env: Environment): Built
231
277
  subject: String(found.id),
232
278
  ...(typeof found.email === "string" ? { email: found.email } : {}),
233
279
  name: found.name ?? found.login ?? String(found.id),
280
+ // What the same answer tells an operator's policy (an account's age and its public
281
+ // counts, so a fresh, empty account is told from an established one with no other
282
+ // request inside `accounts.resolve`'s time limit, MT-03); a count GitHub didn't give is
283
+ // left out rather than guessed.
234
284
  facts: {
235
285
  login: found.login ?? null,
236
286
  ...(found.created_at !== undefined ? { createdAt: found.created_at } : {}),
287
+ ...count("publicRepos", found.public_repos),
288
+ ...count("publicGists", found.public_gists),
289
+ ...count("followers", found.followers),
237
290
  },
238
291
  };
239
292
  },
@@ -249,7 +302,6 @@ function developmentProvider(config: IdentityProviderConfig, apiOrigin: string):
249
302
  id: config.id,
250
303
  label: config.label ?? "Development sign-in",
251
304
  kind: "development",
252
- verifies: false,
253
305
  authorize(state) {
254
306
  const url = new URL(`${apiOrigin}/signin/${config.id}/name`);
255
307
  url.searchParams.set("state", state);