@fungi.computer/oyster 0.27.1 → 0.28.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.
@@ -1,5 +1,6 @@
1
1
  import { type ComputerSize } from "@fungi.computer/computer/backing";
2
2
  import { type AppMethodRefusedReply } from "@fungi.computer/agar/backend";
3
+ import type { WatchdogSqliteOwner } from "@fungi.computer/watchdog";
3
4
  import { type ComputerPorts } from "@fungi.computer/agar/computer";
4
5
  import { type PreviewSelector } from "./preview.js";
5
6
  import { type StandaloneTenancyEnv } from "./tenancy.js";
@@ -76,6 +77,12 @@ export type StandaloneAgentComputerRpc = ComputerFilesRpc & Readonly<{
76
77
  filePatch(authority: ComputerGrant, input: z.output<typeof patchInputSchema>): Promise<z.output<typeof patchOutputSchema>>;
77
78
  fileWrite(authority: ComputerGrant, path: string, bytes: Uint8Array): Promise<void>;
78
79
  }>;
80
+ /**
81
+ * The size fixed at creation. The configured Computer and the build Computer
82
+ * are never created by the fleet, so they have no row and run at the default
83
+ * size; refusing them would fail every container start and App build.
84
+ */
85
+ export declare function standaloneComputerSize(sql: WatchdogSqliteOwner["sql"]): ComputerSize;
79
86
  /** Durable workspace and existing backings, with fleet checks at native acceptance. */
80
87
  export declare class ComputerDO extends NativeComputerDO implements ComputerFetch, StandaloneAgentComputerRpc {
81
88
  #private;
@@ -87,7 +94,7 @@ export declare class ComputerDO extends NativeComputerDO implements ComputerFetc
87
94
  * name from the configured id once the namespace verifies it.
88
95
  */
89
96
  protected nameCandidates(): readonly string[];
90
- /** The size fixed at creation; a Computer never created by the fleet has none. */
97
+ /** The size fixed at creation, or the default for a non-fleet Computer. */
91
98
  protected computerSize(): ComputerSize;
92
99
  /** Install the fleet's creation projection before exposing its new identity. */
93
100
  initializeFleetBackings(backings: readonly AttachedBackend[], size: ComputerSize): void;
@@ -1,4 +1,4 @@
1
- import { attachedBackendId, computerSizeSchema, hostedBackingSchema, } from "@fungi.computer/computer/backing";
1
+ import { attachedBackendId, computerSizeSchema, defaultComputerSize, hostedBackingSchema, } from "@fungi.computer/computer/backing";
2
2
  import { appMethodRefusalStatus, appMethodRefusedReplySchema, } from "@fungi.computer/agar/backend";
3
3
  import * as Schema from "effect/Schema";
4
4
  import { computerPortsSchema, } from "@fungi.computer/agar/computer";
@@ -117,6 +117,20 @@ const previewRefusal = appMethodRefusedReplySchema.parse({
117
117
  /** The non-secret context a native command carries for its admitted Git step. */
118
118
  const workflowGitExecutionContextSchema = z.lazy(() => z.strictObject({ workflowGit: workflowGitPassGrantSchema }));
119
119
  const sizeTable = "CREATE TABLE IF NOT EXISTS oyster_computer_size (singleton INTEGER PRIMARY KEY CHECK (singleton = 1), size TEXT NOT NULL CHECK (size IN ('small','default','large'))) STRICT";
120
+ /**
121
+ * The size fixed at creation. The configured Computer and the build Computer
122
+ * are never created by the fleet, so they have no row and run at the default
123
+ * size; refusing them would fail every container start and App build.
124
+ */
125
+ export function standaloneComputerSize(sql) {
126
+ sql.exec(sizeTable);
127
+ const row = sql
128
+ .exec("SELECT size FROM oyster_computer_size WHERE singleton=1")
129
+ .toArray()[0];
130
+ return row === undefined
131
+ ? defaultComputerSize
132
+ : computerSizeSchema.parse(row.size);
133
+ }
120
134
  /** Durable workspace and existing backings, with fleet checks at native acceptance. */
121
135
  export class ComputerDO extends NativeComputerDO {
122
136
  previewBindings;
@@ -173,16 +187,9 @@ export class ComputerDO extends NativeComputerDO {
173
187
  });
174
188
  return this.#lifecycle;
175
189
  }
176
- /** The size fixed at creation; a Computer never created by the fleet has none. */
190
+ /** The size fixed at creation, or the default for a non-fleet Computer. */
177
191
  computerSize() {
178
- const sql = this.state.storage.sql;
179
- sql.exec(sizeTable);
180
- const row = sql
181
- .exec("SELECT size FROM oyster_computer_size WHERE singleton=1")
182
- .toArray()[0];
183
- if (row === undefined)
184
- throw new Error("Computer was created without a size");
185
- return computerSizeSchema.parse(row.size);
192
+ return standaloneComputerSize(this.state.storage.sql);
186
193
  }
187
194
  /** Install the fleet's creation projection before exposing its new identity. */
188
195
  initializeFleetBackings(backings, size) {
@@ -28,8 +28,6 @@ export async function approveChosenDashboard(operation, owner) {
28
28
  permissions.authority.authorityVersion !==
29
29
  installed.authority.authorityVersion ||
30
30
  permissions.authority.declaredOperationsDigest !==
31
- installed.authority.declaredOperationsDigest ||
32
- permissions.declaredOperations.digest !==
33
31
  installed.authority.declaredOperationsDigest)
34
32
  throw new Error(`${name} approval snapshot changed`);
35
33
  const shell = permissions.declaredOperations.capabilities.find((row) => row.capability === "team.workbenchHost");
@@ -48,6 +46,7 @@ export async function approveChosenDashboard(operation, owner) {
48
46
  storeGeneration: projection.storeGeneration,
49
47
  authorityVersion: installed.authority.authorityVersion,
50
48
  artifactDigest: digest,
49
+ declaredOperationsDigest: permissions.declaredOperations.digest,
51
50
  command,
52
51
  }));
53
52
  if (!saved.ok)
@@ -40,10 +40,10 @@ export declare const mediaFrameMethods: {
40
40
  requestId: string;
41
41
  libraryPath: string;
42
42
  settings: {
43
- width: number;
44
- height: number;
45
43
  model: string;
46
44
  prompt: string;
45
+ width: number;
46
+ height: number;
47
47
  resolution?: "480p" | "720p" | "768p" | "1080p" | "4k" | undefined;
48
48
  aspectRatio?: "16:9" | "4:3" | "1:1" | "3:4" | "9:16" | "21:9" | "9:21" | undefined;
49
49
  references?: {
@@ -70,6 +70,19 @@ export declare const mediaFrameMethods: {
70
70
  path: string;
71
71
  role: "reference" | "first-frame" | "last-frame";
72
72
  }[] | undefined;
73
+ audioReferences?: {
74
+ path: string;
75
+ }[] | undefined;
76
+ };
77
+ } | {
78
+ kind: "audio";
79
+ requestId: string;
80
+ libraryPath: string;
81
+ settings: {
82
+ model: "elevenlabs/music-v2" | "elevenlabs/eleven-multilingual-v2" | "elevenlabs/eleven-v3";
83
+ prompt: string;
84
+ voiceId?: string | undefined;
85
+ durationSeconds?: number | undefined;
73
86
  };
74
87
  }];
75
88
  decodeResult: (input: unknown, options?: import("effect/SchemaAST").ParseOptions) => Schema.Json;
@@ -200,6 +200,14 @@ function standaloneMediaService(env, actorId, workspace, owner = "owner", librar
200
200
  await files.mkdir(workspacePath(libraryPath));
201
201
  },
202
202
  write: (path, bytes) => files.write(workspacePath(path), bytes),
203
+ readAudioReference: async (reference) => {
204
+ if (reference.computerId !== computerId)
205
+ throw new MediaSettingsError("reference Computer is not selected");
206
+ const bytes = await files.read(workspacePath(reference.path));
207
+ if (bytes === null)
208
+ throw new MediaSettingsError("audio reference is unavailable");
209
+ return bytes;
210
+ },
203
211
  };
204
212
  const admittedDestination = fit === undefined
205
213
  ? destination
@@ -28,6 +28,12 @@ export declare class StandaloneTenants extends TenancyRegistryDO {
28
28
  /** The same trusted bindings are used by HTTP, MCP and cold root readers. */
29
29
  export type StandaloneTenancyEnv = Pick<OysterGitWorkerEnv, "OYSTER_ORIGIN" | "OYSTER_OWNER_NAME" | "OYSTER_OWNER_KEY" | "KEYS"> & Readonly<{
30
30
  TENANTS: DurableObjectNamespace<StandaloneTenants>;
31
+ /** Opt-in Cloudflare Access sign-in: the team domain, with the AUD tag. */
32
+ OYSTER_ACCESS_TEAM_DOMAIN?: string;
33
+ /** The Access application's AUD tag; set together with the team domain. */
34
+ OYSTER_ACCESS_AUD?: string;
35
+ /** The Access `sub` bound to the existing owner; unset binds no one. */
36
+ OYSTER_ACCESS_OWNER_SUBJECT?: string;
31
37
  }>;
32
38
  /** A live registry-owned owner; the configured label is never its member ID. */
33
39
  export type StandaloneOwner = Readonly<{
@@ -1,5 +1,6 @@
1
1
  import { TenancyRegistryDO, admittedRegistry, durableObjectRegistry, } from "../tenancy/cloudflare.js";
2
2
  import { createTenancy, } from "../tenancy/index.js";
3
+ import { cloudflareAccess, cloudflareAccessIssuer, } from "../tenancy/cloudflare-access.js";
3
4
  import { ownerKey } from "../tenancy/owner-key.js";
4
5
  import { loopbackAliasLocation } from "../tenancy/registry-record.js";
5
6
  import { hosts } from "../tenancy/resolve.js";
@@ -126,6 +127,9 @@ export function standaloneTenancy(env) {
126
127
  }
127
128
  return pending;
128
129
  }
130
+ function blankAsAbsent(value) {
131
+ return value === undefined || value.trim() === "" ? undefined : value.trim();
132
+ }
129
133
  async function composeTenancy(env) {
130
134
  const scope = tenantScope(defaultTenant, env.OYSTER_ORIGIN);
131
135
  const domain = new URL(scope.origin).host;
@@ -140,6 +144,25 @@ async function composeTenancy(env) {
140
144
  if ("kind" in seeded)
141
145
  throw new StandaloneSeedConfigurationChanged(seeded);
142
146
  const registry = durableObjectRegistry(env.TENANTS, { readonly: true });
147
+ const teamDomain = blankAsAbsent(env.OYSTER_ACCESS_TEAM_DOMAIN);
148
+ const accessAudience = blankAsAbsent(env.OYSTER_ACCESS_AUD);
149
+ if ((teamDomain === undefined) !== (accessAudience === undefined))
150
+ throw new Error("Set OYSTER_ACCESS_TEAM_DOMAIN and OYSTER_ACCESS_AUD together, or neither");
151
+ // One adapter per environment, so its signing-key cache outlives requests.
152
+ const access = teamDomain === undefined || accessAudience === undefined
153
+ ? null
154
+ : cloudflareAccess({ teamDomain, audience: accessAudience });
155
+ const subject = blankAsAbsent(env.OYSTER_ACCESS_OWNER_SUBJECT);
156
+ if (access !== null && teamDomain !== undefined) {
157
+ // Access fronts a hostname you control; workers.dev would bypass it.
158
+ if (new URL(scope.origin).hostname.endsWith(".workers.dev"))
159
+ throw new Error("Cloudflare Access cannot protect a workers.dev origin; set OYSTER_ORIGIN to the Access-protected hostname");
160
+ // The configuration states the whole Access binding of the existing owner.
161
+ const [ownerId] = seeded.owners;
162
+ if (ownerId === undefined)
163
+ throw new Error("Standalone tenant has no owner to bind");
164
+ await env.TENANTS.getByName("registry").bindIdentities(defaultTenant, ownerId, cloudflareAccessIssuer(teamDomain), subject === undefined ? [] : [subject]);
165
+ }
143
166
  /** The canonical owner, only while the one admitted record still proves it. */
144
167
  const ownerOf = ({ tenant, membership, }) => tenant.id !== defaultTenant ||
145
168
  tenant.status !== "active" ||
@@ -179,6 +202,40 @@ async function composeTenancy(env) {
179
202
  },
180
203
  auth: [
181
204
  ownerAuth,
205
+ // After the key adapters and before the terminal named-key entry.
206
+ ...(access === null
207
+ ? []
208
+ : [
209
+ {
210
+ id: "standalone-cloudflare-access",
211
+ async authenticate(request, selected) {
212
+ const result = await access.authenticate(request, selected);
213
+ if (result.kind !== "identity")
214
+ return result;
215
+ // Resolve only through the registry's existing binding, and
216
+ // only to the one owner this admission proved.
217
+ // Shared registry state can hold a binding a newer
218
+ // configuration removed; this isolate admits only its own.
219
+ if (result.identity.subject !== subject)
220
+ return { kind: "refused", status: 403 };
221
+ const membership = await registry.membershipOf(selected.id, result.identity);
222
+ return owner === null ||
223
+ membership?.role !== "owner" ||
224
+ membership.memberId !== owner.actor.memberId
225
+ ? { kind: "refused", status: 403 }
226
+ : {
227
+ kind: "principal",
228
+ principal: {
229
+ actor: {
230
+ kind: "member",
231
+ memberId: membership.memberId,
232
+ },
233
+ role: "owner",
234
+ },
235
+ };
236
+ },
237
+ },
238
+ ]),
182
239
  {
183
240
  id: "standalone-named-key",
184
241
  async authenticate(request) {
@@ -1,4 +1,5 @@
1
1
  import type { Brand } from "effect/Brand";
2
+ import { type TenantId } from "../../tenant.js";
2
3
  import type { Identity, ManagedTenantRegistry, Membership, ReadonlyTenantRegistry, Tenant } from "../contracts.js";
3
4
  /** The registry owner's atomic read of one host and one identity. */
4
5
  export type RegistryAdmission = Readonly<{
@@ -23,6 +24,8 @@ export type TenantAdmission = AdmissionRecord & Brand<"TenantAdmission">;
23
24
  export type TenancyRegistryDO = ManagedTenantRegistry & Required<Pick<ReadonlyTenantRegistry, "byDomain">> & Readonly<{
24
25
  /** One atomic read of the tenant at a host and one identity's membership. */
25
26
  admission(host: string, identity: Identity): Promise<RegistryAdmission | null>;
27
+ /** Declare a provider's complete identity set for one existing member. */
28
+ bindIdentities(id: TenantId, memberId: string, provider: string, subjects: readonly string[]): Promise<void>;
26
29
  }> & Rpc.DurableObjectBranded;
27
30
  /** Re-export from a host Worker and bind a SQLite-backed Durable Object namespace. */
28
31
  export declare const TenancyRegistryDO: new (ctx: DurableObjectState) => TenancyRegistryDO;
@@ -56,6 +56,8 @@ class RegistryObject extends DurableObject {
56
56
  CREATE TABLE IF NOT EXISTS domains (host TEXT PRIMARY KEY, tenant_id TEXT NOT NULL, ordinal INTEGER NOT NULL);
57
57
  CREATE INDEX IF NOT EXISTS domains_tenant ON domains(tenant_id);
58
58
  CREATE TABLE IF NOT EXISTS identities (provider TEXT NOT NULL, subject TEXT NOT NULL, member_id TEXT UNIQUE NOT NULL, PRIMARY KEY(provider,subject));
59
+ CREATE TABLE IF NOT EXISTS identity_aliases (provider TEXT NOT NULL, subject TEXT NOT NULL, member_id TEXT NOT NULL, PRIMARY KEY(provider,subject));
60
+ CREATE INDEX IF NOT EXISTS identity_aliases_member ON identity_aliases(member_id);
59
61
  CREATE TABLE IF NOT EXISTS memberships (tenant_id TEXT NOT NULL, member_id TEXT NOT NULL, role TEXT NOT NULL CHECK (role IN ('owner','member')), membership_version INTEGER NOT NULL DEFAULT 1 CHECK(membership_version BETWEEN 1 AND 9007199254740991), PRIMARY KEY(tenant_id,member_id));
60
62
  CREATE TABLE IF NOT EXISTS membership_clock (id INTEGER PRIMARY KEY CHECK(id=1), revision INTEGER NOT NULL CHECK(revision BETWEEN 0 AND 9007199254740991));
61
63
  INSERT OR IGNORE INTO membership_clock VALUES(1,0);
@@ -157,7 +159,7 @@ class RegistryObject extends DurableObject {
157
159
  }
158
160
  #membershipOf(id, owner) {
159
161
  const row = this.ctx.storage.sql
160
- .exec(`SELECT m.member_id,m.role,m.membership_version FROM memberships m JOIN identities i ON m.member_id=i.member_id WHERE m.tenant_id=? AND i.provider=? AND i.subject=?`, id, owner.provider, owner.subject)
162
+ .exec(`SELECT m.member_id,m.role,m.membership_version FROM memberships m JOIN (SELECT provider,subject,member_id FROM identities UNION ALL SELECT provider,subject,member_id FROM identity_aliases) i ON m.member_id=i.member_id WHERE m.tenant_id=? AND i.provider=? AND i.subject=?`, id, owner.provider, owner.subject)
161
163
  .toArray()[0];
162
164
  if (row === undefined)
163
165
  return null;
@@ -174,7 +176,7 @@ class RegistryObject extends DurableObject {
174
176
  const origin = checkedOrigin(parsed.origin, parsed.domains);
175
177
  return this.ctx.storage.transactionSync(() => {
176
178
  const raw = this.ctx.storage.sql
177
- .exec("SELECT member_id FROM identities WHERE provider=? AND subject=?", parsed.owner.provider, parsed.owner.subject)
179
+ .exec("SELECT member_id FROM identities WHERE provider=? AND subject=? UNION ALL SELECT member_id FROM identity_aliases WHERE provider=? AND subject=?", parsed.owner.provider, parsed.owner.subject, parsed.owner.provider, parsed.owner.subject)
178
180
  .toArray()[0];
179
181
  const memberId = raw === undefined
180
182
  ? createMemberId()
@@ -196,6 +198,45 @@ class RegistryObject extends DurableObject {
196
198
  });
197
199
  });
198
200
  }
201
+ /**
202
+ * Declare every identity `provider` may use as one existing member, in one
203
+ * transaction. Other aliases of that provider for the member are removed, so
204
+ * the call states the complete set. It never creates a member or tenant, and
205
+ * refuses an identity already mapped to a different member.
206
+ */
207
+ bindIdentities(id, memberId, provider, subjects) {
208
+ return Promise.resolve().then(() => {
209
+ const target = Schema.decodeUnknownSync(Schema.Struct({
210
+ id: tenantIdSchema,
211
+ memberId: Schema.NonEmptyString,
212
+ provider: Schema.NonEmptyString,
213
+ subjects: Schema.Array(Schema.NonEmptyString),
214
+ }))({ id, memberId, provider, subjects });
215
+ this.ctx.storage.transactionSync(() => {
216
+ if (this.ctx.storage.sql
217
+ .exec("SELECT 1 FROM memberships WHERE tenant_id=? AND member_id=?", target.id, target.memberId)
218
+ .toArray().length === 0)
219
+ throw new Error("Member does not exist in this tenant");
220
+ for (const subject of target.subjects) {
221
+ const mapped = this.ctx.storage.sql
222
+ .exec("SELECT member_id FROM identities WHERE provider=? AND subject=? UNION ALL SELECT member_id FROM identity_aliases WHERE provider=? AND subject=?", target.provider, subject, target.provider, subject)
223
+ .toArray()
224
+ .map((row) => Schema.decodeUnknownSync(memberRow)(row).member_id);
225
+ if (mapped.some((existing) => existing !== target.memberId))
226
+ throw new Error("Identity already has a canonical member mapping");
227
+ if (mapped.length === 0)
228
+ this.ctx.storage.sql.exec("INSERT INTO identity_aliases (provider,subject,member_id) VALUES (?,?,?)", target.provider, subject, target.memberId);
229
+ }
230
+ for (const raw of this.ctx.storage.sql
231
+ .exec("SELECT subject FROM identity_aliases WHERE provider=? AND member_id=?", target.provider, target.memberId)
232
+ .toArray()) {
233
+ const { subject } = Schema.decodeUnknownSync(Schema.Struct({ subject: Schema.String }))(raw);
234
+ if (!target.subjects.includes(subject))
235
+ this.ctx.storage.sql.exec("DELETE FROM identity_aliases WHERE provider=? AND subject=?", target.provider, subject);
236
+ }
237
+ });
238
+ });
239
+ }
199
240
  setStatus(id, status) {
200
241
  const parsed = Schema.decodeUnknownSync(statusSchema)(status);
201
242
  if (this.#get(id) === null)
@@ -0,0 +1,28 @@
1
+ import type { AuthAdapter } from "./contracts.js";
2
+ /** Cloudflare Access settings for one Access application; the adapter is opt-in. */
3
+ export type CloudflareAccessOptions = Readonly<{
4
+ /** The Zero Trust team domain, for example `team.cloudflareaccess.com`. */
5
+ teamDomain: string;
6
+ /** The Access application's Application Audience (AUD) tag. */
7
+ audience: string;
8
+ /** Optional host-owned transport for the team's signing keys. */
9
+ fetch?: typeof globalThis.fetch;
10
+ }>;
11
+ /** The request header Cloudflare Access adds after it admits a request. */
12
+ export declare const cloudflareAccessAssertionHeader = "Cf-Access-Jwt-Assertion";
13
+ /**
14
+ * The exact `iss` Access signs, which is also the identity provider namespace.
15
+ * Access omits the trailing slash; the match is exact.
16
+ */
17
+ export declare function cloudflareAccessIssuer(teamDomain: string): string;
18
+ /**
19
+ * Verify a Cloudflare Access application token and return its issuer-scoped
20
+ * identity. The registry alone maps that identity to a member: an Access user
21
+ * with no explicit binding is refused by the kit, and nothing is created here.
22
+ *
23
+ * Precedence: any `Authorization` header or Oyster owner-key cookie is an
24
+ * explicit Oyster credential, so this adapter passes and the key adapters
25
+ * decide. Register it after the key adapters and before any terminal adapter.
26
+ * Only the `Cf-Access-Jwt-Assertion` header is read, as Cloudflare recommends.
27
+ */
28
+ export declare function cloudflareAccess(options: CloudflareAccessOptions): AuthAdapter;
@@ -0,0 +1,99 @@
1
+ import { createRemoteJWKSet, customFetch, errors, jwtVerify, } from "jose";
2
+ import * as Option from "effect/Option";
3
+ import * as Schema from "effect/Schema";
4
+ import { parse } from "hono/utils/cookie";
5
+ import { ownerKeyCookieName } from "../auth.js";
6
+ /** The request header Cloudflare Access adds after it admits a request. */
7
+ export const cloudflareAccessAssertionHeader = "Cf-Access-Jwt-Assertion";
8
+ const nonEmpty = Schema.decodeUnknownOption(Schema.NonEmptyString);
9
+ const maxTokenLength = 16 * 1024;
10
+ const teamSuffix = ".cloudflareaccess.com";
11
+ function invalidCredential(cause) {
12
+ return (cause instanceof errors.JWTInvalid ||
13
+ cause instanceof errors.JWTExpired ||
14
+ cause instanceof errors.JWTClaimValidationFailed ||
15
+ cause instanceof errors.JWSInvalid ||
16
+ cause instanceof errors.JWSSignatureVerificationFailed ||
17
+ cause instanceof errors.JOSEAlgNotAllowed ||
18
+ cause instanceof errors.JOSENotSupported ||
19
+ cause instanceof errors.JWKSMultipleMatchingKeys ||
20
+ cause instanceof errors.JWKSNoMatchingKey);
21
+ }
22
+ /**
23
+ * The exact `iss` Access signs, which is also the identity provider namespace.
24
+ * Access omits the trailing slash; the match is exact.
25
+ */
26
+ export function cloudflareAccessIssuer(teamDomain) {
27
+ const host = teamDomain.toLowerCase();
28
+ const origin = new URL(`https://${host}`);
29
+ if (origin.host !== host ||
30
+ !host.endsWith(teamSuffix) ||
31
+ host.length === teamSuffix.length ||
32
+ origin.pathname !== "/" ||
33
+ origin.username ||
34
+ origin.password ||
35
+ origin.search ||
36
+ origin.hash)
37
+ throw new TypeError("Configure a Cloudflare Access team domain (<team>.cloudflareaccess.com)");
38
+ return `https://${host}`;
39
+ }
40
+ /**
41
+ * Verify a Cloudflare Access application token and return its issuer-scoped
42
+ * identity. The registry alone maps that identity to a member: an Access user
43
+ * with no explicit binding is refused by the kit, and nothing is created here.
44
+ *
45
+ * Precedence: any `Authorization` header or Oyster owner-key cookie is an
46
+ * explicit Oyster credential, so this adapter passes and the key adapters
47
+ * decide. Register it after the key adapters and before any terminal adapter.
48
+ * Only the `Cf-Access-Jwt-Assertion` header is read, as Cloudflare recommends.
49
+ */
50
+ export function cloudflareAccess(options) {
51
+ const issuer = cloudflareAccessIssuer(options.teamDomain);
52
+ if (options.audience.length === 0)
53
+ throw new TypeError("Configure the Cloudflare Access application AUD tag");
54
+ const origin = new URL(issuer);
55
+ const jwks = createRemoteJWKSet(new URL("/cdn-cgi/access/certs", origin), options.fetch === undefined ? {} : { [customFetch]: options.fetch });
56
+ return {
57
+ id: "cloudflare-access",
58
+ async authenticate(request) {
59
+ // An explicit Oyster credential selects the key path, valid or not.
60
+ if (request.headers.has("Authorization") ||
61
+ Object.hasOwn(parse(request.headers.get("Cookie") ?? ""), ownerKeyCookieName))
62
+ return { kind: "pass" };
63
+ const token = request.headers.get(cloudflareAccessAssertionHeader);
64
+ if (token === null)
65
+ return { kind: "pass" };
66
+ if (token.length === 0 || token.length > maxTokenLength)
67
+ return { kind: "refused", status: 401 };
68
+ let payload;
69
+ try {
70
+ ({ payload } = await jwtVerify(token, jwks, {
71
+ issuer,
72
+ audience: options.audience,
73
+ algorithms: ["RS256"],
74
+ requiredClaims: ["exp", "iat"],
75
+ }));
76
+ }
77
+ catch (cause) {
78
+ if (invalidCredential(cause))
79
+ return { kind: "refused", status: 401 };
80
+ throw cause;
81
+ }
82
+ if (payload.type !== "app")
83
+ return { kind: "refused", status: 401 };
84
+ // A service token is not a human: it carries a client ID and an empty
85
+ // subject. It is not this adapter's credential, so the key path decides.
86
+ if (Option.isSome(nonEmpty(payload.common_name)))
87
+ return { kind: "pass" };
88
+ const subject = nonEmpty(payload.sub);
89
+ if (Option.isNone(subject))
90
+ return { kind: "refused", status: 401 };
91
+ // Email is display metadata only; the registry never looks it up.
92
+ const email = nonEmpty(payload.email);
93
+ const identity = Option.isSome(email)
94
+ ? { provider: issuer, subject: subject.value, email: email.value }
95
+ : { provider: issuer, subject: subject.value };
96
+ return { kind: "identity", identity };
97
+ },
98
+ };
99
+ }
@@ -35,7 +35,7 @@ uses. A `createOysterWorker` host needs `LOADER`, `RELEASES`, `REGISTRY`,
35
35
  | `@fungi.computer/oyster/auth` | `ownerKeyAuth`, `ownerOrKeyAuth` | Owner-key sign-in (a Bearer key or the login cookie, compared in constant time) and named agent keys. |
36
36
  | `@fungi.computer/oyster/authorization` | `routes`, route requirements | The one route table and its typed requirements. |
37
37
  | `@fungi.computer/oyster/tenant` | `TenantScope`, `tenantScope`, `singleTenant`, `OysterTenancy` | Host-resolved tenant identity and the scope that prefixes registry, key and repository names. |
38
- | `@fungi.computer/oyster/tenancy` | `createTenancy` and its adapters | Request resolution, a tenant registry and sign-in adapters (owner key, Auth0) for a multi-tenant host. |
38
+ | `@fungi.computer/oyster/tenancy` | `createTenancy` and its adapters | Request resolution, a tenant registry and sign-in adapters (owner key, Auth0, Access) for a multi-tenant host. |
39
39
  | `@fungi.computer/oyster/app-storage` | `AppStorageBinding`, `createAppStorage`, `appStorageSchemaStatements` | `env.APP_STORAGE` and its SQLite owner: declared keys, live admission, revision checks and watch invalidations. |
40
40
  | `@fungi.computer/oyster/agents` | `OysterAgents`, `agentCapabilities`, `agentApprovalRoutes` | The host's Agent slot, its App capabilities and the owner-only approval routes. |
41
41
  | `@fungi.computer/oyster/computer` | `computerSlots`, `ComputerTerminalHost` | Computer ports, processes and terminal routes supplied by the host; execution stays in the Computer runtime. |
@@ -237,11 +237,12 @@ returns 409.
237
237
  **App permissions.** After selecting a new Release, open **App access** beside
238
238
  the App, or `/api/installations/<installationId>/grants`, review the requested
239
239
  capabilities and choose **Save permissions**. The page sends a `PUT` carrying
240
- the captured `storeGeneration`, `authorityVersion` and Release `artifactDigest`
241
- with a `{kind:"change-grants",changes:[{capability,grant}]}` command; `null`
242
- revokes a capability. A replaced store, stale Release or concurrent approval
243
- returns `409`, and the page refreshes and rebases your edits. The required
244
- `InstallationStore` exposes `generation()` and
240
+ the captured `storeGeneration`, `authorityVersion`, Release `artifactDigest` and
241
+ the displayed `declaredOperationsDigest` with a
242
+ `{kind:"change-grants",changes:[{capability,grant}]}` command; `null` revokes a
243
+ capability. A replaced store, stale Release, changed host operations or
244
+ concurrent approval returns `409`, and the page refreshes and rebases your
245
+ edits. The required `InstallationStore` exposes `generation()` and
245
246
  `compareAndPut(record, expectedVersion, expectedGeneration)`, checking both pins
246
247
  in one commit transaction.
247
248
 
@@ -647,6 +648,68 @@ last-modified. Oyster adds `Cache-Control: no-store`,
647
648
  `X-Content-Type-Options: nosniff` and a sandboxed, deny-by-default Content
648
649
  Security Policy. Cookies, redirects and other headers cannot come from guests.
649
650
 
651
+ ### Cloudflare Access sign-in
652
+
653
+ `@fungi.computer/oyster/tenancy/cloudflare-access` exports `cloudflareAccess`,
654
+ an opt-in `AuthAdapter` for installations behind a Cloudflare Access
655
+ application. It verifies the `Cf-Access-Jwt-Assertion` header with `jose`
656
+ against the team's keys at
657
+ `https://<team>.cloudflareaccess.com/cdn-cgi/access/certs`. Keys are cached, and
658
+ an unknown `kid` triggers a refetch, so Cloudflare's six-week rotation needs no
659
+ deploy (the library rate-limits that refetch to once per 30 seconds). A token
660
+ must have the exact `iss` `https://<team>.cloudflareaccess.com`, your
661
+ application's AUD tag in `aud`, a valid `exp` and `nbf`, `type: "app"` and a
662
+ non-empty `sub`. Only the header is read, as Cloudflare recommends, never
663
+ `CF_Authorization` or the unvalidated email header.
664
+
665
+ The adapter returns the identity
666
+ `{ provider: "https://<team>.cloudflareaccess.com", subject: sub }`. Email is
667
+ display data and is never looked up. The tenancy kit then resolves it only
668
+ through `membershipOf` to a member that was bound ahead of time, so an Access
669
+ user with no binding is refused with 403 and no member is created. An Access
670
+ service token (a `common_name`, empty `sub`) is never a human: the adapter
671
+ passes, and it is refused 401 unless an Oyster key credential accompanies it.
672
+
673
+ **Precedence.** Any `Authorization` header or `oyster_session` cookie is an
674
+ explicit Oyster credential, so the adapter passes and the key adapters decide.
675
+ An invalid key is therefore never rescued by a valid assertion. With no
676
+ assertion it passes; an invalid or expired assertion is refused 401. Place it
677
+ after the key adapters and before any adapter that refuses what remains.
678
+
679
+ **Standalone host.** Set both of these (a half-set pair fails at startup) to
680
+ turn it on, and bind your Access subject to the existing owner:
681
+
682
+ ```jsonc
683
+ "vars": {
684
+ "OYSTER_ACCESS_TEAM_DOMAIN": "yourteam.cloudflareaccess.com",
685
+ "OYSTER_ACCESS_AUD": "<Application Audience (AUD) tag>",
686
+ "OYSTER_ACCESS_OWNER_SUBJECT": "<your Access user's sub>"
687
+ }
688
+ ```
689
+
690
+ `OYSTER_ACCESS_OWNER_SUBJECT` is the binding. At startup the host calls the
691
+ registry's `bindIdentities` on the `TENANTS` Durable Object, which adds an
692
+ `identity_aliases` row from `{ issuer, sub }` to the owner's existing member ID.
693
+ It writes no tenant, member or owner, and the standalone seed is unchanged, so
694
+ your data and owner key stay. The setting states the complete binding: changing
695
+ or clearing it removes the old subject, and only that subject, for that issuer.
696
+ Only the owner can be bound. To find your `sub`, sign in through Access, copy
697
+ the `CF_Authorization` cookie from your browser's developer tools and decode its
698
+ payload (`cut -d. -f2`, then base64url). Cloudflare documents `sub` as unique to
699
+ an email address per account, and it changes if the Access user is deleted and
700
+ re-added, so rebind it then.
701
+
702
+ **Set `OYSTER_ORIGIN` to the Access-protected hostname**, and set
703
+ `workers_dev: false` and `preview_urls: false` in Wrangler so the Worker has no
704
+ unprotected `workers.dev` address. The host refuses to start with Access
705
+ configured and `OYSTER_ORIGIN` on `*.workers.dev`. Because a stale Durable
706
+ Object binding could outlive a removed subject during a rollout, each isolate
707
+ also admits only the `OYSTER_ACCESS_OWNER_SUBJECT` it is configured with.
708
+
709
+ **Use a hostname-based Access application.** Worker-level Access rejects
710
+ WebSocket upgrades, which Shed and Computer terminals use. Protect the Worker's
711
+ hostname, not the Worker, and keep Oyster's own keys for agents and automation.
712
+
650
713
  ### Hosting many tenants
651
714
 
652
715
  Pass your own `OysterTenancy` from `@fungi.computer/oyster/tenant` as
package/docs/api/apps.md CHANGED
@@ -188,14 +188,15 @@ digest. The host checks authorization and freshness before saving.
188
188
 
189
189
  ###### Parameters
190
190
 
191
- | Parameter | Type |
192
- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
193
- | `appKey` | `string` |
194
- | `pins` | \{ `storeGeneration`: `string`; `authorityVersion`: `number`; `artifactDigest`: `Sha256Digest`; \} |
195
- | `pins.storeGeneration` | `string` |
196
- | `pins.authorityVersion` | `number` |
197
- | `pins.artifactDigest` | `Sha256Digest` |
198
- | `changes` | readonly `Readonly`\<\{ `capability`: \| `"computer.list"` \| `"computer.readFile"` \| `"computer.writeFile"` \| `"computer.execute"` \| `"approvals"` \| `"agent.list"` \| `"agent.manage"` \| `"agent.rename"` \| `"agent.avatar"` \| `"agent.instructions"` \| `"agent.toolPolicy"` \| `"agent.read"` \| `"agent.send"` \| `"llm.generation"` \| `"media.generation"` \| `"media.share"` \| `"games:servers"` \| `"git.repository"` \| `"apps.open"` \| `"apps.call"` \| `"app.storage"` \| `"app.events.emit"` \| `"team.workbenchHost"` \| `"marketplace.browse"` \| `"marketplace.purchase"` \| `"workflow.run"` \| `"workflow.publish"` \| `"workflow.arm"` \| `"world"` \| `"channels.read"` \| `"channels.personal.manage"`; `grant`: \| `Readonly`\<\{ `operations`: readonly `string`[]; `resources`: \| `"tenant-scope"` \| readonly `Readonly`\<\{ `kind`: `string`; `id`: `string`; \}\>[]; \}\> \| `null`; \}\>[] |
191
+ | Parameter | Type | Description |
192
+ | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
193
+ | `appKey` | `string` | - |
194
+ | `pins` | \{ `storeGeneration`: `string`; `authorityVersion`: `number`; `artifactDigest`: `Sha256Digest`; `declaredOperationsDigest`: `Sha256Digest`; \} | - |
195
+ | `pins.storeGeneration` | `string` | - |
196
+ | `pins.authorityVersion` | `number` | - |
197
+ | `pins.artifactDigest` | `Sha256Digest` | - |
198
+ | `pins.declaredOperationsDigest` | `Sha256Digest` | The declared-operations digest the owner saw; a save against a changed host snapshot is refused. |
199
+ | `changes` | readonly `Readonly`\<\{ `capability`: \| `"computer.list"` \| `"computer.readFile"` \| `"computer.writeFile"` \| `"computer.execute"` \| `"approvals"` \| `"agent.list"` \| `"agent.manage"` \| `"agent.rename"` \| `"agent.avatar"` \| `"agent.instructions"` \| `"agent.toolPolicy"` \| `"agent.read"` \| `"agent.send"` \| `"llm.generation"` \| `"media.generation"` \| `"media.share"` \| `"games:servers"` \| `"git.repository"` \| `"apps.open"` \| `"apps.call"` \| `"app.storage"` \| `"app.events.emit"` \| `"team.workbenchHost"` \| `"marketplace.browse"` \| `"marketplace.purchase"` \| `"workflow.run"` \| `"workflow.publish"` \| `"workflow.arm"` \| `"world"` \| `"channels.read"` \| `"channels.personal.manage"`; `grant`: \| `Readonly`\<\{ `operations`: readonly `string`[]; `resources`: \| `"tenant-scope"` \| readonly `Readonly`\<\{ `kind`: `string`; `id`: `string`; \}\>[]; \}\> \| `null`; \}\>[] | - |
199
200
 
200
201
  ###### Returns
201
202
 
@@ -1524,6 +1525,10 @@ const permissionPinsSchema: ZodObject<
1524
1525
  storeGeneration: ZodString;
1525
1526
  authorityVersion: ZodNumber;
1526
1527
  artifactDigest: ZodPipe<ZodUnknown, ZodTransform<Sha256Digest, unknown>>;
1528
+ declaredOperationsDigest: ZodPipe<
1529
+ ZodUnknown,
1530
+ ZodTransform<Sha256Digest, unknown>
1531
+ >;
1527
1532
  },
1528
1533
  $strict
1529
1534
  >;
@@ -1540,6 +1545,7 @@ const permissionSaveSchema: ZodObject<{
1540
1545
  storeGeneration: ZodString;
1541
1546
  authorityVersion: ZodNumber;
1542
1547
  artifactDigest: ZodPipe<ZodUnknown, ZodTransform<Sha256Digest, unknown>>;
1548
+ declaredOperationsDigest: ZodPipe<ZodUnknown, ZodTransform<Sha256Digest, unknown>>;
1543
1549
  command: ZodDiscriminatedUnion<[ZodObject<{
1544
1550
  kind: ZodLiteral<"install">;
1545
1551
  }, $strict>, ZodObject<{