@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
@@ -392,7 +392,7 @@ export class ComputerDO extends NativeComputerDO {
392
392
  async #previewInstallation(selector) {
393
393
  const owner = await (await standaloneTenancy(this.previewBindings)).owner();
394
394
  if (selector.ownerId !== owner?.actor.memberId)
395
- throw new PreviewRefused();
395
+ throw new PreviewRefused("owner_required");
396
396
  const current = await this.previewBindings.REGISTRY.getByName("registry").get(selector.installationId);
397
397
  if (current === null ||
398
398
  "kind" in current ||
@@ -400,14 +400,14 @@ export class ComputerDO extends NativeComputerDO {
400
400
  JSON.stringify(selectionOf(current)) !==
401
401
  JSON.stringify(selector.selection) ||
402
402
  current.release.artifact.artifactDigest !== selector.artifactDigest)
403
- throw new PreviewRefused();
403
+ throw new PreviewRefused("app_not_allowed");
404
404
  return current;
405
405
  }
406
406
  async #currentPreview(selector) {
407
407
  const current = await this.#previewInstallation(selector);
408
408
  const verified = await verifyRelease(r2ArtifactStore(this.previewBindings.RELEASES), current.release, undefined, false);
409
409
  if (!verified.declaration?.capabilities.includes("computer.execute"))
410
- throw new PreviewRefused();
410
+ throw new PreviewRefused("app_not_allowed");
411
411
  await this.#previewInstallation(selector);
412
412
  }
413
413
  async #previewOwner() {
@@ -415,7 +415,7 @@ export class ComputerDO extends NativeComputerDO {
415
415
  return this.#preview;
416
416
  const origins = await previewOrigins(this.previewBindings);
417
417
  if (origins === null)
418
- throw new PreviewRefused();
418
+ throw new PreviewRefused("preview_not_configured");
419
419
  await this.listPortsAfterAcceptance(() => undefined);
420
420
  this.#preview = createStandalonePreview(this.state.storage, this.#id(), origins, {
421
421
  accept: (ownerId) => {
@@ -486,7 +486,7 @@ export class ComputerDO extends NativeComputerDO {
486
486
  async #portPreviews(authority, selectorInput) {
487
487
  const selector = Schema.decodeUnknownSync(previewSelectorSchema)(selectorInput);
488
488
  if (authority.provenance.actor !== `owner:${selector.ownerId}`)
489
- throw new PreviewRefused();
489
+ throw new PreviewRefused("app_not_allowed");
490
490
  this.#accept(authority, "listPorts");
491
491
  await this.#currentPreview(selector);
492
492
  const ports = await this.listPortsAfterAcceptance(() => {
@@ -505,13 +505,17 @@ export class ComputerDO extends NativeComputerDO {
505
505
  async issuePortConnect(ownerId, port) {
506
506
  const owner = await (await standaloneTenancy(this.previewBindings)).owner();
507
507
  if (owner?.actor.memberId !== ownerId)
508
- return null;
508
+ return { kind: "refused", reason: "owner_required" };
509
509
  try {
510
- return await (await this.#previewOwner()).issueOwner(ownerId, port);
510
+ const issued = await (await this.#previewOwner()).issueOwner(ownerId, port);
511
+ return { kind: "issued", previewUrl: issued.previewUrl };
511
512
  }
512
513
  catch (cause) {
513
- if (cause instanceof PreviewRefused || cause instanceof PortAccessError)
514
- return null;
514
+ if (cause instanceof PreviewRefused)
515
+ return { kind: "refused", reason: cause.reason };
516
+ if (cause instanceof PortAccessError &&
517
+ (cause.reason === "unexposed" || cause.reason === "capacity"))
518
+ return { kind: "refused", reason: cause.reason };
515
519
  throw cause;
516
520
  }
517
521
  }
@@ -1,6 +1,7 @@
1
1
  import * as Schema from "effect/Schema";
2
2
  import { ComputerPortAccess } from "@fungi.computer/computer/port-access";
3
3
  import type { OysterEnv } from "../host.js";
4
+ import { type PortPreviewIssue, type PortPreviewIssueRefusal } from "../port-preview-entry.js";
4
5
  export declare const previewSelectorSchema: Schema.Struct<{
5
6
  readonly ownerId: Schema.NonEmptyString;
6
7
  readonly installationId: Schema.NonEmptyString;
@@ -30,6 +31,8 @@ export type StandalonePreviewEnv = Readonly<{
30
31
  }>;
31
32
  export declare function previewOrigins(env: StandalonePreviewEnv): Promise<PreviewOrigins | null>;
32
33
  export declare class PreviewRefused extends Error {
34
+ readonly reason: PortPreviewIssueRefusal;
35
+ constructor(reason: PortPreviewIssueRefusal);
33
36
  }
34
37
  export type PreviewNative = Readonly<{
35
38
  accept: (ownerId: string) => void;
@@ -45,10 +48,12 @@ export declare function createStandalonePreview(storage: ConstructorParameters<t
45
48
  fetch(port: number, request: Request): Promise<Response>;
46
49
  };
47
50
  export declare function standalonePreviewRequest(request: Request, env: StandalonePreviewEnv, ownsComputer: (computerId: string) => Promise<boolean>, forward: (computerId: string, port: number, request: Request) => Promise<Response>): Promise<Response | null>;
48
- /** Establish a top-level same-site document before the owner's Strict-cookie POST. */
51
+ /**
52
+ * Issue a private port preview from the owner's own click on the host's
53
+ * confirm page (`OysterHost.portPreviewEntry`), never from a submit no person
54
+ * made.
55
+ */
49
56
  export declare function standalonePortEntryRoutes(ports: Readonly<{
50
57
  ownsComputer: (computerId: string) => Promise<boolean>;
51
- issue: (computerId: string, ownerId: string, port: number) => Promise<{
52
- previewUrl: string;
53
- } | null>;
58
+ issue: (computerId: string, ownerId: string, port: number) => Promise<PortPreviewIssue>;
54
59
  }>): import("../authorization.js").Routes<OysterEnv>;
@@ -1,11 +1,12 @@
1
1
  import * as Schema from "effect/Schema";
2
2
  import * as z from "zod";
3
- import { ComputerPortAccess, PortAccessError, } from "@fungi.computer/computer/port-access";
3
+ import { ComputerPortAccess } from "@fungi.computer/computer/port-access";
4
4
  import { selectionSchema } from "../index.js";
5
5
  import { sha256DigestSchema } from "@fungi.computer/puffball/effect";
6
6
  import { computerPortInputSchema } from "@fungi.computer/computer-contract";
7
- import { owner, publicRoute, routes } from "../authorization.js";
8
- import { html } from "hono/html";
7
+ import { owner, routes } from "../authorization.js";
8
+ import { sameOriginRequest } from "../request-origin.js";
9
+ import { parsePortPreviewPort, portPreviewIssueSchema, portPreviewRefusalMessage, portPreviewRefusalStatus, } from "../port-preview-entry.js";
9
10
  export const previewSelectorSchema = Schema.Struct({
10
11
  ownerId: Schema.NonEmptyString,
11
12
  installationId: Schema.NonEmptyString,
@@ -60,16 +61,21 @@ export async function previewOrigins(env) {
60
61
  };
61
62
  }
62
63
  export class PreviewRefused extends Error {
64
+ reason;
65
+ constructor(reason) {
66
+ super(`Port preview ${reason}`);
67
+ this.reason = reason;
68
+ }
63
69
  }
64
70
  // The retained flat hostname uses the Computer's non-secret identity. Fleet
65
71
  // IDs have a computer_ prefix; configured standalone IDs can be simple labels.
66
72
  const hostnameComputer = z.string().regex(/^(?:computer_)?[a-z0-9]+$/u);
67
73
  function previewUrl(origins, computerId, port) {
68
74
  if (!hostnameComputer.safeParse(computerId).success)
69
- throw new PreviewRefused();
75
+ throw new PreviewRefused("invalid_computer_address");
70
76
  const label = `${computerId.replace("computer_", "computer-")}-${String(port)}`;
71
77
  if (label.length > 63)
72
- throw new PreviewRefused();
78
+ throw new PreviewRefused("invalid_computer_address");
73
79
  const result = new URL(origins.preview);
74
80
  result.hostname = `${label}.${result.hostname}`;
75
81
  return result;
@@ -160,49 +166,34 @@ export async function standalonePreviewRequest(request, env, ownsComputer, forwa
160
166
  return new Response(null, { status: 404 });
161
167
  return forward(computerId, port.data.port, request);
162
168
  }
163
- /** Establish a top-level same-site document before the owner's Strict-cookie POST. */
169
+ /**
170
+ * Issue a private port preview from the owner's own click on the host's
171
+ * confirm page (`OysterHost.portPreviewEntry`), never from a submit no person
172
+ * made.
173
+ */
164
174
  export function standalonePortEntryRoutes(ports) {
165
175
  const path = "/computers/:computerId/ports/:port";
166
- return routes()
167
- .get(path, publicRoute("a preview entry document; only the owner-admitted POST issues a token"), (context) => {
176
+ return routes().post(path, owner("direct"), async (context, { principal }) => {
168
177
  context.header("Cache-Control", "no-store");
169
- context.header("Referrer-Policy", "no-referrer");
170
- context.header("Cross-Origin-Opener-Policy", "same-origin");
171
- // Chromium applies form-action to the POST redirect as well. The fixed
172
- // same-origin form must be able to finish on the HTTPS preview site.
173
- context.header("Content-Security-Policy", "default-src 'none'; script-src 'unsafe-inline'; form-action https:; frame-ancestors 'none'; base-uri 'none'");
174
- return context.html(html `<!doctype html><title>Open preview</title>
175
- <main>
176
- <form method="post" action="${context.req.path}">
177
- <button>Open preview</button>
178
- </form>
179
- <script>
180
- document.forms[0].requestSubmit();
181
- </script>
182
- </main>`);
183
- })
184
- .post(path, owner("direct"), async (context, { principal }) => {
178
+ const refuse = (reason) => context.json({ error: reason, message: portPreviewRefusalMessage(reason) }, portPreviewRefusalStatus[reason]);
179
+ // Activation alone does not prove origin: a clicked sibling-site form
180
+ // can carry both user activation and the owner's Strict cookie.
181
+ if (!sameOriginRequest(context.req.raw))
182
+ return refuse("same_origin_required");
183
+ // Require a user-activated navigation, never an automatic entry submit.
184
+ if (context.req.header("Sec-Fetch-User") !== "?1")
185
+ return refuse("confirmation_required");
185
186
  const computerId = context.req.param("computerId");
186
187
  const portParam = context.req.param("port");
187
- const port = computerPortInputSchema.safeParse({
188
- port: Number(portParam),
189
- });
190
- if (!/^[1-9][0-9]{0,4}$/u.test(portParam) ||
191
- !port.success ||
192
- !(await ports.ownsComputer(computerId)))
193
- return context.body(null, 404);
194
- try {
195
- const issued = await ports.issue(computerId, principal.actor.memberId, port.data.port);
196
- if (issued === null)
197
- return context.body(null, 404);
198
- context.header("Cache-Control", "no-store");
199
- context.header("Referrer-Policy", "no-referrer");
200
- return context.redirect(issued.previewUrl, 302);
201
- }
202
- catch (cause) {
203
- if (cause instanceof PreviewRefused || cause instanceof PortAccessError)
204
- return context.body(null, 404);
205
- throw cause;
206
- }
188
+ const port = parsePortPreviewPort(portParam);
189
+ if (port === undefined)
190
+ return refuse("invalid_port");
191
+ if (!(await ports.ownsComputer(computerId)))
192
+ return refuse("computer_not_found");
193
+ const issued = portPreviewIssueSchema.parse(await ports.issue(computerId, principal.actor.memberId, port));
194
+ if (issued.kind === "refused")
195
+ return refuse(issued.reason);
196
+ context.header("Referrer-Policy", "no-referrer");
197
+ return context.redirect(issued.previewUrl, 302);
207
198
  });
208
199
  }
@@ -26,7 +26,7 @@ export declare class StandaloneTenants extends TenancyRegistryDO {
26
26
  seed(input: StandaloneSeed): Promise<Tenant | StandaloneSeedRefusal>;
27
27
  }
28
28
  /** The same trusted bindings are used by HTTP, MCP and cold root readers. */
29
- export type StandaloneTenancyEnv = Pick<OysterGitWorkerEnv, "OYSTER_ORIGIN" | "OYSTER_OWNER_NAME" | "OYSTER_OWNER_KEY" | "KEYS"> & Readonly<{
29
+ export type StandaloneTenancyEnv = Pick<OysterGitWorkerEnv, "OYSTER_ORIGIN" | "OYSTER_OWNER_NAME" | "OYSTER_OWNER_KEY" | "KEYS" | "REGISTRY"> & Readonly<{
30
30
  TENANTS: DurableObjectNamespace<StandaloneTenants>;
31
31
  /** Opt-in Cloudflare Access sign-in: the team domain, with the AUD tag. */
32
32
  OYSTER_ACCESS_TEAM_DOMAIN?: string;
@@ -5,6 +5,7 @@ import { ownerKey } from "../tenancy/owner-key.js";
5
5
  import { loopbackAliasLocation } from "../tenancy/registry-record.js";
6
6
  import { hosts } from "../tenancy/resolve.js";
7
7
  import { ownerOrKeyAuth } from "../auth.js";
8
+ import { registryOwnerSessions } from "../workers.js";
8
9
  import { HTTPException } from "hono/http-exception";
9
10
  import { defaultTenant, tenantScope, } from "../tenant.js";
10
11
  import * as Schema from "effect/Schema";
@@ -182,8 +183,10 @@ async function composeTenancy(env) {
182
183
  const admitted = (admission) => {
183
184
  const view = admittedRegistry(admission);
184
185
  const owner = ownerOf(admission);
186
+ const sessions = registryOwnerSessions(() => env.REGISTRY.getByName(scope.durableName("registry")));
185
187
  const ownerAuth = ownerKey({
186
188
  registry: view,
189
+ sessions: () => sessions,
187
190
  keys: {
188
191
  get: () => Promise.resolve(owner === null
189
192
  ? null
@@ -242,7 +245,7 @@ async function composeTenancy(env) {
242
245
  if (owner === null)
243
246
  return { kind: "refused", status: 403 };
244
247
  const keys = () => env.KEYS.getByName(scope.durableName("keys"));
245
- const auth = ownerOrKeyAuth(env.OYSTER_OWNER_KEY, owner.actor.memberId, keys);
248
+ const auth = ownerOrKeyAuth(env.OYSTER_OWNER_KEY, owner.actor.memberId, sessions, keys);
246
249
  const admission = await auth.authenticate(request);
247
250
  // This entry admits only named keys; the owner key has its own entry.
248
251
  return admission.kind === "admitted" &&
@@ -260,6 +263,9 @@ async function composeTenancy(env) {
260
263
  login: async (request) => routes === undefined
261
264
  ? new Response("Sign-in is not available", { status: 404 })
262
265
  : await routes.fetch(request),
266
+ logout: async (request) => routes === undefined
267
+ ? new Response("Sign-out is not available", { status: 404 })
268
+ : await routes.fetch(request),
263
269
  };
264
270
  };
265
271
  /**
@@ -337,6 +343,8 @@ async function composeTenancy(env) {
337
343
  },
338
344
  login: async (incoming) => (await (await forRequest(incoming))?.login(incoming)) ??
339
345
  new Response("Not found", { status: 404 }),
346
+ logout: async (incoming) => (await (await forRequest(incoming))?.logout(incoming)) ??
347
+ new Response("Not found", { status: 404 }),
340
348
  },
341
349
  };
342
350
  },
@@ -6,6 +6,8 @@
6
6
  import { createOysterGitWorker, createOysterGitMcpOwner, oysterGitRoot, } from "../workers-git.js";
7
7
  import { defaultTenant, tenantScope } from "../tenant.js";
8
8
  import { oysterPrincipalIsOwner } from "../authorization.js";
9
+ import { r2ArtifactStore } from "../workers.js";
10
+ import { standaloneCandidatePreview } from "./candidate-preview.js";
9
11
  import { standaloneComputerControl } from "./computer-control.js";
10
12
  import { standalonePermissionResources } from "./permission-resources.js";
11
13
  import { onBoxVmIngress, ownerLocalBackendDialPath, } from "@fungi.computer/computer";
@@ -20,7 +22,7 @@ import { StandaloneInstance as ComputerInstance } from "./instance.js";
20
22
  // Every guest binding in every frame is this one entrypoint, routed by props.
21
23
  export { OysterBinding } from "./instance.js";
22
24
  import { StandaloneWorkflowRunsBase, } from "./workflows.js";
23
- import { standaloneTenancyForRequest, StandaloneSeedConfigurationChanged, } from "./tenancy.js";
25
+ import { standaloneTenancyForRequest, standaloneTenancy, StandaloneSeedConfigurationChanged, } from "./tenancy.js";
24
26
  export { StandaloneTenants } from "./tenancy.js";
25
27
  import { standalonePreviewRequest, standalonePortEntryRoutes, } from "./preview.js";
26
28
  import { standaloneMachineLinkRoutes, } from "./machine-link.js";
@@ -119,8 +121,19 @@ const standaloneRoot = (selectComputer) => {
119
121
  role: "owner",
120
122
  };
121
123
  },
124
+ // The owner confirms a port preview on the host's own page before the
125
+ // owner route below issues it.
126
+ portPreviewEntry: true,
122
127
  // Operator source seeding and owner builds share the one owner guard.
123
- ownerRoutes: (env, scope) => standaloneOwnerRoutes(env, scope, () => root.hostFor(env, scope)).include(standalonePortEntryRoutes({
128
+ ownerRoutes: (env, scope) => standaloneOwnerRoutes(env, scope, () => root.hostFor(env, scope))
129
+ .include(standaloneCandidatePreview({
130
+ scope,
131
+ secret: env.OYSTER_OWNER_KEY,
132
+ owner: async () => (await standaloneTenancy(env)).owner(),
133
+ readBuild: (jobId) => tenantRegistry(env, scope).readBuild(jobId),
134
+ artifacts: r2ArtifactStore(env.RELEASES),
135
+ }).routes)
136
+ .include(standalonePortEntryRoutes({
124
137
  ownsComputer: (id) => tenantRegistry(env, scope).ownsComputer(id),
125
138
  issue: (id, ownerId, port) => env.COMPUTER.getByName(id).issuePortConnect(ownerId, port),
126
139
  })),
@@ -17,13 +17,16 @@ const starterHomeInstructions = `# Shiitake's instructions
17
17
 
18
18
  These are my standing instructions. They live on my Computer at
19
19
  AGENTS.md and load at the start of every conversation. Read or patch
20
- it with that plain path. My person and I both edit this file.
20
+ it with that plain path after listing \`files.list({path: "."})\` and
21
+ confirming it is present. My person and I both edit this file.
21
22
 
22
23
  ## First conversation
23
24
  My person is new to Fungi. In our first conversation, load the \`setup-fungi\`
24
25
  skill with \`return await skill.load({name: "setup-fungi"});\` inside execute
25
26
  and follow it. If they ask for something specific first, do that, then set up.
26
- When setup is finished, delete this section.
27
+ Continue approved work → useful result → name card → widget approval in one
28
+ flow, resuming after each answer; a work summary does not finish setup. Keep
29
+ setup progress here until the offers are settled, then delete this section.
27
30
 
28
31
  ## About my person
29
32
  (Empty until setup. Fill in: their name, what they want from Fungi, their
@@ -21,7 +21,7 @@ export declare const storageFrameMethods: {
21
21
  };
22
22
  } | {
23
23
  readonly kind: "rejected";
24
- readonly code: "invalid" | "unavailable" | "conflict" | "undeclared_key" | "scope_not_declared" | "owner_required" | "too_large" | "quota_exceeded";
24
+ readonly code: "invalid" | "unavailable" | "conflict" | "owner_required" | "undeclared_key" | "scope_not_declared" | "too_large" | "quota_exceeded";
25
25
  };
26
26
  requiredOperations: () => string[];
27
27
  };
@@ -39,7 +39,7 @@ export declare const storageFrameMethods: {
39
39
  };
40
40
  } | {
41
41
  readonly kind: "rejected";
42
- readonly code: "invalid" | "unavailable" | "conflict" | "undeclared_key" | "scope_not_declared" | "owner_required" | "too_large" | "quota_exceeded";
42
+ readonly code: "invalid" | "unavailable" | "conflict" | "owner_required" | "undeclared_key" | "scope_not_declared" | "too_large" | "quota_exceeded";
43
43
  };
44
44
  requiredOperations: () => string[];
45
45
  };
@@ -56,7 +56,7 @@ export declare const storageFrameMethods: {
56
56
  };
57
57
  } | {
58
58
  readonly kind: "rejected";
59
- readonly code: "invalid" | "unavailable" | "conflict" | "undeclared_key" | "scope_not_declared" | "owner_required" | "too_large" | "quota_exceeded";
59
+ readonly code: "invalid" | "unavailable" | "conflict" | "owner_required" | "undeclared_key" | "scope_not_declared" | "too_large" | "quota_exceeded";
60
60
  };
61
61
  requiredOperations: () => string[];
62
62
  };
@@ -1,3 +1,4 @@
1
+ import type { OwnerSessions } from "../owner-sessions.js";
1
2
  import type { TenantId } from "../tenant.js";
2
3
  import type { AuthAdapter, ReadonlyTenantRegistry, ReadonlyTenancy } from "./contracts.js";
3
4
  /** Stored owner verification material for one selected tenant. */
@@ -16,7 +17,9 @@ export type OwnerKeyOptions = Readonly<{
16
17
  /** Current verification material, or null when no owner key is configured. */
17
18
  get(tenantId: TenantId): Promise<OwnerKeyRecord | null>;
18
19
  }>;
19
- /** Optional relative POST /login route, explicitly mounted by the host. */
20
+ /** Host-owned owner browser sessions for one tenant; the cookie names one of these. */
21
+ sessions(tenantId: TenantId): OwnerSessions;
22
+ /** Optional relative POST /login and POST /logout routes, explicitly mounted by the host. */
20
23
  login?: Readonly<{
21
24
  /** Resolve the tenant through the kit, not from form/body data. */
22
25
  resolveTenant: ReadonlyTenancy["resolve"];
@@ -19,7 +19,17 @@ export function ownerKey(options) {
19
19
  const record = await options.keys.get(tenant.id);
20
20
  if (record === null)
21
21
  return context.json({ error: "unauthorized" }, 401);
22
- const helper = ownerKeyAuth(record.key, record.memberId);
22
+ // The session is stored only once the signed-in member is still the
23
+ // tenant's owner, so a refused sign-in leaves no session behind.
24
+ const sessions = options.sessions(tenant.id);
25
+ const opened = [];
26
+ const helper = ownerKeyAuth(record.key, record.memberId, {
27
+ ...sessions,
28
+ open: (...session) => {
29
+ opened.push(session);
30
+ return Promise.resolve();
31
+ },
32
+ });
23
33
  if (helper.login === undefined)
24
34
  throw new Error("Oyster owner authentication has no login handler");
25
35
  const response = await helper.login(context.req.raw);
@@ -27,9 +37,24 @@ export function ownerKey(options) {
27
37
  return response;
28
38
  if (!(await currentOwner(tenant, record.memberId)))
29
39
  return context.json({ error: "forbidden" }, 403);
40
+ for (const session of opened)
41
+ await sessions.open(...session);
30
42
  response.headers.set("Cache-Control", "no-store");
31
43
  return response;
32
44
  });
45
+ if (login !== undefined)
46
+ routes.post("/logout", async (context) => {
47
+ const tenant = await login.resolveTenant(context.req.raw);
48
+ if (tenant === null)
49
+ return context.json({ error: "not_found" }, 404);
50
+ const record = await options.keys.get(tenant.id);
51
+ if (record === null)
52
+ return context.json({ error: "unauthorized" }, 401);
53
+ const helper = ownerKeyAuth(record.key, record.memberId, options.sessions(tenant.id));
54
+ if (helper.logout === undefined)
55
+ throw new Error("Oyster owner authentication has no logout handler");
56
+ return await helper.logout(context.req.raw);
57
+ });
33
58
  const adapter = {
34
59
  id: "owner-key",
35
60
  async authenticate(request, tenant) {
@@ -45,7 +70,7 @@ export function ownerKey(options) {
45
70
  return recognizedCookie
46
71
  ? { kind: "refused", status: 401 }
47
72
  : { kind: "pass" };
48
- const result = await ownerKeyAuth(record.key, record.memberId).authenticate(request);
73
+ const result = await ownerKeyAuth(record.key, record.memberId, options.sessions(tenant.id)).authenticate(request);
49
74
  if (result.kind === "refused")
50
75
  return recognizedCookie
51
76
  ? { kind: "refused", status: 401 }
@@ -1,4 +1,4 @@
1
- import { ownerKeyAuth } from "../auth.js";
1
+ import { ownerKeyCredential } from "../auth.js";
2
2
  import { OysterArchivingError } from "./old-worker-readonly.js";
3
3
  const path = "/__upgrade/registry-sql";
4
4
  const noStore = { "Cache-Control": "no-store" };
@@ -12,11 +12,7 @@ export async function oldRegistrySqlRequest(request, ownerKey, exportRegistry) {
12
12
  return archivingResponse();
13
13
  if (request.headers.get("Authorization")?.startsWith("Bearer ") !== true)
14
14
  return new Response(null, { status: 401, headers: noStore });
15
- const result = await ownerKeyAuth(ownerKey).authenticate(request);
16
- if (result.kind !== "admitted" ||
17
- result.principal.actor.kind !== "member" ||
18
- !("role" in result.principal) ||
19
- result.principal.role !== "owner")
15
+ if ((await ownerKeyCredential(ownerKey, request)) !== "owner")
20
16
  return new Response(null, { status: 401, headers: noStore });
21
17
  return exportRegistry();
22
18
  }
@@ -2,6 +2,7 @@
2
2
  export declare function attemptWebhook(target: Readonly<{
3
3
  url: string;
4
4
  secret: string;
5
+ previousSecret?: string;
5
6
  }>, delivery: Readonly<{
6
7
  id: string;
7
8
  type: string;
@@ -4,7 +4,7 @@ export async function attemptWebhook(target, delivery) {
4
4
  try {
5
5
  const response = await fetch(target.url, {
6
6
  method: "POST",
7
- headers: await webhookHeaders(target.secret, delivery.id, delivery.type, Math.floor(Date.now() / 1000), delivery.body),
7
+ headers: await webhookHeaders(target.secret, delivery.id, delivery.type, Math.floor(Date.now() / 1000), delivery.body, target.previousSecret),
8
8
  body: delivery.body,
9
9
  signal: AbortSignal.timeout(10_000),
10
10
  });
@@ -136,6 +136,23 @@ export declare class OysterWebhooks<Env extends OysterKeysEnv = OysterKeysEnv> e
136
136
  types: readonly string[];
137
137
  secret?: string | undefined;
138
138
  }): Promise<SubscriptionCreated | SubscriptionRefused>;
139
+ /**
140
+ * Replace a subscription's signing secret and return the new one once. The
141
+ * secret it replaces keeps signing beside it for 24 hours, so a receiver
142
+ * can switch without dropping a delivery; a second rotation in that window
143
+ * retires the older one at once. `null` when there is no such subscription;
144
+ * a concurrent change while sealing returns `conflict`.
145
+ */
146
+ rotateSecret(id: string): Promise<Readonly<{
147
+ secret: string;
148
+ }> | Readonly<{
149
+ error: "unavailable" | "conflict";
150
+ }> | null>;
151
+ /**
152
+ * Queue a delivery that ran out of retries again, from its first attempt.
153
+ * Only a `failed` delivery is redelivered; `false` for any other.
154
+ */
155
+ redeliver(deliveryId: string): Promise<boolean>;
139
156
  /** Every subscription. */
140
157
  subscriptions(): WebhookSubscription[];
141
158
  /** Remove a subscription and its deliveries. */
@@ -248,6 +265,8 @@ export type OysterGitWorkerOptions<Env extends OysterGitWorkerEnv> = Readonly<{
248
265
  }> | null>;
249
266
  /** Further owner-only routes this host serves, after the owner guard. */
250
267
  ownerRoutes?: (env: Env, scope: TenantScope) => Routes<OysterEnv>;
268
+ /** Serve the owner's port preview confirm page; see `OysterHost.portPreviewEntry`. */
269
+ portPreviewEntry?: boolean;
251
270
  }>;
252
271
  /** A tenant's whole Git host: the App server, `host.git` and the owner routes. */
253
272
  export type OysterGitWorkerHost = OysterHost & Readonly<{