@fungi.computer/oyster 0.56.2 → 0.57.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/agent-computer-source.js +4 -1
  2. package/dist/auth.d.ts +12 -4
  3. package/dist/auth.js +85 -24
  4. package/dist/boot-capability-route.js +5 -1
  5. package/dist/boot-gate.d.ts +5 -0
  6. package/dist/boot-gate.js +12 -2
  7. package/dist/boot-host-script.js +1 -1
  8. package/dist/boot-mount.d.ts +7 -1
  9. package/dist/boot-mount.js +11 -5
  10. package/dist/credential-migration-002.js +6 -1
  11. package/dist/embed-metafiles.js +2 -2
  12. package/dist/embed-scripts.js +2 -2
  13. package/dist/git.d.ts +8 -2
  14. package/dist/git.js +12 -3
  15. package/dist/hello-app-script.js +1 -1
  16. package/dist/host-page-assets.js +1 -1
  17. package/dist/host-page-lazy.d.ts +2 -0
  18. package/dist/host-page-lazy.js +8 -0
  19. package/dist/host-page.d.ts +22 -1
  20. package/dist/host-page.js +91 -12
  21. package/dist/host.d.ts +8 -0
  22. package/dist/host.js +60 -7
  23. package/dist/owner-sessions.d.ts +25 -0
  24. package/dist/owner-sessions.js +50 -0
  25. package/dist/page/boot-host.js +20 -2
  26. package/dist/page/port-preview.d.ts +1 -0
  27. package/dist/page/port-preview.js +33 -0
  28. package/dist/page-script.js +3 -3
  29. package/dist/platform-skills.generated.d.ts +1 -1
  30. package/dist/platform-skills.generated.js +1 -1
  31. package/dist/port-preview-entry.d.ts +84 -0
  32. package/dist/port-preview-entry.js +86 -0
  33. package/dist/standalone/agents.js +1 -0
  34. package/dist/standalone/builds.js +5 -0
  35. package/dist/standalone/candidate-preview.d.ts +25 -0
  36. package/dist/standalone/candidate-preview.js +265 -0
  37. package/dist/standalone/computer.d.ts +2 -3
  38. package/dist/standalone/computer.js +13 -9
  39. package/dist/standalone/preview.d.ts +9 -4
  40. package/dist/standalone/preview.js +35 -44
  41. package/dist/standalone/tenancy.d.ts +1 -1
  42. package/dist/standalone/tenancy.js +9 -1
  43. package/dist/standalone/worker.js +15 -2
  44. package/dist/starter-agent.js +5 -2
  45. package/dist/storage-frame.d.ts +3 -3
  46. package/dist/tenancy/owner-key.d.ts +4 -1
  47. package/dist/tenancy/owner-key.js +27 -2
  48. package/dist/upgrade/old-worker-http.js +2 -6
  49. package/dist/webhook-delivery.d.ts +1 -0
  50. package/dist/webhook-delivery.js +1 -1
  51. package/dist/workers-git.d.ts +19 -0
  52. package/dist/workers-git.js +108 -7
  53. package/dist/workers.d.ts +11 -0
  54. package/dist/workers.js +33 -1
  55. package/docs/api/README.md +14 -3
  56. package/docs/api/auth.md +96 -8
  57. package/docs/api/git.md +13 -7
  58. package/docs/api/host.md +2 -0
  59. package/docs/api/tenancy/owner-key.md +1 -0
  60. package/docs/api/workers-git.md +50 -0
  61. package/docs/api/workers.md +98 -16
  62. package/package.json +18 -18
@@ -3,3 +3,5 @@ import type { HostPageOptions } from "./host-page.js";
3
3
  export declare function renderHostPage(options: HostPageOptions): Promise<Response>;
4
4
  /** Serve one content-addressed host page asset, loading the renderer on first use. */
5
5
  export declare function serveHostPageAsset(path: string): Promise<Response>;
6
+ export declare function renderPreviewStyles(): Promise<string>;
7
+ export declare function renderPreviewChrome(notice: import("./host-page.js").PreviewNotice): Promise<string>;
@@ -13,3 +13,11 @@ export async function serveHostPageAsset(path) {
13
13
  const serve = await loadLazily(() => import("./host-page.js").then(({ hostPageAsset }) => hostPageAsset), renderer);
14
14
  return serve(path);
15
15
  }
16
+ export async function renderPreviewStyles() {
17
+ const render = await loadLazily(() => import("./host-page.js").then((module) => module.previewStyles), renderer);
18
+ return render();
19
+ }
20
+ export async function renderPreviewChrome(notice) {
21
+ const render = await loadLazily(() => import("./host-page.js").then((module) => module.previewChrome), renderer);
22
+ return render(notice);
23
+ }
@@ -1,8 +1,15 @@
1
1
  import { type AppPermissionsViewData } from "./apps/permissions.js";
2
+ import { type PortPreviewEntry } from "./port-preview-entry.js";
2
3
  /** Human-facing states only. API refusals keep their original wire format. */
3
- export type HostPageState = "permissions" | "root" | "empty" | "login" | "login-invalid" | "key-help" | "signing-in" | "not-found" | "server-error" | "access-denied" | "desktop-missing";
4
+ export type HostPageState = "preview" | "permissions" | "root" | "empty" | "login" | "login-invalid" | "key-help" | "signing-in" | "open-preview" | "not-found" | "server-error" | "access-denied" | "desktop-missing";
4
5
  export type HostPageOptions = Readonly<{
5
6
  state: HostPageState;
7
+ preview?: Readonly<{
8
+ appName?: string;
9
+ action: string;
10
+ preparing: boolean;
11
+ }>;
12
+ inlineStyles?: string;
6
13
  title?: string;
7
14
  status?: number;
8
15
  stylesheets?: readonly string[];
@@ -19,6 +26,8 @@ export type HostPageOptions = Readonly<{
19
26
  returning?: boolean;
20
27
  /** Login only: the visitor arrived through a one-time link that was already used. */
21
28
  usedLink?: boolean;
29
+ /** Open preview only: the port and Computer it opens, and where the owner's own click posts. */
30
+ previewEntry?: PortPreviewEntry;
22
31
  /** Only the single-use helper passes a key, in a POST field, never a URL. */
23
32
  signIn?: Readonly<{
24
33
  action: string;
@@ -33,3 +42,15 @@ export type HostPageOptions = Readonly<{
33
42
  export declare function hostPageAsset(path: string): Promise<Response>;
34
43
  /** One server-rendered Caps composition, usable without styles, art or JS. */
35
44
  export declare function hostPage(options: HostPageOptions): Promise<Response>;
45
+ /** Maintained Caps and Oyster page tokens, embedded for the private preview. */
46
+ export declare function previewStyles(): Promise<string>;
47
+ export type PreviewNotice = Readonly<{
48
+ appName: string;
49
+ revision: string;
50
+ status: string;
51
+ explanation: string;
52
+ expiresAt: number;
53
+ entry: string;
54
+ }>;
55
+ /** Trusted preview chrome; the candidate cannot supply HTML or host authority. */
56
+ export declare function previewChrome(notice: PreviewNotice): Promise<string>;
package/dist/host-page.js CHANGED
@@ -6,11 +6,14 @@ import { Status } from "@fungi.computer/caps/components/status";
6
6
  import { Button } from "@fungi.computer/caps/components/button";
7
7
  import { Input } from "@fungi.computer/caps/components/input";
8
8
  import { Card, CardHeader, CardTitle, CardContent, } from "@fungi.computer/caps/components/card";
9
+ import { loadPageAssets } from "./page-assets.js";
9
10
  import { fungiFaviconHref } from "@fungi.computer/sigils/favicon";
10
11
  import { permissionScreen, } from "./apps/permissions.js";
11
12
  import { permissionCatalog } from "./apps/catalog.js";
13
+ import { portPreviewReferrerPolicy, portPreviewRefusalMessage, } from "./port-preview-entry.js";
12
14
  const docs = "https://docs.fungi.computer";
13
15
  const copy = {
16
+ preview: ["Preview", "Oyster · Preview", "Opening preview…"],
14
17
  permissions: [
15
18
  "Choose what this App can do.",
16
19
  "Oyster · App permissions",
@@ -46,6 +49,11 @@ const copy = {
46
49
  "One-time sign-in",
47
50
  "This private link signs you in on this computer. It works once. Continue to your Oyster below if it does not open automatically.",
48
51
  ],
52
+ "open-preview": [
53
+ "Open this preview?",
54
+ "Private port preview",
55
+ "An App asked to open a port on your Computer, signed in as you. Nothing opens until you choose Open preview.",
56
+ ],
49
57
  "not-found": [
50
58
  "Nothing growing here.",
51
59
  "404",
@@ -68,6 +76,12 @@ const copy = {
68
76
  ],
69
77
  };
70
78
  const abilities = {
79
+ preview: [
80
+ "Preview a change",
81
+ "Open the page.",
82
+ "Check the change.",
83
+ "Merge in Bonsai when ready.",
84
+ ],
71
85
  permissions: [
72
86
  "You choose the access",
73
87
  "Check the App and Release below.",
@@ -110,6 +124,12 @@ const abilities = {
110
124
  "Continue below if it does not.",
111
125
  "Use your saved key if needed.",
112
126
  ],
127
+ "open-preview": [
128
+ "You choose what opens",
129
+ "Check this is the preview you expected.",
130
+ "Choose Open preview to continue.",
131
+ "Close this tab if you did not ask for it.",
132
+ ],
113
133
  "not-found": [
114
134
  "Find an available page",
115
135
  "Return to your Oyster.",
@@ -163,6 +183,12 @@ function pageContent(options, url) {
163
183
  const { state, signIn } = options;
164
184
  const content = [];
165
185
  const actions = [];
186
+ if (state === "preview" && options.preview) {
187
+ content.push(h("form", { method: "post", action: options.preview.action }, options.preview.preparing
188
+ ? h("input", { type: "hidden", name: "intent", value: "prepare" })
189
+ : null, h(Button, { type: "submit", size: "sm" }, options.preview.preparing ? "Continue" : "Open preview")));
190
+ return { content, actions };
191
+ }
166
192
  if (state === "permissions" && options.permissions) {
167
193
  const { config } = options.permissions;
168
194
  const screen = permissionScreen({
@@ -203,6 +229,17 @@ function pageContent(options, url) {
203
229
  else if (state === "signing-in" && signIn) {
204
230
  content.push(h("form", { method: "post", action: signIn.action, "data-auto-sign-in": true }, h("input", { type: "hidden", name: "key", value: signIn.key }), h("div", { className: "actions" }, h(Button, { type: "submit" }, "Continue to Oyster"), link("Having trouble?", url("/login/key-help"), true))));
205
231
  }
232
+ else if (state === "open-preview" && options.previewEntry) {
233
+ content.push(h("div", {
234
+ "data-port-preview-entry": true,
235
+ "data-action": options.previewEntry.action,
236
+ "data-port": options.previewEntry.port,
237
+ "data-computer-id": options.previewEntry.computerId,
238
+ "data-refusal": options.previewEntry.refusal,
239
+ }, h("form", { method: "post", action: options.previewEntry.action }, h("div", { className: "actions" }, h(Button, { type: "submit" }, "Open preview"), link("Back to your Oyster", url("/"), true))), options.previewEntry.refusal === undefined
240
+ ? null
241
+ : h("noscript", null, portPreviewRefusalMessage(options.previewEntry.refusal))));
242
+ }
206
243
  else if (state === "key-help") {
207
244
  content.push(h("p", { className: "detail" }, "If the original key is gone, follow the owner recovery instructions. Oyster cannot reveal or reconstruct it. No key reset happens from this page."));
208
245
  actions.push(link("Back to sign-in", url("/login")), link("Read recovery steps", `${docs}/guides/run-your-own-oyster`, true));
@@ -220,7 +257,9 @@ function pageContent(options, url) {
220
257
  : null))));
221
258
  if (state === "desktop-missing")
222
259
  content.push(h("p", { className: "detail" }, "For a local trial, retry the original try command in your terminal with the same project directory and port. If approval was revoked, use App access to review the desktop’s permissions."));
223
- actions.push(link("Read the quickstart", `${docs}/oyster-quickstart`), link("Install an App", `${docs}/agents/build-an-app.md`, true));
260
+ actions.push(link("Read the quickstart", `${docs}/oyster-quickstart`), link("Install an App", `${docs}/agents/build-an-app.md`, true),
261
+ // Ends this browser's session on the server, then returns to sign-in.
262
+ h("form", { method: "post", action: url("/logout") }, h(Button, { type: "submit", variant: "outline" }, "Sign out")));
224
263
  }
225
264
  else {
226
265
  if (state === "server-error")
@@ -238,6 +277,7 @@ function illustration(state, assetUrl) {
238
277
  "login-invalid",
239
278
  "key-help",
240
279
  "signing-in",
280
+ "open-preview",
241
281
  "access-denied",
242
282
  ].includes(state);
243
283
  const art = keyArt
@@ -281,10 +321,16 @@ function illustration(state, assetUrl) {
281
321
  /** One server-rendered Caps composition, usable without styles, art or JS. */
282
322
  export async function hostPage(options) {
283
323
  const { state, title = "Oyster" } = options;
284
- const [baseHeading, eyebrow, description] = copy[state];
285
- const heading = state === "login" && options.returning === true
286
- ? "Welcome back."
287
- : baseHeading;
324
+ const referrerPolicy = state === "open-preview" ? portPreviewReferrerPolicy : "no-referrer";
325
+ const [baseHeading, eyebrow, baseDescription] = copy[state];
326
+ const description = state === "open-preview" && options.previewEntry
327
+ ? `An App asked to open port ${String(options.previewEntry.port)} on Computer ${options.previewEntry.computerId}, signed in as you. Nothing opens until you choose Open preview.`
328
+ : baseDescription;
329
+ const heading = state === "preview"
330
+ ? (options.preview?.appName ?? "Opening preview…")
331
+ : state === "login" && options.returning === true
332
+ ? "Welcome back."
333
+ : baseHeading;
288
334
  const url = (path) => options.oysterUrl ? new URL(path, options.oysterUrl).href : path;
289
335
  // A failed decorative module must still leave the form and recovery readable.
290
336
  let assets;
@@ -300,23 +346,42 @@ export async function hostPage(options) {
300
346
  return asset ? url(asset.path) : undefined;
301
347
  };
302
348
  const { content, actions } = pageContent(options, url);
349
+ const script = state === "open-preview" ? "port-preview.js" : "host-page.js";
303
350
  const body = renderToStaticMarkup(h("html", { lang: "en" }, h("head", null, h("meta", { charSet: "utf-8" }), h("meta", {
304
351
  name: "viewport",
305
352
  content: "width=device-width,initial-scale=1",
306
- }), h("meta", { name: "referrer", content: "no-referrer" }), h("title", null, `${heading} · ${title}`), h("link", {
353
+ }), h("meta", { name: "referrer", content: referrerPolicy }), h("title", null, `${heading} · ${title}`), h("link", {
307
354
  rel: "icon",
308
355
  type: "image/svg+xml",
309
356
  href: fungiFaviconHref,
310
- }), ...(options.stylesheets ?? []).map((href) => h("link", { key: href, rel: "stylesheet", href: url(href) })), assetUrl("layout.css")
357
+ }), ...(options.stylesheets ?? []).map((href) => h("link", { key: href, rel: "stylesheet", href: url(href) })), options.inlineStyles
358
+ ? h("style", {
359
+ dangerouslySetInnerHTML: { __html: options.inlineStyles },
360
+ })
361
+ : null, !options.inlineStyles && assetUrl("layout.css")
311
362
  ? h("link", { rel: "stylesheet", href: assetUrl("layout.css") })
312
- : null), h("body", null, h("header", { className: "page-header" }, h("div", { className: "brand" }, "oyster", h("small", null, "by fungi.computer")), h("nav", { className: "page-nav", "aria-label": "Oyster" }, h("a", { href: url("/") }, "Your Oyster"), h("a", { href: docs }, "Help & docs"))), h("main", { className: "stage" }, h("div", { className: "card-holder" }, illustration(state, assetUrl)), h("section", { className: "copy", "aria-labelledby": "page-heading" }, h("p", { className: "eyebrow" }, eyebrow), h("h1", { className: "heading", id: "page-heading" }, heading), h("p", { className: "description" }, description), ...content, actions.length
363
+ : null), h("body", { className: state === "preview" ? "preview-entry" : undefined }, h("header", { className: "page-header" }, h("div", { className: "brand" }, "oyster", h("small", null, "by fungi.computer")), h("nav", { className: "page-nav", "aria-label": "Oyster" }, h("a", { href: url("/") }, "Your Oyster"), h("a", { href: docs }, "Help & docs"))), h("main", { className: "stage" }, state === "preview"
364
+ ? null
365
+ : h("div", { className: "card-holder" }, illustration(state, assetUrl)), h("section", { className: "copy", "aria-labelledby": "page-heading" }, h("p", { className: "eyebrow" }, eyebrow), h("h1", { className: "heading", id: "page-heading" }, heading), h("p", { className: "description" }, state === "preview"
366
+ ? options.preview?.appName
367
+ ? `Preview this change to ${options.preview.appName} before you merge it.`
368
+ : "Opening preview…"
369
+ : description), ...content, actions.length
313
370
  ? h("div", { className: "actions" }, ...actions)
314
371
  : null, h("p", { className: "helper" }, state === "login" || state === "login-invalid"
315
372
  ? "Your key is sent only to this Oyster."
316
- : state === "not-found"
373
+ : state === "not-found" ||
374
+ state === "open-preview" ||
375
+ state === "preview"
317
376
  ? null
318
- : h("a", { href: `${docs}/agents/index.md` }, "Hand your LLM the setup guide →")))), h("footer", { className: "page-footer" }, h("span", null, "Oyster · A home for your Apps")), assetUrl("host-page.js")
319
- ? h("script", { type: "module", src: assetUrl("host-page.js") })
377
+ : h("a", { href: `${docs}/agents/index.md` }, "Hand your LLM the setup guide →")))), h("footer", { className: "page-footer" }, h("span", null, "Oyster · A home for your Apps")), state !== "preview" && assetUrl(script)
378
+ ? h("script", { type: "module", src: assetUrl(script) })
379
+ : null, options.preview?.preparing
380
+ ? h("script", {
381
+ dangerouslySetInnerHTML: {
382
+ __html: "document.forms[0].requestSubmit()",
383
+ },
384
+ })
320
385
  : null, options.permissions
321
386
  ? h("script", {
322
387
  type: "application/json",
@@ -334,9 +399,23 @@ export async function hostPage(options) {
334
399
  "Content-Type": "text/html; charset=utf-8",
335
400
  "Cache-Control": "no-store",
336
401
  "X-Content-Type-Options": "nosniff",
337
- "Referrer-Policy": "no-referrer",
402
+ "Referrer-Policy": referrerPolicy,
338
403
  "X-Robots-Tag": "noindex, nofollow",
339
404
  Vary: "Accept",
340
405
  },
341
406
  });
342
407
  }
408
+ /** Maintained Caps and Oyster page tokens, embedded for the private preview. */
409
+ export async function previewStyles() {
410
+ const [assets, sources] = await Promise.all([pageAssets(), loadPageAssets()]);
411
+ const layout = assets["layout.css"];
412
+ if (layout === undefined)
413
+ throw new Error("Oyster page styles unavailable");
414
+ return sources.shellStyles + sources.loginFontStyles + layout.source;
415
+ }
416
+ /** Trusted preview chrome; the candidate cannot supply HTML or host authority. */
417
+ export async function previewChrome(notice) {
418
+ return (`<style>${await previewStyles()}</style>` +
419
+ renderToStaticMarkup(h("header", { className: "preview-bar", "data-preview-bar": "" }, h("span", null, "Preview"), h("span", { "aria-hidden": true }, "·"), h("span", { className: "preview-app", title: notice.appName }, notice.appName), h("span", { className: "preview-build" }, `build ${notice.revision}`), h("span", { "aria-hidden": true }, "·"), h("span", { id: "preview-state" }, notice.status), h("details", { className: "preview-details" }, h(Button, { asChild: true, size: "xs", variant: "ghost" }, h("summary", null, "Details")), h(Card, { className: "preview-explanation" }, h(CardContent, null, h("p", null, notice.explanation), h("p", null, "This preview only shows the page. It cannot use your files or run commands."), h("p", null, "Merge in Bonsai to build and install the change. Reload this page to open the preview again.")))))) +
420
+ renderToStaticMarkup(h("section", { id: "preview-expired", hidden: true, role: "status" }, h("p", null, "This preview expired. Reload to open it again."), h(Button, { asChild: true, size: "sm" }, h("a", { href: notice.entry }, "Reload")))));
421
+ }
package/dist/host.d.ts CHANGED
@@ -56,6 +56,8 @@ export type OysterAuth = Readonly<{
56
56
  authenticate: (request: Request) => Promise<OysterAuthResult>;
57
57
  /** Handle the browser sign-in form post; returns the response to send. */
58
58
  login?: (request: Request) => Promise<Response>;
59
+ /** End this browser's session on the server and clear its cookie. */
60
+ logout?: (request: Request) => Promise<Response>;
59
61
  }>;
60
62
  /** A serializable registry commit result, including across native DO RPC. */
61
63
  export type InstallationCommit = Readonly<{
@@ -248,6 +250,12 @@ export type OysterHost = Readonly<{
248
250
  /** Further routes the host adds (keys, webhooks, builds); each declares
249
251
  * its own requirement and receives the admitted principal from it. */
250
252
  ownerRoutes?: Routes<OysterEnv>;
253
+ /**
254
+ * Serve the owner's confirm page for private port previews at
255
+ * `/computers/:computerId/ports/:port`. Only the owner's own click on it
256
+ * posts to the owner route that issues the preview; nothing submits it.
257
+ */
258
+ portPreviewEntry?: boolean;
251
259
  /** Adapters granted only when the Release declares them and admission passes. */
252
260
  capabilities?: readonly OysterCapability[];
253
261
  /**
package/dist/host.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { parsePortPreviewPort, portPreviewReferrerPolicy, portPreviewRefusalEntry, } from "./port-preview-entry.js";
1
2
  import { hostGateFacts, releaseCache } from "./internal/host-gate.js";
2
3
  import { InstallationOperationError, installationCommandIds, installationRequestIdSchema, installationRecoverySelectionSchema, installationWaitQuerySchema, maxSettlementWaitMs, } from "./installation-operations.js";
3
4
  import { completedInstallationResponse, observeInstallation, InstallationObservationError, } from "./installation-client.js";
@@ -384,15 +385,49 @@ export function oysterRouteTable(host) {
384
385
  ...options,
385
386
  });
386
387
  };
388
+ const previewHeaders = {
389
+ "Cache-Control": "no-store",
390
+ "Referrer-Policy": portPreviewReferrerPolicy,
391
+ "Cross-Origin-Opener-Policy": "same-origin",
392
+ // Chromium applies form-action to the POST redirect too.
393
+ "Content-Security-Policy": "default-src 'none'; script-src 'self'; connect-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src data:; form-action 'self' https:; frame-ancestors 'none'; base-uri 'none'",
394
+ };
395
+ const previewPage = async (entry, status = 200) => {
396
+ const response = await page("open-preview", {
397
+ previewEntry: entry,
398
+ status,
399
+ });
400
+ for (const [name, value] of Object.entries(previewHeaders))
401
+ response.headers.set(name, value);
402
+ return response;
403
+ };
387
404
  table.get("/_oyster/host-assets/*", publicRoute("content-addressed host illustrations and layout"), (context) => serveHostPageAsset(new URL(context.req.url).pathname));
388
405
  table.get("/login", publicRoute("the sign-in form"), (context) => page("login", {
389
406
  returning: getCookie(context, returningCookieName) === "1",
390
407
  usedLink: context.req.query("link") === "used",
391
408
  }));
409
+ if (host.portPreviewEntry === true)
410
+ table.get("/computers/:computerId/ports/:port", publicRoute("the owner's preview confirm page; only their own click posts to the owner route"), async (context) => {
411
+ // Only route text is shown: this public page reads nothing about the
412
+ // Computer, so a visitor learns nothing from it.
413
+ const computerId = context.req.param("computerId");
414
+ const portParam = context.req.param("port");
415
+ const port = parsePortPreviewPort(portParam);
416
+ if (port === undefined)
417
+ return context.body(null, 404);
418
+ return previewPage({
419
+ action: context.req.path,
420
+ port,
421
+ computerId,
422
+ });
423
+ });
392
424
  table.get("/login/key-help", publicRoute("owner key recovery instructions, without a reset"), () => page("key-help"));
393
425
  table.post("/login", door("the host's own sign-in checks the posted key"), (context) => host.auth.login === undefined
394
426
  ? refusal(404, "Sign-in is not available")
395
427
  : host.auth.login(context.req.raw));
428
+ table.post("/logout", door("the host's own sign-out revokes the presented session"), (context) => host.auth.logout === undefined
429
+ ? refusal(404, "Sign-out is not available")
430
+ : host.auth.logout(context.req.raw));
396
431
  if (host.mcp !== undefined) {
397
432
  const mcp = host.mcp;
398
433
  table.all("/mcp", door("MCP authenticates every request; tools read this module's reach"), (context) => mcp.handleRequest(context.req.raw));
@@ -1576,8 +1611,10 @@ export function oysterRouteTable(host) {
1576
1611
  // Present errors only at the host's document boundary. App assets, transports
1577
1612
  // and API responses retain their status, headers and machine-readable body.
1578
1613
  const appEntry = match("/apps/:installationId/", { decode: false });
1614
+ const previewEntryPath = match("/computers/:computerId/ports/:port", { decode: false });
1579
1615
  const documentResponse = async (request, response) => {
1580
1616
  const path = new URL(request.url).pathname;
1617
+ const previewTarget = host.portPreviewEntry === true ? previewEntryPath(path) : false;
1581
1618
  if (capabilityRoutes.some((route) => route.matches(path)))
1582
1619
  return response;
1583
1620
  const document = parseAccept(request.headers.get("Accept") ?? "").find((entry) => entry.q > 0 && ["text/html", "application/json"].includes(entry.type))?.type === "text/html" &&
@@ -1592,9 +1629,17 @@ export function oysterRouteTable(host) {
1592
1629
  "/mcp",
1593
1630
  "/git",
1594
1631
  ].some((prefix) => path === prefix || path.startsWith(`${prefix}/`)))) ||
1595
- (request.method === "POST" && path === "/login"));
1632
+ (request.method === "POST" &&
1633
+ (path === "/login" || Boolean(previewTarget))));
1596
1634
  if (!document || response.status < 400)
1597
1635
  return response;
1636
+ const previewEntry = request.method === "POST" && previewTarget
1637
+ ? await portPreviewRefusalEntry(response, {
1638
+ action: path,
1639
+ computerId: previewTarget.params.computerId,
1640
+ port: previewTarget.params.port,
1641
+ })
1642
+ : undefined;
1598
1643
  const state = path === "/login" && [400, 401].includes(response.status)
1599
1644
  ? "login-invalid"
1600
1645
  : response.status === 403
@@ -1604,17 +1649,22 @@ export function oysterRouteTable(host) {
1604
1649
  : "not-found";
1605
1650
  let rendered;
1606
1651
  try {
1607
- rendered = await page(state, { status: response.status });
1652
+ rendered = previewEntry
1653
+ ? await previewPage(previewEntry, response.status)
1654
+ : await page(state, { status: response.status });
1608
1655
  }
1609
1656
  catch (cause) {
1610
1657
  if (!(cause instanceof PageAssetsLoadError))
1611
1658
  throw cause;
1612
1659
  console.error("Host page assets unavailable; serving recovery document", cause);
1613
- rendered = await renderHostPage({
1614
- state,
1615
- title,
1616
- status: response.status,
1617
- });
1660
+ rendered = await renderHostPage(previewEntry
1661
+ ? {
1662
+ state: "open-preview",
1663
+ title,
1664
+ status: response.status,
1665
+ previewEntry,
1666
+ }
1667
+ : { state, title, status: response.status });
1618
1668
  }
1619
1669
  // Keep timing, robots and retry metadata from the original refusal.
1620
1670
  response.headers.forEach((value, name) => {
@@ -1628,6 +1678,9 @@ export function oysterRouteTable(host) {
1628
1678
  ].includes(name))
1629
1679
  rendered.headers.set(name, value);
1630
1680
  });
1681
+ if (previewEntry)
1682
+ for (const [name, value] of Object.entries(previewHeaders))
1683
+ rendered.headers.set(name, value);
1631
1684
  return rendered;
1632
1685
  };
1633
1686
  return {
@@ -0,0 +1,25 @@
1
+ /** How long one browser sign-in lasts, absolutely: no sliding renewal. */
2
+ export declare const ownerSessionLifetimeMs: number;
3
+ /**
4
+ * The server side of owner browser sessions. The cookie carries a random
5
+ * session id; the store keeps only its digest, the owner it signs in, and an
6
+ * expiry. Logging out revokes the row, so a copied cookie stops working.
7
+ */
8
+ export type OwnerSessions = Readonly<{
9
+ /** Record a new session for `owner` opened at `now`; it ends `ownerSessionLifetimeMs` later. */
10
+ open(owner: string, digest: string, now: number): Promise<void>;
11
+ /** The owner a live session signs in, or null for an unknown, expired or revoked one. */
12
+ owner(digest: string, now: number): Promise<string | null>;
13
+ /** Revoke one session; revoking an unknown session does nothing. */
14
+ revoke(digest: string): Promise<void>;
15
+ }>;
16
+ /** The synchronous SQL a Durable Object or SQLite host gives the store. */
17
+ export type OwnerSessionSql = Readonly<{
18
+ /** Run one statement with positional bindings. */
19
+ exec(query: string, ...bindings: (string | number | null)[]): {
20
+ /** The statement's rows, decoded by the store. */
21
+ toArray(): readonly object[];
22
+ };
23
+ }>;
24
+ /** Owner sessions over one store's SQL. */
25
+ export declare function ownerSessionStore(sql: OwnerSessionSql): OwnerSessions;
@@ -0,0 +1,50 @@
1
+ import * as Schema from "effect/Schema";
2
+ /** How long one browser sign-in lasts, absolutely: no sliding renewal. */
3
+ export const ownerSessionLifetimeMs = 30 * 24 * 60 * 60 * 1000;
4
+ const sessionRows = Schema.Array(Schema.Struct({ owner: Schema.String, expires_at: Schema.Number }));
5
+ /**
6
+ * The session table, created on first use. Older stores have no sessions,
7
+ * so the browser cookies they issued (a digest of the owner key) match no
8
+ * row here and fail closed to the sign-in page.
9
+ */
10
+ function ensureOwnerSessions(sql) {
11
+ sql.exec(`CREATE TABLE IF NOT EXISTS oyster_owner_sessions (
12
+ session_digest TEXT PRIMARY KEY, owner TEXT NOT NULL,
13
+ expires_at INTEGER NOT NULL) STRICT`);
14
+ }
15
+ /** Owner sessions over one store's SQL. */
16
+ export function ownerSessionStore(sql) {
17
+ let ready = false;
18
+ const table = () => {
19
+ if (!ready)
20
+ ensureOwnerSessions(sql);
21
+ ready = true;
22
+ return sql;
23
+ };
24
+ return {
25
+ open(owner, digest, now) {
26
+ const store = table();
27
+ // Expired rows go when a new session opens, so the table stays small.
28
+ store.exec("DELETE FROM oyster_owner_sessions WHERE expires_at <= ?", now);
29
+ store.exec("INSERT INTO oyster_owner_sessions (session_digest, owner, expires_at) VALUES (?, ?, ?)", digest, owner, now + ownerSessionLifetimeMs);
30
+ return Promise.resolve();
31
+ },
32
+ owner(digest, now) {
33
+ const store = table();
34
+ const [row] = Schema.decodeUnknownSync(sessionRows)(store
35
+ .exec("SELECT owner, expires_at FROM oyster_owner_sessions WHERE session_digest = ?", digest)
36
+ .toArray());
37
+ if (row === undefined)
38
+ return Promise.resolve(null);
39
+ if (row.expires_at <= now) {
40
+ store.exec("DELETE FROM oyster_owner_sessions WHERE session_digest = ?", digest);
41
+ return Promise.resolve(null);
42
+ }
43
+ return Promise.resolve(row.owner);
44
+ },
45
+ revoke(digest) {
46
+ table().exec("DELETE FROM oyster_owner_sessions WHERE session_digest = ?", digest);
47
+ return Promise.resolve();
48
+ },
49
+ };
50
+ }
@@ -11,12 +11,30 @@ async function bootHost() {
11
11
  throw new Error("Host boot configuration unavailable");
12
12
  const config = bootUiSchema
13
13
  .pick({ identity: true })
14
- .extend({ entry: z.url() })
14
+ .extend({
15
+ identity: bootUiSchema.shape.identity.extend({
16
+ surfaceId: z.string().min(1).max(256),
17
+ }),
18
+ entry: z.url(),
19
+ expiresAt: z.number().optional(),
20
+ })
15
21
  .parse(JSON.parse(element.textContent));
16
22
  const frame = document.getElementById("candidate");
17
23
  if (!(frame instanceof HTMLIFrameElement) || frame.contentWindow === null)
18
24
  throw new Error("Host candidate frame unavailable");
19
- const denied = () => Promise.reject(new Error("No grants during host boot"));
25
+ if (config.expiresAt !== undefined) {
26
+ window.setTimeout(() => {
27
+ frame.hidden = true;
28
+ document.querySelector(".preview-details")?.removeAttribute("open");
29
+ const expired = document.getElementById("preview-expired");
30
+ if (expired !== null)
31
+ expired.hidden = false;
32
+ const state = document.getElementById("preview-state");
33
+ if (state !== null)
34
+ state.textContent = "expired";
35
+ }, Math.max(0, config.expiresAt - Date.now()));
36
+ }
37
+ const denied = () => Promise.reject(new Error("No grants in this preview"));
20
38
  const connection = connectAppHost({
21
39
  appWindow: frame.contentWindow,
22
40
  expectedAppOrigin: "null",
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,33 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useEffect } from "react";
3
+ import { createRoot } from "react-dom/client";
4
+ import { Button } from "@fungi.computer/caps/components/button";
5
+ import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@fungi.computer/caps/components/dialog";
6
+ import { Toaster, toast } from "@fungi.computer/caps/components/toaster";
7
+ import { portPreviewEntrySchema, portPreviewRefusalMessage, } from "../port-preview-entry.js";
8
+ import { bootstrapIsolatedPageTheme } from "./isolated-page-theme.js";
9
+ const root = document.querySelector("[data-port-preview-entry]");
10
+ if (root === null)
11
+ throw new Error("Port preview confirmation is missing");
12
+ const entry = portPreviewEntrySchema.parse({
13
+ action: root.dataset.action,
14
+ computerId: root.dataset.computerId,
15
+ port: Number(root.dataset.port),
16
+ refusal: root.dataset.refusal,
17
+ });
18
+ const toasterId = "port-preview";
19
+ function PortPreviewDialog() {
20
+ useEffect(() => {
21
+ if (entry.refusal !== undefined)
22
+ toast.error(portPreviewRefusalMessage(entry.refusal), { toasterId });
23
+ }, []);
24
+ return (_jsxs(_Fragment, { children: [_jsx(Dialog, { defaultOpen: true, onOpenChange: (open) => {
25
+ if (!open)
26
+ window.location.assign("/");
27
+ }, children: _jsx(DialogContent, { children: _jsxs("form", { method: "post", action: entry.action, children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { children: "Open this preview?" }), _jsx(DialogDescription, { children: "An App asked to open a private preview using your Oyster sign-in. Only continue if you expected it." })] }), _jsxs("dl", { className: "mt-md text-sm", children: [_jsxs("div", { className: "flex h-8 items-center justify-between gap-sm", "data-preview-fact": true, children: [_jsx("dt", { children: "Computer" }), _jsx("dd", { className: "min-w-0 truncate font-mono", children: entry.computerId })] }), _jsxs("div", { className: "flex h-8 items-center justify-between gap-sm", "data-preview-fact": true, children: [_jsx("dt", { children: "Port" }), _jsx("dd", { className: "font-mono", children: entry.port })] })] }), _jsxs(DialogFooter, { className: "mt-lg", children: [_jsx(DialogClose, { render: _jsx(Button, { variant: "outline", size: "sm" }), children: "Cancel" }), _jsx(Button, { type: "submit", size: "sm", children: "Open preview" })] })] }) }) }), _jsx(Toaster, { id: toasterId })] }));
28
+ }
29
+ // The native form remains usable without JavaScript. Enhance it with Caps;
30
+ // no script submits the form or requests preview credentials.
31
+ bootstrapIsolatedPageTheme();
32
+ document.body.replaceChildren(root);
33
+ createRoot(root).render(_jsx(PortPreviewDialog, {}));