From 8a03b88686effc9f07e53860fe0ab4e3cf3202f4 Mon Sep 17 00:00:00 2001 From: Rhys Sullivan <39114868+RhysSullivan@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:59:21 +0000 Subject: [PATCH 01/68] Export cd3556b5 --- .../src/implementation/onboarding-store.ts | 11 +- apps/hosted/cloud/src/implementation/sso.ts | 26 +-- .../src/implementation/registration.ts | 15 ++ .../src/implementation/organization-auth.ts | 89 ++++++++ apps/hosted/server/src/index.ts | 1 + apps/hosted/web/src/contracts/organization.ts | 16 +- e2e/ci-selection.ts | 11 +- e2e/support/invitation-authority.ts | 143 ++++++++++++ e2e/test-plan.ts | 58 ++++- ...cloud-invitation-inviter-authority.spec.ts | 24 ++ e2e/tests/cloud-sso.spec.ts | 27 +++ e2e/tests/invitation-dialog.spec.ts | 43 +++- .../invitation-inviter-authority.spec.ts | 30 +++ e2e/tests/invitation-reaccept.spec.ts | 6 + e2e/tests/invitation-redemption.spec.ts | 214 +++++++++++++----- e2e/tests/invitation-security.spec.ts | 38 +++- patches/better-auth-cancel-invitation.md | 22 ++ patches/better-auth@1.7.20.patch | 23 ++ 18 files changed, 715 insertions(+), 82 deletions(-) create mode 100644 e2e/support/invitation-authority.ts create mode 100644 e2e/tests/cloud-invitation-inviter-authority.spec.ts create mode 100644 e2e/tests/invitation-inviter-authority.spec.ts create mode 100644 patches/better-auth-cancel-invitation.md diff --git a/apps/hosted/cloud/src/implementation/onboarding-store.ts b/apps/hosted/cloud/src/implementation/onboarding-store.ts index 638e1bafe6..c820ff3f92 100644 --- a/apps/hosted/cloud/src/implementation/onboarding-store.ts +++ b/apps/hosted/cloud/src/implementation/onboarding-store.ts @@ -3,6 +3,7 @@ import { SqlClient } from "effect/sql"; import { fumadb } from "fumadb-effect"; import { column, idColumn, schema, table } from "fumadb-effect/schema"; import { sqlAdapter } from "fumadb-effect/sql"; +import { invitingRoles } from "@executor-js/hosted-server"; import { SetupOrder, SetupSkip } from "@executor-js/hosted-server/setup"; import { CompanyProfile, @@ -65,7 +66,8 @@ export const makeOnboardingStore = Effect.gen(function* () { Effect.map((rows) => rows[0]), ); // This statement must follow the user lock so a waiting request sees the - // previous transaction's committed membership under READ COMMITTED. + // previous transaction's committed membership under READ COMMITTED. The invitation is one that + // can still be accepted: its inviter still holds a role that may invite (`inviterMayInvite`). const state = (id: string, email: string) => sql`select coalesce((select jsonb_agg(jsonb_build_object( @@ -73,8 +75,11 @@ export const makeOnboardingStore = Effect.gen(function* () { ) order by o."createdAt", o.id) from organization o join member m on m."organizationId" = o.id where m."userId" = ${id} and not exists (select 1 from hosted_organization_removal r where r.organization_id = o.id)), '[]'::jsonb) as organizations, - (select id from invitation where lower(email) = lower(${email}) and status = 'pending' - and "expiresAt" > now() order by "expiresAt", id limit 1) as invitation, + (select i.id from invitation i where lower(i.email) = lower(${email}) and i.status = 'pending' + and i."expiresAt" > now() + and exists (select 1 from member im where im."userId" = i."inviterId" + and im."organizationId" = i."organizationId" and im.role in ${sql.in(invitingRoles)}) + order by i."expiresAt", i.id limit 1) as invitation, (exists(select 1 from cloud_organization_setup where user_id = ${id}) or exists(select 1 from invitation where lower(email) = lower(${email}) and status = 'accepted')) as provisioned `.pipe( diff --git a/apps/hosted/cloud/src/implementation/sso.ts b/apps/hosted/cloud/src/implementation/sso.ts index 64d7e0b85f..6e7b238c33 100644 --- a/apps/hosted/cloud/src/implementation/sso.ts +++ b/apps/hosted/cloud/src/implementation/sso.ts @@ -3,6 +3,7 @@ import type { AuthContext, BetterAuthPlugin, GenericEndpointContext } from "bett import { getCurrentAdapter } from "better-auth"; import { APIError, createAuthMiddleware, getSessionFromCtx } from "better-auth/api"; import { symmetricDecrypt, symmetricEncrypt } from "better-auth/crypto"; +import { inviterMayInvite } from "@executor-js/hosted-server"; import { Option, Schema } from "effect"; import type { CloudBillingHooks } from "./auth-options.ts"; @@ -148,19 +149,18 @@ export const cloudSso = (billing?: CloudBillingHooks) => { }) ) return; - // An explicit invitation owns its role and must still be accepted. - if ( - await database.findOne({ - model: "invitation", - where: [ - { field: "organizationId", value: provider.organizationId }, - { field: "email", value: user.email.toLowerCase() }, - { field: "status", value: "pending" }, - { field: "expiresAt", value: new Date(), operator: "gt" }, - ], - }) - ) - return; + // An explicit invitation owns its role and must still be accepted, if it still can be. + const invitations = await database.findMany<{ organizationId: string; inviterId: string }>({ + model: "invitation", + where: [ + { field: "organizationId", value: provider.organizationId }, + { field: "email", value: user.email.toLowerCase() }, + { field: "status", value: "pending" }, + { field: "expiresAt", value: new Date(), operator: "gt" }, + ], + }); + for (const invitation of invitations) + if (await inviterMayInvite(database, invitation)) return; const count = await database.count({ model: "member", where: [{ field: "organizationId", value: provider.organizationId }], diff --git a/apps/hosted/self-host/src/implementation/registration.ts b/apps/hosted/self-host/src/implementation/registration.ts index 411874678d..e3824ea628 100644 --- a/apps/hosted/self-host/src/implementation/registration.ts +++ b/apps/hosted/self-host/src/implementation/registration.ts @@ -11,6 +11,7 @@ import type { } from "@better-auth/core"; import { APIError, createAuthEndpoint, isAPIError } from "better-auth/api"; import { setSessionCookie } from "better-auth/cookies"; +import { inviterMayInvite } from "@executor-js/hosted-server"; import { SsoRefusal } from "@executor-js/hosted-self-host-web/sso"; import { Cause, Effect, Exit, Schema } from "effect"; import { z } from "zod"; @@ -28,6 +29,7 @@ const Invitation = Schema.Struct({ id: Schema.String, email: Schema.String, organizationId: Schema.String, + inviterId: Schema.String, role: Schema.Literals(["admin", "member"]), status: Schema.String, expiresAt: Schema.Date, @@ -228,6 +230,10 @@ const register = ( return yield* deny( "This invitation is invalid, expired, or for a different email.", ); + if (!(yield* call(() => inviterMayInvite(adapter, invitation)))) + return yield* deny( + "The person who sent this invitation can no longer invite members. Ask an administrator for a new invitation.", + ); organizationId = org.id; role = invitation.role; yield* call(() => @@ -328,4 +334,13 @@ export const selfHostRegistration = (settings: Effect.Success register(ctx, ctx.body, { invitation: ctx.body.invitation }), ), }, + // Both routes check a password (registration does for an existing account), so they take + // Better Auth's sign-in limit: three requests per address every ten seconds. + rateLimit: [ + { + pathMatcher: (path) => path === "/self-host/setup" || path === "/self-host/register", + window: 10, + max: 3, + }, + ], }) satisfies BetterAuthPlugin; diff --git a/apps/hosted/server/src/implementation/organization-auth.ts b/apps/hosted/server/src/implementation/organization-auth.ts index 1c8248c9e1..ef2c70e125 100644 --- a/apps/hosted/server/src/implementation/organization-auth.ts +++ b/apps/hosted/server/src/implementation/organization-auth.ts @@ -1,3 +1,4 @@ +import type { AuthContext } from "@better-auth/core"; import type { BetterAuthPlugin } from "better-auth"; import { APIError, createAuthMiddleware, getSessionFromCtx } from "better-auth/api"; import { Option, Schema } from "effect"; @@ -34,13 +35,54 @@ const StoredInvitation = Schema.Struct({ role: InviteMember.fields.role, status: Schema.String, organizationId: Schema.NonEmptyString, + inviterId: Schema.NonEmptyString, }); +/** A membership as the remove and role-change routes return it. */ +const ChangedMember = Schema.Struct({ + userId: Schema.NonEmptyString, + organizationId: Schema.NonEmptyString, + role: OrganizationRole, +}); +const RemovedMember = Schema.Struct({ member: ChangedMember }); + +/** + * The roles that may send invitations, at either the admin or the member role. Executor checks + * the role, not its rank: an admin's invitation as admin is as valid as an owner's. An invitation + * keeps its authority only while its inviter still holds one of these roles in its organization. + */ +export const invitingRoles = ["owner", "admin"] as const; +const mayInvite = (role: typeof OrganizationRole.Type) => + (invitingRoles as ReadonlyArray).includes(role); + +/** + * Whether the invitation's inviter is still a member who may invite. Acceptance and self-host + * registration copy the stored role into a new membership, so they check this first, and Cloud's + * entry and SSO sign-in pass over invitations that fail it. SQL readers state the same rule with + * `invitingRoles`. + */ +export const inviterMayInvite = async ( + adapter: Pick, + invitation: { readonly organizationId: string; readonly inviterId: string }, +) => { + const inviter = Schema.decodeUnknownOption(Membership)( + await adapter.findOne({ + model: "member", + where: [ + { field: "userId", value: invitation.inviterId }, + { field: "organizationId", value: invitation.organizationId }, + ], + select: ["role"], + }), + ); + return Option.isSome(inviter) && mayInvite(inviter.value.role); +}; const JoinedMember = Schema.Struct({ organizationId: Schema.NonEmptyString }); const JoinedOrganization = Schema.Struct({ name: Schema.String }); const SentInvitation = Schema.Struct({ id: Schema.NonEmptyString, email: Schema.NonEmptyString, organizationId: Schema.NonEmptyString, + inviterId: Schema.NonEmptyString, }); /** @@ -167,6 +209,14 @@ export const explicitOrganizationAuth = { alreadyMember: { name: organization.value.name }, }); } + // Known limit: this check and Better Auth's acceptance are separate statements with no + // lock between them, so an inviter removed or demoted in that instant does not stop this + // acceptance, just as one a moment earlier would have gone through. + if (!(await inviterMayInvite(context.context.adapter, stored.value))) + throw new APIError("BAD_REQUEST", { + message: + "The person who sent this invitation can no longer invite members. Ask an administrator for a new invitation.", + }); return { context: { body: invitation.value } }; } // The invitation identifies the organization; Better Auth checks its current membership and cancel permission. @@ -198,6 +248,45 @@ export const explicitOrganizationAuth = { ], update: { status: "canceled" }, }); + // Native resend keeps the invitation's inviter and only renews its expiry. The member + // resending it has just passed Better Auth's invite permission check, so the invitation + // now carries their authority; otherwise an inviter who has since lost the role would + // leave the resent invitation unredeemable. + const session = await getSessionFromCtx(context); + if (session === null || sent.value.inviterId === session.user.id) return; + const resent = await context.context.adapter.update>({ + model: "invitation", + where: [ + { field: "id", value: sent.value.id }, + { field: "status", value: "pending" }, + ], + update: { inviterId: session.user.id }, + }); + if (resent !== null) return context.json(resent); + }), + }, + { + matcher: (context) => + context.path === "/organization/remove-member" || + context.path === "/organization/update-member-role", + // A member who leaves, or loses the role that let them invite, takes back the + // invitations they sent that are still pending. + handler: createAuthMiddleware(async (context) => { + const returned = context.context.returned; + const removed = context.path === "/organization/remove-member"; + const member = removed + ? Option.map(Schema.decodeUnknownOption(RemovedMember)(returned), (r) => r.member) + : Schema.decodeUnknownOption(ChangedMember)(returned); + if (Option.isNone(member) || (!removed && mayInvite(member.value.role))) return; + await context.context.adapter.updateMany({ + model: "invitation", + where: [ + { field: "organizationId", value: member.value.organizationId }, + { field: "inviterId", value: member.value.userId }, + { field: "status", value: "pending" }, + ], + update: { status: "canceled" }, + }); }), }, ], diff --git a/apps/hosted/server/src/index.ts b/apps/hosted/server/src/index.ts index f90f511472..97db7ae2e2 100644 --- a/apps/hosted/server/src/index.ts +++ b/apps/hosted/server/src/index.ts @@ -82,6 +82,7 @@ export { migrateOrganizationRemovals } from "./implementation/organization-remov export * from "./contracts/user-removal.ts"; export { previewUserRemoval, removeUser } from "./implementation/user-removal.ts"; export { deleteUserRecords } from "./implementation/user-records.ts"; +export { inviterMayInvite, invitingRoles } from "./implementation/organization-auth.ts"; export { hostedOAuthCallback } from "./implementation/accounts.ts"; export * from "./contracts/oauth-client-metadata.ts"; diff --git a/apps/hosted/web/src/contracts/organization.ts b/apps/hosted/web/src/contracts/organization.ts index 6f5200f5ea..b3da4daead 100644 --- a/apps/hosted/web/src/contracts/organization.ts +++ b/apps/hosted/web/src/contracts/organization.ts @@ -58,13 +58,15 @@ const request = ( result.error.code === "ORGANIZATION_SLUG_ALREADY_TAKEN" || result.error.code === "ORGANIZATION_ALREADY_EXISTS" ? "This organization URL is already in use. Choose another." - : result.error.code === "INVITATION_NOT_FOUND" - ? "This invitation has already been used, was revoked, or has expired. Ask an administrator for a new invitation." - : result.error.code === "ORGANIZATION_MEMBERSHIP_LIMIT_REACHED" - ? "This organization has reached its plan's member limit. An owner or admin can upgrade the plan to add members." - : result.error.status === 403 - ? "You do not have permission to do that." - : "Unable to update the organization. Check the details and try again.", + : result.error.code === "INVITATION_ALREADY_ACCEPTED" + ? "This person has already accepted the invitation and joined. Change their role or remove them in the members list." + : result.error.code === "INVITATION_NOT_FOUND" + ? "This invitation has already been used, was revoked, or has expired. Ask an administrator for a new invitation." + : result.error.code === "ORGANIZATION_MEMBERSHIP_LIMIT_REACHED" + ? "This organization has reached its plan's member limit. An owner or admin can upgrade the plan to add members." + : result.error.status === 403 + ? "You do not have permission to do that." + : "Unable to update the organization. Check the details and try again.", }), ), ), diff --git a/e2e/ci-selection.ts b/e2e/ci-selection.ts index 087c3a3158..561566a73a 100644 --- a/e2e/ci-selection.ts +++ b/e2e/ci-selection.ts @@ -178,7 +178,7 @@ const jobs = { runner: 3, pattern: - "Cloud SSO SAML accepts|Cloud's operator OAuth client signs in|Cloud's own Executor for Google registration refuses|Safari reports only the page's own failures|Cloud cron triggers run their jobs|Cloud cron jobs record their outcome|Cloud support dialog lists every channel|Hosted feedback enforces its API contract|Executor's catalog calls an app's own cache methods|Executor app is installed with nothing left pending|Cloud MCP routes a request inside a session|Cloud MCP sessions continue after their session object is evicted|Request and workflow attempts at one team|remote skill catalog|a skill read without a revision|abandons a GitHub skills load|reads its catalog and the tool in one cache command|a cold call's wake is reported by that call alone|another organization's admin cannot read the link|account connections cannot cross organizations|Deploys wake webhook source setup|Cloud's schedule coordinator keeps nine slow scheduled runs|a webhook source reconciling for an activation that another supersedes|A skill catalog refreshed in the background after a dashboard batch read|Cloud MCP session objects run parallel tool calls|Cloud MCP session objects cancel a statement|Cloud MCP session objects discover the other apps|Cloud MCP session objects' database pool|Cloud's database pool runs a statement whose connection|Hosted MCP resume reports an approved call's own failure|Cloud refuses to remove an organization while one of its app workflows runs|Cloud v1 session handoff|Cloud accepts MCP requests v1 forwards|Cloud validates a v1 WorkOS API key|Hosted MCP operation and bearer-check spans name|Hosted management API request spans name only|Hosted request spans record the client, the credential|Cloud's gateway names an authenticated MCP request's organization|A person deletes their own user|On Cloud a slow tool call log write|A Cloud scenario's clean-up returns once its organization's removal is accepted|The end-of-run removal check answers each look within its request limit|The end-of-run removal check asks again after a dropped request|The end-of-run removal check keeps waiting for a removal recorded done|a run's sleep whose engine call failed is called again", + "Cloud SSO SAML accepts|Cloud's operator OAuth client signs in|Cloud's own Executor for Google registration refuses|Safari reports only the page's own failures|Cloud cron triggers run their jobs|Cloud cron jobs record their outcome|Cloud support dialog lists every channel|Hosted feedback enforces its API contract|Executor's catalog calls an app's own cache methods|Executor app is installed with nothing left pending|Cloud MCP routes a request inside a session|Cloud MCP sessions continue after their session object is evicted|Request and workflow attempts at one team|remote skill catalog|a skill read without a revision|abandons a GitHub skills load|reads its catalog and the tool in one cache command|a cold call's wake is reported by that call alone|another organization's admin cannot read the link|account connections cannot cross organizations|Deploys wake webhook source setup|Cloud's schedule coordinator keeps nine slow scheduled runs|a webhook source reconciling for an activation that another supersedes|A skill catalog refreshed in the background after a dashboard batch read|Cloud MCP session objects run parallel tool calls|Cloud MCP session objects cancel a statement|Cloud MCP session objects discover the other apps|Cloud MCP session objects' database pool|Cloud's database pool runs a statement whose connection|Hosted MCP resume reports an approved call's own failure|Cloud refuses to remove an organization while one of its app workflows runs|Cloud v1 session handoff|Cloud accepts MCP requests v1 forwards|Cloud validates a v1 WorkOS API key|Hosted MCP operation and bearer-check spans name|Hosted management API request spans name only|Hosted request spans record the client, the credential|Cloud's gateway names an authenticated MCP request's organization|A person deletes their own user|Cloud invitations left pending after their inviter lost|On Cloud a slow tool call log write|A Cloud scenario's clean-up returns once its organization's removal is accepted|The end-of-run removal check answers each look within its request limit|The end-of-run removal check asks again after a dropped request|The end-of-run removal check keeps waiting for a removal recorded done|a run's sleep whose engine call failed is called again", }, // Cloud's hosts: role hosts, the edge and sign-in on `app.`. Run in `cloud-product`, their // load kept the team installation's workflow span from arriving within its 30-second wait, so @@ -630,6 +630,15 @@ const patchGuards: Readonly>> = { "local-workflow-engine-memory.spec.ts", "workflow-durability.spec.ts", ], + // Its patch makes cancelling refuse an invitation that is no longer pending (the reaccept and + // dialog scenarios), has self-host SSO read UserInfo claims through generic OAuth's guarded + // fetch, and checks timestamps the database rate limiter reads back. + "better-auth": [ + "invitation-reaccept.spec.ts", + "invitation-dialog.spec.ts", + "self-host-sso.spec.ts", + "cloud-auth-rate-limit.spec.ts", + ], "@opencode-ai/codemode": [ "mcp-catalog.spec.ts", "mcp-execute-concurrency.spec.ts", diff --git a/e2e/support/invitation-authority.ts b/e2e/support/invitation-authority.ts new file mode 100644 index 0000000000..9d047af6d8 --- /dev/null +++ b/e2e/support/invitation-authority.ts @@ -0,0 +1,143 @@ +/** + * Invitations whose inviter no longer holds a role that may invite, left pending as a cleanup that + * never ran would leave them. Changing the role through the API cancels them, so each target's + * scenario changes it in its own storage with `write` instead, and this checks that nothing + * redeems or offers them, and that an owner resending one makes it acceptable. + */ +import { expect } from "@effect/vitest"; +import { Effect, Schema } from "effect"; +import { Api, body } from "./api.ts"; +import { Actors, password } from "./actors.ts"; +import { Resource } from "./contracts.ts"; +import { Target } from "./platform.ts"; +import { freeSeat } from "./seats.ts"; + +const Invitations = Schema.Array(Schema.Struct({ id: Schema.String, status: Schema.String })); + +/** One parameterized statement against the target's own auth tables. */ +export interface RoleStatement { + readonly sql: string; + readonly params: ReadonlyArray; +} + +type Write = ( + statements: readonly [RoleStatement], +) => Effect.Effect>, E, R>; + +/** Makes the admin a member in storage, so their pending invitations stay pending. */ +const demoteAdmin = (write: Write) => + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors; + const { userId } = yield* body( + Schema.Struct({ userId: Schema.String }), + yield* api.request(actors.admin, "GET", "/api/viewer"), + ); + const demote: readonly [RoleStatement] = [ + { + sql: `update member set role = 'member' where "organizationId" = $1 and "userId" = $2 + returning role`, + params: [actors.organization.id, userId], + }, + ]; + expect(yield* write(demote)).toEqual([[{ role: "member" }]]); + }); + +export const staleInvitations = (write: Write) => + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors, + target = yield* Target; + const cloud = target.metadata.target === "cloud"; + const organizationId = actors.organization.id; + const invite = (email: string) => + Effect.gen(function* () { + const response = yield* api.request( + actors.admin, + "POST", + "/api/auth/organization/invite-member", + { organizationId, email, role: "admin" }, + ); + expect(response.status).toBe(200); + return (yield* body(Resource, response)).id; + }); + // The admin invites the removed member back, and on self-host someone without an account. + const seat = yield* freeSeat; + const returning = yield* invite(seat.email); + const newcomer = "invited-before-demotion@example.test"; + const unregistered = cloud ? undefined : yield* invite(newcomer); + // The admin becomes a member in storage; their invitations stay pending. + yield* demoteAdmin(write); + const invitations = yield* body( + Invitations, + yield* api.request( + actors.owner, + "GET", + `/api/auth/organization/list-invitations?organizationId=${organizationId}`, + ), + ); + for (const id of [returning, unregistered].filter((id) => id !== undefined)) + expect(invitations.find((invitation) => invitation.id === id)?.status).toBe("pending"); + if (cloud) { + // Cloud's entry does not send the member to an invitation that cannot be accepted. + const entry = yield* api.request(actors.member, "POST", "/api/onboarding/prepare"); + expect(entry.status).toBe(200); + expect((yield* body(Schema.Struct({ status: Schema.String }), entry)).status).toBe("draft"); + } + // Accepting is refused, so the member does not come back as an admin. + expect( + (yield* api.request(actors.member, "POST", "/api/auth/organization/accept-invitation", { + invitationId: returning, + })).status, + ).toBe(400); + expect( + (yield* api.request(actors.member, "GET", `/api/organizations/${organizationId}/access`)) + .status, + ).toBe(403); + // Self-host registration with the other invitation is refused as well. + if (unregistered !== undefined) + expect( + (yield* api.request(yield* api.session(), "POST", "/api/auth/self-host/register", { + invitation: unregistered, + email: newcomer, + name: "Invited user", + password, + })).status, + ).toBe(403); + }); + +/** + * An owner's resend of an invitation whose inviter has since become a member makes it acceptable + * again; the former admin's own resend is refused. + */ +export const resentStaleInvitation = (write: Write) => + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors; + const organizationId = actors.organization.id; + const resend = (actor: typeof actors.owner, email: string) => + api.request(actor, "POST", "/api/auth/organization/invite-member", { + organizationId, + email, + role: "admin", + resend: true, + }); + const seat = yield* freeSeat; + const invited = yield* resend(actors.admin, seat.email); + expect(invited.status).toBe(200); + const { id } = yield* body(Resource, invited); + yield* demoteAdmin(write); + expect((yield* resend(actors.admin, seat.email)).status).toBe(403); + const resent = yield* resend(actors.owner, seat.email); + expect(resent.status).toBe(200); + expect((yield* body(Resource, resent)).id).toBe(id); + expect( + (yield* api.request(actors.member, "POST", "/api/auth/organization/accept-invitation", { + invitationId: id, + })).status, + ).toBe(200); + expect( + (yield* api.request(actors.member, "GET", `/api/organizations/${organizationId}/access`)) + .status, + ).toBe(200); + }); diff --git a/e2e/test-plan.ts b/e2e/test-plan.ts index fc3698457b..83e0b1517e 100644 --- a/e2e/test-plan.ts +++ b/e2e/test-plan.ts @@ -9784,10 +9784,66 @@ export const scenarios = plan({ }, }, invitationRedemption: { + fixtures: "actors", + file: "invitation-redemption.spec.ts", + title: "self-host invitation links admit the intended role exactly once", + targets: { + local: na("Self-host invitation signup."), + "self-host": scheduled, + cloud: na("Cloud requires a verified recipient instead of password registration."), + }, + }, + invitationInviterAuthority: { + fixtures: "actors", + file: "invitation-inviter-authority.spec.ts", + legacyStorage: true, + title: + "self-host invitations left pending after their inviter lost the role to invite are neither accepted nor registered", + targets: { + local: na("Hosted organization invitations."), + "self-host": scheduled, + cloud: na("cloud-invitation-inviter-authority.spec.ts writes Cloud's own database."), + }, + }, + invitationInviterResend: { + fixtures: "actors", + file: "invitation-inviter-authority.spec.ts", + legacyStorage: true, + title: + "self-host invitations left pending after their inviter lost the role to invite are accepted once an owner resends them", + targets: { + local: na("Hosted organization invitations."), + "self-host": scheduled, + cloud: na("cloud-invitation-inviter-authority.spec.ts writes Cloud's own database."), + }, + }, + cloudInvitationInviterResend: { + fixtures: "actors", + file: "cloud-invitation-inviter-authority.spec.ts", + title: + "Cloud invitations left pending after their inviter lost the role to invite are accepted once an owner resends them", + targets: { + local: na("Hosted organization invitations."), + "self-host": na("invitation-inviter-authority.spec.ts writes self-host's own database."), + cloud: managedCloud, + }, + }, + cloudInvitationInviterAuthority: { + fixtures: "actors", + file: "cloud-invitation-inviter-authority.spec.ts", + title: + "Cloud invitations left pending after their inviter lost the role to invite are neither accepted nor offered at entry", + targets: { + local: na("Hosted organization invitations."), + "self-host": na("invitation-inviter-authority.spec.ts writes self-host's own database."), + cloud: managedCloud, + }, + }, + invitationReadmission: { fixtures: "actors", file: "invitation-redemption.spec.ts", title: - "self-host invitation links admit the intended role exactly once without replacing accounts", + "self-host invitations readmit a former admin as a member only with their password and die with their inviter's membership", targets: { local: na("Self-host invitation signup."), "self-host": scheduled, diff --git a/e2e/tests/cloud-invitation-inviter-authority.spec.ts b/e2e/tests/cloud-invitation-inviter-authority.spec.ts new file mode 100644 index 0000000000..7eae918eaf --- /dev/null +++ b/e2e/tests/cloud-invitation-inviter-authority.spec.ts @@ -0,0 +1,24 @@ +/** + * Cloud invitations left pending after their inviter lost the role to invite, made by changing the + * role in managed Cloud's database. + */ +import { layer } from "@effect/vitest"; +import { HostedLive, withHostedCase } from "../support/case.ts"; +import { writeRows } from "../support/cloud-rows.ts"; +import { resentStaleInvitation, staleInvitations } from "../support/invitation-authority.ts"; +import { scenarios } from "../test-plan.ts"; + +layer(HostedLive, { excludeTestServices: true })("Cloud invitation inviter authority", (it) => { + it.effect(scenarios.cloudInvitationInviterAuthority.title, (context) => + withHostedCase( + context, + staleInvitations((statements) => writeRows("sso-database.json", statements)), + ), + ); + it.effect(scenarios.cloudInvitationInviterResend.title, (context) => + withHostedCase( + context, + resentStaleInvitation((statements) => writeRows("sso-database.json", statements)), + ), + ); +}); diff --git a/e2e/tests/cloud-sso.spec.ts b/e2e/tests/cloud-sso.spec.ts index d0a142606f..cd2daba62c 100644 --- a/e2e/tests/cloud-sso.spec.ts +++ b/e2e/tests/cloud-sso.spec.ts @@ -6,6 +6,7 @@ import { Actors, freshOwnerSession } from "../support/actors.ts"; import { Api, body } from "../support/api.ts"; import { Browser } from "../support/browser.ts"; import { Target } from "../support/platform.ts"; +import { writeRows } from "../support/cloud-rows.ts"; import { ssoFixture } from "../support/sso.ts"; import { scenarios } from "../test-plan.ts"; import { holdQuery } from "../support/query-transition.ts"; @@ -793,6 +794,19 @@ layer(HostedLive, { excludeTestServices: true })("Cloud customer SSO", (it) => { yield* browser.checkpoint("Verified SAML setup"); yield* signOut; const email = `saml-${randomUUID().slice(0, 8)}@sso.example.test`; + // An invitation from someone who cannot invite to this team does not hold back joining. + const { userId: outsider } = yield* body( + Schema.Struct({ userId: Schema.String }), + yield* api.request(actors.member, "GET", "/api/viewer"), + ); + yield* writeRows("sso-database.json", [ + { + sql: `insert into invitation + (id, "organizationId", email, role, status, "expiresAt", "createdAt", "inviterId") + values ($1, $2, $3, 'admin', 'pending', now() + interval '1 day', now(), $4)`, + params: [`stale-${randomUUID()}`, team.id, email, outsider], + }, + ]); yield* fixture.configure(email); const destination = `/org/${team.slug}/organization`; yield* startFromEmail(email, destination); @@ -803,6 +817,19 @@ layer(HostedLive, { excludeTestServices: true })("Cloud customer SSO", (it) => { const identity = yield* browserSession; expect(identity.user.email).toBe(email); expect(identity.user.emailVerified).toBe(true); + const roster = yield* body( + Schema.Struct({ + members: Schema.Array(Schema.Struct({ userId: Schema.String, role: Schema.String })), + }), + yield* api.request( + actors.owner, + "GET", + `/api/auth/organization/list-members?organizationId=${team.id}`, + ), + ); + expect( + roster.members.filter((row) => row.userId === identity.user.id).map((row) => row.role), + ).toEqual(["member"]); yield* browser.checkpoint("SAML member opens their team"); yield* signOut; yield* browser.use("Replay the already consumed assertion", (page) => diff --git a/e2e/tests/invitation-dialog.spec.ts b/e2e/tests/invitation-dialog.spec.ts index 1dacb77b23..24b1c93430 100644 --- a/e2e/tests/invitation-dialog.spec.ts +++ b/e2e/tests/invitation-dialog.spec.ts @@ -4,8 +4,10 @@ import { Effect } from "effect"; import { randomUUID } from "node:crypto"; import type { Page } from "playwright"; import { Actors } from "../support/actors.ts"; +import { Api, body } from "../support/api.ts"; import { Browser } from "../support/browser.ts"; import { HostedLive, withHostedCase } from "../support/case.ts"; +import { Resource } from "../support/contracts.ts"; import { freeSeat } from "../support/seats.ts"; import { scenarios } from "../test-plan.ts"; @@ -17,7 +19,7 @@ layer(HostedLive, { excludeTestServices: true })("Invitation dialog", (it) => { const actors = yield* Actors; const browser = yield* Browser; const email = `invite-${randomUUID().slice(0, 8)}@example.test`; - yield* freeSeat; + const seat = yield* freeSeat; yield* browser.login(actors.owner); yield* browser.use("Open organization settings", (page) => page.goto(`/org/${actors.organization.slug}/organization`), @@ -115,6 +117,45 @@ layer(HostedLive, { excludeTestServices: true })("Invitation dialog", (it) => { yield* browser.use("The invitation row is removed", (page) => row(page).waitFor({ state: "detached" }), ); + // The member is invited back and accepts while the list still shows the invitation. + const api = yield* Api; + const sent = yield* api.request( + actors.owner, + "POST", + "/api/auth/organization/invite-member", + { + organizationId: actors.organization.id, + email: seat.email, + role: "member", + }, + ); + expect(sent.status).toBe(200); + const returning = yield* body(Resource, sent); + const revoke = (page: Page) => + page.getByRole("button", { name: `Revoke invitation to ${seat.email}`, exact: true }); + yield* browser.use("Reload the members list", (page) => + page.reload().then(() => revoke(page).waitFor({ state: "visible" })), + ); + expect( + (yield* api.request(actors.member, "POST", "/api/auth/organization/accept-invitation", { + invitationId: returning.id, + })).status, + ).toBe(200); + yield* browser.use("Revoke the accepted invitation", (page) => revoke(page).click()); + yield* browser.use("Confirm revoking it", (page) => + page.getByRole("button", { name: "Revoke invitation", exact: true }).click(), + ); + expect( + yield* browser.use("The dialog says the person has joined", (page) => + dialog(page) + .getByRole("alert") + .waitFor({ state: "visible" }) + .then(() => dialog(page).getByRole("alert").textContent()), + ), + ).toBe( + "This person has already accepted the invitation and joined. Change their role or remove them in the members list.", + ); + yield* browser.checkpoint("Revoking an accepted invitation"); }), ), ); diff --git a/e2e/tests/invitation-inviter-authority.spec.ts b/e2e/tests/invitation-inviter-authority.spec.ts new file mode 100644 index 0000000000..9eb64b867a --- /dev/null +++ b/e2e/tests/invitation-inviter-authority.spec.ts @@ -0,0 +1,30 @@ +/** + * Self-host invitations left pending after their inviter lost the role to invite, made by changing + * the role in the product's database while it is stopped. + */ +import { layer } from "@effect/vitest"; +import { Effect } from "effect"; +import { HostedLive, withHostedCase } from "../support/case.ts"; +import { resentStaleInvitation, staleInvitations } from "../support/invitation-authority.ts"; +import { legacyStorage } from "../support/legacy-storage.ts"; +import { serverControl } from "../support/server-control.ts"; +import { scenarios } from "../test-plan.ts"; + +layer(HostedLive, { excludeTestServices: true })("Invitation inviter authority", (it) => { + it.effect(scenarios.invitationInviterAuthority.title, (context) => + withHostedCase( + context, + staleInvitations((statements) => + legacyStorage(statements).pipe(Effect.tap(() => serverControl("start"))), + ), + ), + ); + it.effect(scenarios.invitationInviterResend.title, (context) => + withHostedCase( + context, + resentStaleInvitation((statements) => + legacyStorage(statements).pipe(Effect.tap(() => serverControl("start"))), + ), + ), + ); +}); diff --git a/e2e/tests/invitation-reaccept.spec.ts b/e2e/tests/invitation-reaccept.spec.ts index e4f82691e5..2f50b6468e 100644 --- a/e2e/tests/invitation-reaccept.spec.ts +++ b/e2e/tests/invitation-reaccept.spec.ts @@ -82,6 +82,12 @@ layer(HostedLive, { excludeTestServices: true })("Invitation reaccept", (it) => ); expect(access.status).toBe(200); yield* browser.checkpoint("Joined the organization"); + // Cancelling an invitation that was already accepted is refused; it stays accepted. + expect( + (yield* api.request(actors.owner, "POST", "/api/auth/organization/cancel-invitation", { + invitationId: invitation, + })).status, + ).toBe(400); // The recipient opens the same link again, as from the email or the back button. const reopened = yield* accept("Second visit", invitation); diff --git a/e2e/tests/invitation-redemption.spec.ts b/e2e/tests/invitation-redemption.spec.ts index f6a683fe94..726f5d6dff 100644 --- a/e2e/tests/invitation-redemption.spec.ts +++ b/e2e/tests/invitation-redemption.spec.ts @@ -1,43 +1,139 @@ -/** Real self-host invitation registration, replay, concurrency and existing-account authority. */ +/** + * Real self-host invitation registration, replay, concurrency, existing-account authority and the + * registration rate limit. + * + * Setup and registration take sign-in's limit: three requests from one address every ten seconds, + * counted for each path. Every request here comes from one address, and provisioning has already + * set up the instance and registered the admin and the member, so a scenario that needs the + * registration window first spends what is left of it and waits out the time Better Auth names. + */ import { expect, layer } from "@effect/vitest"; import { Effect, Schema } from "effect"; +import { HttpClient, HttpClientRequest } from "effect/http"; import { Api, body, type Session } from "../support/api.ts"; import { Actors, password } from "../support/actors.ts"; import { HostedLive, withHostedCase } from "../support/case.ts"; import { Resource } from "../support/contracts.ts"; +import { Target } from "../support/platform.ts"; import { scenarios } from "../test-plan.ts"; +const SessionIdentity = Schema.Struct({ user: Schema.Struct({ email: Schema.String }) }); +const Invitations = Schema.Array(Schema.Struct({ id: Schema.String, status: Schema.String })); +const Access = Schema.Struct({ role: Schema.String }); +/** Seconds named by Better Auth's X-Retry-After header, within the ten-second window. */ +const retryAfter = Schema.decodeUnknownEffect( + Schema.NumberFromString.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(10)), +); + +/** A request from a client without cookies, with the limit's retry time when it refuses. */ +const postAnonymously = (path: "setup" | "register", input: Record) => + Effect.gen(function* () { + const target = yield* Target, + http = yield* HttpClient.HttpClient; + const origin = target.metadata.origin; + return yield* Effect.scoped( + Effect.gen(function* () { + const request = yield* HttpClientRequest.post(`${origin}/api/auth/self-host/${path}`).pipe( + HttpClientRequest.setHeaders({ origin }), + HttpClientRequest.bodyJson({ ...input, name: "Invited user" }), + ); + const response = yield* http.execute(request); + yield* response.text; + return { status: response.status, retryAfter: response.headers["x-retry-after"] }; + }), + ); + }); + +/** + * Repeat `attempt` until it is refused for its rate, and return the seconds the refusal names. + * Every answer before then is `refused`. Provisioning spent at most two of the path's three + * requests, so the first attempt is always answered and the fourth at the latest is limited. + */ +const spendLimit = (attempt: ReturnType, refused: number) => + Effect.gen(function* () { + const statuses: Array = []; + let wait: number | undefined; + while (wait === undefined && statuses.length < 4) { + const answer = yield* attempt; + statuses.push(answer.status); + if (answer.status === 429) wait = yield* retryAfter(answer.retryAfter); + } + expect(statuses[0]).toBe(refused); + expect(statuses.slice(0, -1).every((status) => status === refused)).toBe(true); + expect(statuses.at(-1)).toBe(429); + return wait ?? 0; + }); +/** Spend what is left of the registration window and wait until a new one opens. */ +const spendRegistrationLimit = (input: Record, refused: number) => + Effect.flatMap(spendLimit(postAnonymously("register", input), refused), (wait) => + Effect.sleep(`${wait} seconds`), + ); + layer(HostedLive, { excludeTestServices: true })("Invitation redemption", (it) => { + const setup = Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors; + const organizationId = actors.organization.id; + const invite = (inviter: Session, email: string, role: "admin" | "member") => + Effect.gen(function* () { + const response = yield* api.request( + inviter, + "POST", + "/api/auth/organization/invite-member", + { organizationId, email, role }, + ); + expect(response.status).toBe(200); + return (yield* body(Resource, response)).id; + }); + const register = (session: Session, invitation: string, email: string, secret = password) => + api.request(session, "POST", "/api/auth/self-host/register", { + invitation, + email, + name: "Invited user", + password: secret, + }); + const role = (session: Session) => + Effect.flatMap( + api.request(session, "GET", `/api/organizations/${organizationId}/access`), + (response) => body(Access, response), + ).pipe(Effect.map((access) => access.role)); + const invitations = Effect.flatMap( + api.request( + actors.owner, + "GET", + `/api/auth/organization/list-invitations?organizationId=${organizationId}`, + ), + (response) => body(Invitations, response), + ); + const status = (id: string) => + Effect.map(invitations, (all) => all.find((invitation) => invitation.id === id)?.status); + const emailOf = (session: Session) => + Effect.flatMap(api.request(session, "GET", "/api/auth/get-session"), (response) => + body(SessionIdentity, response), + ).pipe(Effect.map((identity) => identity.user.email)); + const remove = (email: string) => + Effect.flatMap( + api.request(actors.owner, "POST", "/api/auth/organization/remove-member", { + organizationId, + memberIdOrEmail: email, + }), + (response) => Effect.sync(() => expect(response.status).toBe(200)), + ); + return { api, actors, invite, register, role, status, emailOf, remove }; + }); + it.effect(scenarios.invitationRedemption.title, (context) => withHostedCase( context, Effect.gen(function* () { - const api = yield* Api, - actors = yield* Actors; - const organizationId = actors.organization.id; - const invite = (email: string, role: "admin" | "member") => - Effect.gen(function* () { - const response = yield* api.request( - actors.admin, - "POST", - "/api/auth/organization/invite-member", - { organizationId, email, role }, - ); - expect(response.status).toBe(200); - return (yield* body(Resource, response)).id; - }); - const register = (session: Session, invitation: string, email: string, secret = password) => - api.request(session, "POST", "/api/auth/self-host/register", { - invitation, - email, - name: "Invited user", - password: secret, - }); + const { api, actors, invite, register, role } = yield* setup; const email = "new-admin@example.test"; - const invitation = yield* invite(email, "admin"); + const invitation = yield* invite(actors.admin, email, "admin"); + // An unknown invitation is refused, and so is every attempt past the limit. + yield* spendRegistrationLimit({ invitation: "unknown-invitation", email, password }, 403); + // The window is fresh: these three registrations fit in it. const recipient = yield* api.session(); expect((yield* register(recipient, invitation, "wrong@example.test")).status).toBe(403); - expect((yield* register(recipient, "unknown-invitation", email)).status).toBe(403); const rival = yield* api.session(); const raced = yield* Effect.all( [register(recipient, invitation, email), register(rival, invitation, email)], @@ -49,42 +145,50 @@ layer(HostedLive, { excludeTestServices: true })("Invitation redemption", (it) = (yield* api.request(login, "POST", "/api/auth/sign-in/email", { email, password })) .status, ).toBe(200); - const access = yield* api.request( - login, - "GET", - `/api/organizations/${organizationId}/access`, - ); - expect(access.status).toBe(200); - expect((yield* body(Schema.Struct({ role: Schema.String }), access)).role).toBe("admin"); - expect((yield* register(recipient, invitation, email)).status).toBe(403); - const cancelledEmail = "cancelled@example.test"; - const cancelled = yield* invite(cancelledEmail, "member"); + expect(yield* role(login)).toBe("admin"); + // Cancelling the accepted invitation is refused and leaves the membership in place. expect( (yield* api.request(actors.admin, "POST", "/api/auth/organization/cancel-invitation", { - invitationId: cancelled, + invitationId: invitation, })).status, - ).toBe(200); - expect((yield* register(recipient, cancelled, cancelledEmail)).status).toBe(403); - expect( - (yield* api.request(actors.owner, "POST", "/api/auth/organization/remove-member", { - organizationId, - memberIdOrEmail: email, - })).status, - ).toBe(200); - const readmission = yield* invite(email, "member"); - expect( - (yield* register(recipient, readmission, email, "attacker-chosen-password")).status, - ).toBe(403); - expect((yield* register(recipient, readmission, email)).status).toBe(200); - const readmitted = yield* api.request( - recipient, - "GET", - `/api/organizations/${organizationId}/access`, + ).toBe(400); + expect(yield* role(login)).toBe("admin"); + // Setup is refused once the instance has an owner, and repeated attempts are limited. + yield* spendLimit( + postAnonymously("setup", { email, password, organizationName: "Second organization" }), + 403, ); - expect((yield* body(Schema.Struct({ role: Schema.String }), readmitted)).role).toBe( - "member", + }), + ), + ); + + it.effect(scenarios.invitationReadmission.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { api, actors, invite, register, role, status, emailOf, remove } = yield* setup; + // The admin invites someone and leaves; the owner invites them back as a member. + const email = yield* emailOf(actors.admin); + const departedEmail = "invited-by-departed@example.test"; + const departed = yield* invite(actors.admin, departedEmail, "admin"); + yield* remove(email); + const readmission = yield* invite(actors.owner, email, "member"); + expect(yield* status(departed)).toBe("canceled"); + expect(yield* status(readmission)).toBe("pending"); + // A wrong password for the existing account is refused, and guesses are limited. + yield* spendRegistrationLimit( + { invitation: readmission, email, password: "attacker-chosen-password" }, + 403, ); - // A failed password check rolls back consumption; the original password and role survive. + // Refused guesses roll back, so the invitation is still pending. + expect(yield* status(readmission)).toBe("pending"); + // The window is fresh: these three registrations fit in it. + expect((yield* register(yield* api.session(), departed, departedEmail)).status).toBe(403); + const recipient = yield* api.session(); + expect((yield* register(recipient, readmission, email)).status).toBe(200); + expect(yield* role(recipient)).toBe("member"); + expect((yield* register(yield* api.session(), readmission, email)).status).toBe(403); + // The guesses never replaced the account's password. expect( (yield* api.request(yield* api.session(), "POST", "/api/auth/sign-in/email", { email, diff --git a/e2e/tests/invitation-security.spec.ts b/e2e/tests/invitation-security.spec.ts index 6adf46a598..dfc78bab59 100644 --- a/e2e/tests/invitation-security.spec.ts +++ b/e2e/tests/invitation-security.spec.ts @@ -3,8 +3,9 @@ import { expect, layer } from "@effect/vitest"; import { Effect, Schema } from "effect"; import { Api, body } from "../support/api.ts"; import { Browser } from "../support/browser.ts"; -import { Actors } from "../support/actors.ts"; +import { Actors, password } from "../support/actors.ts"; import { HostedLive, withHostedCase } from "../support/case.ts"; +import { Target } from "../support/platform.ts"; import { freeSeat } from "../support/seats.ts"; import { scenarios } from "../test-plan.ts"; @@ -127,6 +128,16 @@ layer(HostedLive, { excludeTestServices: true })("Invitation privacy", (it) => { invitationId: invitation.id, })).status, ).toBe(200); + // A cancelled link no longer registers an account on self-host. + if ((yield* Target).metadata.target !== "cloud") + expect( + (yield* api.request(yield* api.session(), "POST", "/api/auth/self-host/register", { + invitation: invitation.id, + email: invitation.email, + name: "Invited user", + password, + })).status, + ).toBe(403); const administrator = yield* body( Schema.Struct({ userId: Schema.String }), @@ -144,6 +155,16 @@ layer(HostedLive, { excludeTestServices: true })("Invitation privacy", (it) => { ); const membership = roster.members.find((member) => member.userId === administrator.userId); expect(membership).toBeDefined(); + // The admin invites the member back as an administrator, then loses the admin role. + const departed = yield* freeSeat; + const sent = yield* api.request( + actors.admin, + "POST", + "/api/auth/organization/invite-member", + { organizationId, email: departed.email, role: "admin" }, + ); + expect(sent.status).toBe(200); + const pending = yield* body(Invitation, sent); expect( (yield* api.request(actors.owner, "POST", "/api/auth/organization/update-member-role", { organizationId, @@ -154,6 +175,21 @@ layer(HostedLive, { excludeTestServices: true })("Invitation privacy", (it) => { // Existing sessions lose invitation access as soon as membership changes. for (const path of [list, full]) expect((yield* api.request(actors.admin, "GET", path)).status).toBe(403); + // The invitations the admin sent are cancelled with the role, and cannot be accepted. + const remaining = yield* body( + Schema.Array(Schema.Struct({ id: Schema.String, status: Schema.String })), + yield* api.request(actors.owner, "GET", list), + ); + expect(remaining.find((value) => value.id === pending.id)?.status).toBe("canceled"); + expect( + (yield* api.request(actors.member, "POST", "/api/auth/organization/accept-invitation", { + invitationId: pending.id, + })).status, + ).toBe(400); + expect( + (yield* api.request(actors.member, "GET", `/api/organizations/${organizationId}/access`)) + .status, + ).toBe(403); }), ), ); diff --git a/patches/better-auth-cancel-invitation.md b/patches/better-auth-cancel-invitation.md new file mode 100644 index 0000000000..ddc1b220d6 --- /dev/null +++ b/patches/better-auth-cancel-invitation.md @@ -0,0 +1,22 @@ +# Better Auth organization: cancel only pending invitations + +`better-auth@1.7.20.patch` changes `cancelInvitation` in +`dist/plugins/organization/routes/crud-invites.mjs`. + +Better Auth wrote `canceled` over any invitation, including one already +accepted, rejected or canceled, and answered 200. An administrator who +cancelled an invitation the recipient had just accepted was told it was +cancelled while the recipient stayed a member. + +With the patch, cancelling passes `fromStatus: "pending"` to +`updateInvitation`, as acceptance already does, so the status changes in the +same statement that checks it. An invitation that was accepted is answered +with `INVITATION_ALREADY_ACCEPTED` (400), so the dashboard can say the person +has joined; any other invitation that is no longer pending is answered with +`INVITATION_NOT_FOUND` (400), as acceptance and rejection answer it. +`invitation-reaccept.spec.ts` cancels an accepted invitation and checks the +refusal and the membership, and `invitation-dialog.spec.ts` checks what the +revoke dialog then says. + +Drop this hunk when Executor upgrades to a Better Auth release that checks the +status when cancelling. diff --git a/patches/better-auth@1.7.20.patch b/patches/better-auth@1.7.20.patch index bfe78af5fb..d2c143ee56 100644 --- a/patches/better-auth@1.7.20.patch +++ b/patches/better-auth@1.7.20.patch @@ -106,3 +106,26 @@ index 8109668..30839db 100644 /** * Require discovery to provide the issuer and JWKS metadata needed to verify * ID tokens before this provider is registered. +diff --git a/dist/plugins/organization/routes/crud-invites.mjs b/dist/plugins/organization/routes/crud-invites.mjs +index 0380d6e..0561765 100644 +--- a/dist/plugins/organization/routes/crud-invites.mjs ++++ b/dist/plugins/organization/routes/crud-invites.mjs +@@ -452,8 +452,17 @@ const cancelInvitation = (options) => createAuthEndpoint("/organization/cancel-i + }); + const canceledI = await adapter.updateInvitation({ + invitationId: ctx.body.invitationId, +- status: "canceled" ++ status: "canceled", ++ fromStatus: "pending" + }); ++ if (!canceledI) { ++ const current = await adapter.findInvitationById(ctx.body.invitationId); ++ if (current?.status === "accepted") throw APIError.from("BAD_REQUEST", { ++ code: "INVITATION_ALREADY_ACCEPTED", ++ message: "This invitation has already been accepted" ++ }); ++ throw APIError.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.INVITATION_NOT_FOUND); ++ } + if (options?.organizationHooks?.afterCancelInvitation) await options?.organizationHooks.afterCancelInvitation({ + invitation: canceledI || invitation, + cancelledBy: session.user, From 68f18b352f365ed015e23a7671e18d440817de9c Mon Sep 17 00:00:00 2001 From: Rhys Sullivan <39114868+RhysSullivan@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:13:32 +0000 Subject: [PATCH 02/68] Export 81e80bb6 --- .changeset/self-host-mcp-clients.md | 15 + .changeset/self-host-runtime-root.md | 7 + apps/docs/content/run/self-host.mdx | 18 ++ apps/hosted/self-host/Dockerfile | 6 +- apps/hosted/self-host/compose.yaml | 4 + apps/hosted/self-host/src/contracts/config.ts | 45 +++ apps/hosted/self-host/src/mcp.ts | 169 ++++++++-- apps/hosted/self-host/src/worker.ts | 7 +- e2e/docker-release.config.ts | 1 + e2e/test-plan.ts | 47 +++ .../docker-release-runtime-files.spec.ts | 49 +++ e2e/tests/mcp-client-bound.spec.ts | 289 ++++++++++++++++++ 12 files changed, 629 insertions(+), 28 deletions(-) create mode 100644 .changeset/self-host-mcp-clients.md create mode 100644 .changeset/self-host-runtime-root.md create mode 100644 e2e/tests/docker-release-runtime-files.spec.ts create mode 100644 e2e/tests/mcp-client-bound.spec.ts diff --git a/.changeset/self-host-mcp-clients.md b/.changeset/self-host-mcp-clients.md new file mode 100644 index 0000000000..5f7b9eb4f9 --- /dev/null +++ b/.changeset/self-host-mcp-clients.md @@ -0,0 +1,15 @@ +--- +"@executor-js/hosted-self-host": patch +--- + +Self-host no longer refuses new MCP clients after 256 API keys or OAuth grants +have been used within half an hour. It keeps up to 512 clients +(`EXECUTOR_MCP_CLIENTS`), and when a new one would pass that it forgets the +least recently used client that has no request in flight and no program waiting +for approval. That client's next request gets `404` and it must initialize a +new session; a client that does not do so on its own needs reconnecting. One member holds at +most 256 of them (`EXECUTOR_MCP_CLIENTS_PER_USER`), so one member's +clients cannot push out everyone else's. When every client that could make room +owns work, a new client gets `503` with `Retry-After: 1`. +A setting that is not a whole number of at least 1 stops the server with an +error naming the setting. diff --git a/.changeset/self-host-runtime-root.md b/.changeset/self-host-runtime-root.md new file mode 100644 index 0000000000..51afe079be --- /dev/null +++ b/.changeset/self-host-runtime-root.md @@ -0,0 +1,7 @@ +--- +"@executor-js/hosted-self-host": patch +--- + +The self-host image's runtime under `/app`, such as `product.mjs`, +`workerd.capnp` and the workerd binary, now belongs to root and is read-only to +the user the server runs as. Only the data directories are that user's. diff --git a/apps/docs/content/run/self-host.mdx b/apps/docs/content/run/self-host.mdx index d41673c568..2af6681586 100644 --- a/apps/docs/content/run/self-host.mdx +++ b/apps/docs/content/run/self-host.mdx @@ -30,6 +30,8 @@ These settings override the defaults: | `EXECUTOR_TRUSTED_PROXIES` | no | Comma-separated addresses of your reverse proxies, so rate limits count each client behind them. List only proxies. See below. | | `EXECUTOR_APP_WORKERS` | no | Most app and data Workers kept loaded at once. The default is `64`. See below. | | `EXECUTOR_APP_WORKER_IDLE_SECONDS` | no | Unload an app or data Worker not called for this long; `0` keeps idle Workers loaded up to the limit. The default is `300`. See below. | +| `EXECUTOR_MCP_CLIENTS` | no | Most MCP clients the server keeps state for at once; each API key or OAuth grant in use is one. The default is `512`. See [Connect an agent](#connect-an-agent). | +| `EXECUTOR_MCP_CLIENTS_PER_USER` | no | Most of those one member may hold. The default is `256`. | | `EXECUTOR_OAUTH_CLIENT_METADATA_URL` | no | Identify Executor to OAuth services by a client metadata document instead of registering a client. Off by default. See below. | | `EXECUTOR_CATALOG_URL` | no | `index.json` of the official app feed that onboarding and **Add app** list. The default is `https://catalog.executor.sh/index.json`; `off` lists only the built-in Executor app, for an instance without outbound internet access. | | `EXECUTOR_REGISTRY_URL` | no | Origin of the public app registry. The default is `https://api.executor.sh`. | @@ -331,6 +333,22 @@ command. The MCP endpoint is `/mcp`. Sign-in happens in the browser, the same way as hosted. See [Add an MCP client](/mcp-clients). +The server keeps each MCP client's state in memory, one client for each API key +or OAuth grant in use. A connected client holds about 200 KB, so the default +of 512 clients takes about 120 MB. It keeps at most `EXECUTOR_MCP_CLIENTS` of +them. When a new client would pass that, the server forgets the one used least +recently. The forgotten client's next request is answered `404` (session not +found), and the client must initialize a new session, as after a server +restart. Some clients do not do that on their own and keep getting `404`, so +their tool calls fail until you reconnect them, for example by restarting the +agent or reconnecting its MCP server. A member who already holds +`EXECUTOR_MCP_CLIENTS_PER_USER` clients loses their own least recently used one instead, so one member cannot +push everyone else's out. A client with a request in flight or a program +waiting for approval is never forgotten. When no client can be, a new one gets +`503` with `Retry-After: 1` until one finishes. A client unused for 30 minutes +is forgotten anyway. Raise the limit with care: with about 800 clients kept, +tool calls took several times as long on a 16-core machine. + ## Move from a local Executor A self-hosted server starts empty. Nothing is copied from the local Executor diff --git a/apps/hosted/self-host/Dockerfile b/apps/hosted/self-host/Dockerfile index b7c790203a..19f2a15438 100644 --- a/apps/hosted/self-host/Dockerfile +++ b/apps/hosted/self-host/Dockerfile @@ -20,6 +20,8 @@ RUN bun install --frozen-lockfile --filter @executor-js/hosted-self-host --filte RUN bun run --cwd apps/hosted/self-host/web build RUN bun run --cwd packages/apps build RUN bun run --cwd apps/hosted/self-host package:runtime +# Readable by everyone and writable by none but root, whatever modes the packages it copies carry. +RUN chmod -R u=rwX,go=rX apps/hosted/self-host/dist/workerd # The telemetry collector, built from its crate by the same script and toolchain as every release # target (packages/telemetry/collector/README.md, Release builds). Only the crate, its toolchain @@ -78,7 +80,9 @@ ENV EXECUTOR_BUILD_VERSION=$EXECUTOR_BUILD_VERSION EXECUTOR_POSTHOG_PUBLIC_KEY=$ COPY --from=system /runtime/ / ENV SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt NODE_ENV=production EXECUTOR_ENVIRONMENT=self-host HOST=0.0.0.0 PORT=4400 EXECUTOR_DATA_DIR=/app/data EXECUTOR_MOTEL_DATA_DIR=/app/motel-data WORKDIR /app -COPY --from=build --chown=1000:1000 /build/apps/hosted/self-host/dist/workerd ./ +# The runtime belongs to root: the host reads it again at every start, so the user that runs app +# code must not be able to change it. Only the data directories are that user's (package-system.sh). +COPY --from=build /build/apps/hosted/self-host/dist/workerd ./ COPY --from=native /executor-host /usr/local/bin/executor-host COPY --from=native /usr/local/go/LICENSE /usr/share/doc/golang/LICENSE COPY --from=native /licenses/ /usr/share/doc/executor-host/ diff --git a/apps/hosted/self-host/compose.yaml b/apps/hosted/self-host/compose.yaml index 1f93892e1c..53f4a0a7aa 100644 --- a/apps/hosted/self-host/compose.yaml +++ b/apps/hosted/self-host/compose.yaml @@ -32,6 +32,10 @@ services: EXECUTOR_APP_WORKERS: # Seconds a Worker stays loaded without a call (default 300); 0 keeps idle ones until the limit. EXECUTOR_APP_WORKER_IDLE_SECONDS: + # Most MCP clients (API keys or OAuth grants in use) kept at once (default 512), and most + # per member (default 256). Past either, the least recently used idle one is forgotten. + EXECUTOR_MCP_CLIENTS: + EXECUTOR_MCP_CLIENTS_PER_USER: EXECUTOR_OAUTH_CALLBACK_URL: # Off by default. /oauth/client-metadata.json serves a client metadata # document there, which authorization servers must be able to fetch over public HTTPS. diff --git a/apps/hosted/self-host/src/contracts/config.ts b/apps/hosted/self-host/src/contracts/config.ts index 155ccb8cb8..e3e871502a 100644 --- a/apps/hosted/self-host/src/contracts/config.ts +++ b/apps/hosted/self-host/src/contracts/config.ts @@ -30,3 +30,48 @@ export const allowPrivateAppFetch = Config.Boolean("EXECUTOR_APPS_ALLOW_PRIVATE_ /** A registry mirror for app builds. Apps resolve their declared packages from the public npm registry by default. */ export const npmRegistry = Config.String("EXECUTOR_NPM_REGISTRY").pipe(Config.option); + +/** An operator setting the server cannot start with. The message names the setting, never its value. */ +export class SelfHostSettingInvalid extends Schema.TaggedError()( + "SelfHostSettingInvalid", + { message: Schema.String }, +) {} + +/** A whole number of at least 1, when set; otherwise `fallback`. */ +const clientCount = (name: string, fallback: number) => + Effect.flatMap(Config.String(name).pipe(Config.option), (value) => + Option.isNone(value) + ? Effect.succeed(fallback) + : /^[1-9][0-9]*$/.test(value.value.trim()) + ? Effect.succeed(Number(value.value.trim())) + : Effect.fail( + new SelfHostSettingInvalid({ + message: `${name} must be a whole number of at least 1.`, + }), + ), + ); + +/** + * The MCP clients the server keeps protocol state for, one per API key or OAuth grant a member uses + * (`mcpSessionKey`), and how many of them one member may hold. Past either, the least recently used + * client without a request in flight or a paused program is forgotten, and its next request must + * initialize again. Read at startup, so a count that is not a whole number of at least 1 stops the + * server with an error naming the setting. + */ +export interface McpClientLimits { + readonly total: number; + readonly perUser: number; +} +/** + * Measured in the image's product isolate: a client that has initialized holds about 170 to 240 KB + * of heap, so 512 hold about 120 MB. Tool calls stayed under about 70 ms with up to about 660 + * clients kept and took 250 to 550 ms with 800. A member may hold half the list. + */ +export const defaultMcpClientLimits: McpClientLimits = { total: 512, perUser: 256 }; +export const mcpClientLimits = Effect.gen(function* () { + const limits: McpClientLimits = { + total: yield* clientCount("EXECUTOR_MCP_CLIENTS", defaultMcpClientLimits.total), + perUser: yield* clientCount("EXECUTOR_MCP_CLIENTS_PER_USER", defaultMcpClientLimits.perUser), + }; + return limits; +}); diff --git a/apps/hosted/self-host/src/mcp.ts b/apps/hosted/self-host/src/mcp.ts index 1bf821ab45..4cb942a5ec 100644 --- a/apps/hosted/self-host/src/mcp.ts +++ b/apps/hosted/self-host/src/mcp.ts @@ -13,16 +13,35 @@ import { } from "@executor-js/hosted-server"; import { McpLimits, defaultMcpLimits } from "@executor-js/mcp"; import { PgliteClient } from "@effect/sql-pglite"; -import { Config, Effect, RcMap, Schema } from "effect"; +import { + Clock, + Config, + Context, + Deferred, + Duration, + Effect, + Exit, + Fiber, + Schedule, + Schema, + Scope, +} from "effect"; +import { McpSchema } from "effect/ai"; import { HttpServerResponse } from "effect/http"; +import { mcpClientLimits } from "./contracts/config.ts"; /** - * Protocol sessions a handler keeps in each elicitation mode, by last use, forgetting only sessions - * that own no work. A handler stays while its caller keeps calling, and the transport has no session - * DELETE, so each client that opened a session for one call, or left without ending its session, - * kept about 0.7 KB until restart. + * Protocol sessions one client's handler keeps in each elicitation mode, by last use, forgetting + * only sessions that own no work. A handler stays while its caller keeps calling, and the transport + * has no session DELETE, so each client that opened a session for one call, or left without ending + * its session, kept about 0.7 KB until restart. */ const maxSessions = 256; +/** A client with no request in flight and no paused program is forgotten after this long. */ +const idleMillis = Duration.toMillis(Duration.minutes(30)); + +/** Every client that could make room owns work: a request in flight or a paused program. */ +class McpClientsFull extends Schema.TaggedError()("McpClientsFull", {}) {} /** Own protocol sessions in the server scope; the returned handler receives SDK/auth per request. */ export const selfHostMcp = Effect.gen(function* () { @@ -33,22 +52,110 @@ export const selfHostMcp = Effect.gen(function* () { Config.withDefault(defaultMcpLimits.timeoutMs), ), }); - const sessions = yield* RcMap.make({ - // Each session keeps what its callers' last tool calls read (CallStateCache). - lookup: (_key: string) => - Effect.map( - makeHostedMcp(undefined, limits, undefined, undefined, maxSessions), - (handler) => ({ - ...handler, - calls: new Map(), - }), - ), - idleTimeToLive: "30 minutes", - capacity: 256, - }); + const bound = yield* mcpClientLimits; + // Each client keeps what its callers' last tool calls read (CallStateCache). + const build = Effect.map( + makeHostedMcp(undefined, limits, undefined, undefined, maxSessions), + (handler) => ({ ...handler, calls: new Map() }), + ); + type Handler = Effect.Success; + // A handler outlives the request that opened it, so it is built in the server's context. + const context = yield* Effect.context, Scope.Scope>>(); + const server = yield* Effect.scope; + const clock = yield* Clock.Clock; + + interface Client { + readonly user: string; + readonly scope: Scope.Closeable; + readonly ready: Deferred.Deferred; + handler: Handler | undefined; + /** Requests in flight, each until its response has been sent, its event stream included. */ + requests: number; + idleSince: number; + } + /** One client per `mcpSessionKey`, least recently used first. */ + const clients = new Map(); + const ownsWork = (client: Client) => + client.requests > 0 || client.handler === undefined || client.handler.programs() > 0; + const forget = (key: string, client: Client) => { + clients.delete(key); + Scope.close(client.scope, Exit.void).pipe(Effect.runForkWith(context), Fiber.runIn(server)); + }; + /** Forget the least recently used client, of `user` when named, that owns no work. */ + const forgetIdle = (user?: string) => { + for (const [key, client] of clients) { + if ((user === undefined || client.user === user) && !ownsWork(client)) { + forget(key, client); + return true; + } + } + return false; + }; + /** Room for one more client of `user`, in the same synchronous step that will take it. */ + const makeRoom = (user: string) => { + let held = 0; + for (const client of clients.values()) if (client.user === user) held++; + if (held >= bound.perUser) return forgetIdle(user); + return clients.size < bound.total || forgetIdle(); + }; + const open = (key: string, user: string) => { + const client: Client = { + user, + scope: Scope.forkUnsafe(server), + ready: Deferred.makeUnsafe(), + handler: undefined, + requests: 0, + idleSince: clock.currentTimeMillisUnsafe(), + }; + clients.set(key, client); + build + .pipe( + Effect.runForkWith(Context.add(context, Scope.Scope, client.scope)), + Fiber.runIn(client.scope), + ) + .addObserver((exit) => { + if (Exit.isSuccess(exit)) client.handler = exit.value; + else if (clients.get(key) === client) forget(key, client); + Deferred.doneUnsafe(client.ready, exit); + }); + return client; + }; + /** The handler of `user`'s client `key`, held by the request's scope and moved to most recent. */ + const handlerFor = (key: string, user: string) => + Effect.uninterruptibleMask((restore) => + Effect.suspend(() => { + let client = clients.get(key); + if (client === undefined) { + if (!makeRoom(user)) return Effect.fail(new McpClientsFull()); + client = open(key, user); + } else { + clients.delete(key); + clients.set(key, client); + } + const held = client; + held.requests++; + return Effect.addFinalizer(() => + Effect.sync(() => { + held.requests--; + held.idleSince = clock.currentTimeMillisUnsafe(); + // Used until its response ended, so a long event stream does not leave it first in line. + if (clients.get(key) === held) { + clients.delete(key); + clients.set(key, held); + } + }), + ).pipe(Effect.andThen(restore(Deferred.await(held.ready)))); + }), + ); + yield* Effect.sync(() => { + const now = clock.currentTimeMillisUnsafe(); + for (const [key, client] of clients) + if (!ownsWork(client) && now - client.idleSince >= idleMillis) forget(key, client); + }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.forkScoped); + const http = authenticatedMcp((access, address) => Effect.gen(function* () { - const handler = yield* RcMap.get(sessions, mcpSessionKey(access)); + const handler = yield* handlerFor(mcpSessionKey(access), access.userId); // PGlite runs in-process, so reads issued together cost no extra connection. A tool call's // statements run together under the client's lock, its reads in one snapshot, as in Cloud. // Not read-only: a statement another caller handed to PGlite just before the lock can still @@ -61,22 +168,32 @@ export const selfHostMcp = Effect.gen(function* () { Effect.provideService(CallStateCache, handler.calls), ); }).pipe( - Effect.catchTag("ExceededCapacityError", () => + // A client that owns work is never forgotten to admit another, so this one waits its turn. + Effect.catchTag("McpClientsFull", () => Effect.succeed( - // An active request is never evicted to admit a new session. - // Native clients can retry after another scope expires. - HttpServerResponse.empty({ status: 503 }), + HttpServerResponse.jsonUnsafe( + { + jsonrpc: "2.0", + id: null, + error: { + code: McpSchema.RESOURCE_EXHAUSTED_ERROR_CODE, + message: + "Too many MCP clients in use: every client this server keeps for you, or for everyone, is running a request or holds a paused program. Retry when one of them finishes.", + }, + }, + { status: 503, headers: { "retry-after": "1" } }, + ), ), ), ), ); const approvals = browserMcpRequest((access, address) => Effect.gen(function* () { - const host = yield* RcMap.get(sessions, mcpSessionKey(access)); + const host = yield* handlerFor(mcpSessionKey(access), access.userId); return yield* hostedMcpApproval(host.approvals, access, address); }).pipe( - Effect.catchTag("ExceededCapacityError", () => - Effect.succeed(HttpServerResponse.empty({ status: 503 })), + Effect.catchTag("McpClientsFull", () => + Effect.succeed(HttpServerResponse.empty({ status: 503, headers: { "retry-after": "1" } })), ), ), ); diff --git a/apps/hosted/self-host/src/worker.ts b/apps/hosted/self-host/src/worker.ts index 6088b43b5b..85942f174e 100644 --- a/apps/hosted/self-host/src/worker.ts +++ b/apps/hosted/self-host/src/worker.ts @@ -36,6 +36,7 @@ import { SelfHostWorkflowRequests, } from "./implementation/executor-services.ts"; import { selfHostRouteMap } from "./implementation/routes.ts"; +import { SelfHostSettingInvalid } from "./contracts/config.ts"; import { bindingBlobStore, bindingDashboard, @@ -256,7 +257,11 @@ export class ExecutorProduct extends DurableObject implements Produ return opened.value; } const squashed = Cause.squash(opened.cause); - if (Schema.is(FirstPartyOAuthClientsInvalid)(squashed)) settings = squashed.message; + if ( + Schema.is(FirstPartyOAuthClientsInvalid)(squashed) || + Schema.is(SelfHostSettingInvalid)(squashed) + ) + settings = squashed.message; failure = opened.cause; } catch (error) { failure = error; diff --git a/e2e/docker-release.config.ts b/e2e/docker-release.config.ts index 658e4c51a7..178f42fffd 100644 --- a/e2e/docker-release.config.ts +++ b/e2e/docker-release.config.ts @@ -39,6 +39,7 @@ export default defineConfig({ "e2e/tests/docker-release-trusted-proxies.spec.ts", "e2e/tests/docker-release-live-query.spec.ts", "e2e/tests/docker-release-mcp-session-release.spec.ts", + "e2e/tests/docker-release-runtime-files.spec.ts", "e2e/tests/docker-release-workflow-memory.spec.ts", "e2e/tests/docker-release-workflow-idle-window.spec.ts", "e2e/tests/docker-release-workflow-restart.spec.ts", diff --git a/e2e/test-plan.ts b/e2e/test-plan.ts index 83e0b1517e..4186a8014c 100644 --- a/e2e/test-plan.ts +++ b/e2e/test-plan.ts @@ -90,6 +90,11 @@ export const appWorkerBudgetLimit = 2; * stalled app reached during the program is told apart from one discovery gave up on. */ export const lazyStallTimeoutMs = 15_000; +/** The MCP client bound the client bound scenarios run with: three clients, two per member. */ +const mcpClientBoundEnvironment = { + EXECUTOR_MCP_CLIENTS: "3", + EXECUTOR_MCP_CLIENTS_PER_USER: "2", +}; /** * Seconds after which the aged search rows scenarios' server renews the rows a search serves * (`EXECUTOR_TOOL_LISTING_RENEW_SECONDS`), in place of the default day: MCP readers never renew @@ -8321,6 +8326,48 @@ export const scenarios = plan({ local: na("Local keeps one protocol server for the process and sets no session bound."), }, }, + mcpClientsIdleForgotten: { + fixtures: "actors", + file: "mcp-client-bound.spec.ts", + title: + "Self-host MCP admits a new client past its client bound by forgetting the least recently used idle one, whose session is told to initialize again", + serverEnvironment: mcpClientBoundEnvironment, + targets: { + "self-host": scheduled, + cloud: na( + "Each Cloud MCP client is its own session object; there is no shared list to bound.", + ), + local: na("Local keeps one protocol server for the process and sets no client bound."), + }, + }, + mcpClientsPerUser: { + fixtures: "actors", + file: "mcp-client-bound.spec.ts", + title: + "Self-host MCP admits a member's client past their share by forgetting that member's own oldest idle client, not another member's", + serverEnvironment: mcpClientBoundEnvironment, + targets: { + "self-host": scheduled, + cloud: na( + "Each Cloud MCP client is its own session object; there is no shared list to bound.", + ), + local: na("Local keeps one protocol server for the process and sets no client bound."), + }, + }, + mcpClientsOwningWork: { + fixtures: "actors", + file: "mcp-client-bound.spec.ts", + title: + "Self-host MCP never forgets a client whose approval prompt waits or whose program is paused, and refuses a new client with 503 when none can be", + serverEnvironment: mcpClientBoundEnvironment, + targets: { + "self-host": scheduled, + cloud: na( + "Each Cloud MCP client is its own session object; there is no shared list to bound.", + ), + local: na("Local keeps one protocol server for the process and sets no client bound."), + }, + }, mcpSessionBound: { fixtures: "actors", file: "mcp-protocol-versions.spec.ts", diff --git a/e2e/tests/docker-release-runtime-files.spec.ts b/e2e/tests/docker-release-runtime-files.spec.ts new file mode 100644 index 0000000000..70e2703901 --- /dev/null +++ b/e2e/tests/docker-release-runtime-files.spec.ts @@ -0,0 +1,49 @@ +/** + * The image's runtime belongs to root. The host reads `/app/workerd.capnp`, `/app/product.mjs` and + * the workerd binary again at every start, so the user that runs app code must not be able to change + * them, or anything else under `/app` and the host's own executables. Only the product and telemetry + * data directories are that user's. Before, the runtime was copied owned by that user. + */ +import { expect, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Effect } from "effect"; +import { releasedServer } from "../support/docker-release-server.ts"; + +/** + * Every path under /app outside the data directories, /app itself included, and the host's + * executables that the running user may write, by access(2) and by opening the files the host reads + * for appending, which writes nothing. The image has no `find`, so dash walks the tree. + */ +const writableRuntime = ` +walk() { + for f in "$1"/* "$1"/.[!.]* "$1"/..?*; do + [ -e "$f" ] || [ -L "$f" ] || continue + case "$f" in /app/data|/app/motel-data) continue ;; esac + [ -w "$f" ] && echo "$f" + [ -d "$f" ] && [ ! -L "$f" ] && walk "$f" + done +} +for f in /app /usr/local/bin /usr/local/bin/executor-host /usr/local/bin/executor-entrypoint; do + [ -w "$f" ] && echo "$f" +done +walk /app +for f in /app/workerd.capnp /app/product.mjs /app/workerd; do + (: >> "$f") 2>/dev/null && echo "opened $f" +done +for f in /app/data /app/motel-data; do + [ -w "$f" ] && echo "data $f" +done +`; + +it.live("released image's runtime files cannot be changed by the user that runs app code", () => + Effect.scoped( + Effect.gen(function* () { + const server = yield* releasedServer; + const writable = (yield* server.exec(writableRuntime)).split("\n").filter(Boolean); + expect(writable, "paths the running user may write").toEqual([ + "data /app/data", + "data /app/motel-data", + ]); + }), + ).pipe(Effect.provide(NodeServices.layer)), +); diff --git a/e2e/tests/mcp-client-bound.spec.ts b/e2e/tests/mcp-client-bound.spec.ts new file mode 100644 index 0000000000..89064d0f3e --- /dev/null +++ b/e2e/tests/mcp-client-bound.spec.ts @@ -0,0 +1,289 @@ +/** + * Self-host keeps protocol state for a bounded number of MCP clients, one per API key or OAuth grant + * (`EXECUTOR_MCP_CLIENTS`), and for at most `EXECUTOR_MCP_CLIENTS_PER_USER` of one member's. These + * scenarios run with a bound of three clients and two per member. Past the bound the least recently + * used client that owns no work is forgotten to admit the new one, and the forgotten client's + * session is told to initialize again. A client with a request in flight, such as a call whose + * approval prompt waits for its client, or with a paused program, is never forgotten; when no + * client may be, the new one is refused with `503` and `Retry-After: 1`. Before, a full list + * refused every new client while its 30-minute idle entries stayed. + */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Exit, Redacted, Schema } from "effect"; +import { HttpClient, HttpClientRequest } from "effect/http"; +import { scenarios } from "../test-plan.ts"; +import { Api, body } from "../support/api.ts"; +import { Actors } from "../support/actors.ts"; +import { Evidence } from "../support/evidence.ts"; +import { HostedLive, withHostedCase } from "../support/case.ts"; +import { McpClient } from "../support/mcp-client.ts"; +import { Target } from "../support/platform.ts"; +import { App } from "../support/contracts.ts"; +import { appsManifest } from "../support/apps-release.ts"; + +type Role = "owner" | "admin" | "member"; +interface Key { + readonly key: Redacted.Redacted; + readonly credentials: Readonly>; +} + +const Reply = Schema.Struct({ + error: Schema.optional(Schema.Struct({ code: Schema.Number, message: Schema.String })), +}); +const Pending = Schema.Struct({ + status: Schema.Literal("approval-required"), + requestId: Schema.String, +}); +const Completed = Schema.Struct({ + status: Schema.Literal("completed"), + execution: Schema.Struct({ ok: Schema.Literal(true), value: Schema.Unknown }), +}); + +/** An API key of `role`, a client of its own, removed when the scenario ends. */ +const apiKey = (role: Role, name: string) => + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors; + const created = yield* body( + Schema.Struct({ id: Schema.String, key: Schema.RedactedFromValue(Schema.String) }), + yield* api.request(actors[role], "POST", "/api/auth/api-key/create", { name }), + ); + yield* Effect.addFinalizer(() => + api + .request(actors[role], "POST", "/api/auth/api-key/delete", { keyId: created.id }) + .pipe(Effect.orDie), + ); + const key: Key = { + key: created.key, + credentials: { + authorization: `Bearer ${Redacted.value(created.key)}`, + "x-executor-organization": actors.organization.id, + }, + }; + return key; + }); + +/** One JSON-RPC POST to /mcp: its status, `Retry-After`, session and reply. */ +const post = (key: Key, message: object, session?: string) => + Effect.gen(function* () { + const target = yield* Target, + http = yield* HttpClient.HttpClient; + const request = yield* HttpClientRequest.post(new URL("/mcp", target.metadata.origin), { + headers: { + ...key.credentials, + accept: "application/json, text/event-stream", + ...(session === undefined + ? {} + : { "mcp-session-id": session, "mcp-protocol-version": "2025-11-25" }), + }, + }).pipe(HttpClientRequest.bodyJson({ jsonrpc: "2.0", ...message })); + const response = yield* http.execute(request).pipe(Effect.timeout("30 seconds")); + const text = yield* response.text; + return { + status: response.status, + retryAfter: response.headers["retry-after"], + session: response.headers["mcp-session-id"], + text, + }; + }).pipe(Effect.scoped, Effect.provideService(HttpClient.TracerPropagationEnabled, false)); + +const initialize = (key: Key) => + post(key, { + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-11-25", + capabilities: {}, + clientInfo: { name: "executor-e2e-client-bound", version: "1" }, + }, + }); +/** A session of the key's client, opened and confirmed. */ +const open = (key: Key) => + Effect.gen(function* () { + const opened = yield* initialize(key); + expect(opened.status, opened.text).toBe(200); + const session = yield* Schema.decodeUnknownEffect(Schema.NonEmptyString)(opened.session); + expect((yield* post(key, { method: "notifications/initialized" }, session)).status).toBe(202); + return session; + }); +/** The status a ping in the session answers: 200 while its client is kept, 404 once forgotten. */ +const ping = (key: Key, session: string) => + post(key, { id: 2, method: "ping" }, session).pipe(Effect.map(({ status }) => status)); + +const checkIdleForgotten = Effect.gen(function* () { + const evidence = yield* Evidence; + const owner = yield* apiKey("owner", "Client bound owner"); + const admin = yield* apiKey("admin", "Client bound admin"); + const member = yield* apiKey("member", "Client bound member"); + const later = yield* apiKey("member", "Client bound member, later"); + const owners = yield* open(owner); + const admins = yield* open(admin); + const members = yield* open(member); + // The owner's client is used again, so the admin's is now the least recently used. + expect(yield* ping(owner, owners)).toBe(200); + yield* evidence.step( + "With three idle clients kept, a fourth is admitted", + Effect.gen(function* () { + const latest = yield* open(later); + expect(yield* ping(later, latest), "the new client").toBe(200); + }), + ); + yield* evidence.step( + "Only the least recently used client was forgotten, and its session is told to initialize again", + Effect.gen(function* () { + expect(yield* ping(owner, owners), "the owner's client, used since").toBe(200); + expect(yield* ping(member, members), "the member's first client").toBe(200); + expect(yield* ping(admin, admins), "the admin's client, least recently used").toBe(404); + const again = yield* open(admin); + expect(yield* ping(admin, again)).toBe(200); + }), + ); +}); + +const checkPerUser = Effect.gen(function* () { + const evidence = yield* Evidence; + const owner = yield* apiKey("owner", "Client share owner"); + const members = yield* Effect.forEach([1, 2, 3], (n) => apiKey("member", `Client share ${n}`)); + const owners = yield* open(owner); + const first = yield* open(members[0]!); + const second = yield* open(members[1]!); + yield* evidence.step( + "A member's third client is admitted by forgetting that member's own oldest, not the oldest overall", + Effect.gen(function* () { + const third = yield* open(members[2]!); + expect(yield* ping(members[2]!, third)).toBe(200); + expect(yield* ping(members[1]!, second)).toBe(200); + expect(yield* ping(owner, owners), "the owner's client, the oldest of all").toBe(200); + expect(yield* ping(members[0]!, first), "the member's own oldest client").toBe(404); + }), + ); +}); + +/** An app whose `approved` tool always asks for approval, removed when the scenario ends. */ +const deployApprovalApp = Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors; + const root = `/api/organizations/${actors.organization.id}`; + const deployed = yield* api.request(actors.owner, "POST", `${root}/apps/deploy`, { + name: "Clients owning work", + files: [ + { + path: "index.ts", + content: `import { defineApp, mutation, object, router } from "apps"; +import { always } from "apps/operations/approval"; +export default defineApp({}, { tools: router({ + approved: mutation({ input: object({}), approval: always() }, async () => "approved"), +}) });`, + }, + appsManifest, + ], + }); + expect(deployed.status, JSON.stringify(deployed.body)).toBe(200); + const app = yield* body(App, deployed); + yield* Effect.addFinalizer(() => + api.request(actors.owner, "DELETE", `${root}/apps/${app.id}`).pipe(Effect.orDie), + ); + return app; +}); + +const checkOwningWork = Effect.gen(function* () { + const actors = yield* Actors, + evidence = yield* Evidence, + mcp = yield* McpClient; + const organization = actors.organization.id; + const app = yield* deployApprovalApp; + const approve = `return await tools[${JSON.stringify(app.slug)}].approved({})`; + const prompted = yield* apiKey("owner", "Client with a prompt"); + const paused = yield* apiKey("owner", "Client with a paused program"); + const another = yield* apiKey("owner", "Owner's third client"); + const admins = yield* Effect.forEach([1, 2], (n) => apiKey("admin", `Admin client ${n}`)); + const services = yield* Effect.context(); + const forgotten: Array = []; + let duringPrompt: Exit.Exit = Exit.void; + + const model = yield* mcp.connect(paused.key, "paused-program", { organization, mode: "model" }); + // Runs while the prompted client's call waits for its answer, its event stream open. + const whilePrompted = Effect.gen(function* () { + const pending = yield* model + .use("Start a program that pauses for approval", (client, signal) => + client.callTool({ name: "execute", arguments: { code: approve } }, undefined, { signal }), + ) + .pipe( + Effect.flatMap((result) => Schema.decodeUnknownEffect(Pending)(result.structuredContent)), + ); + yield* evidence.step( + "The owner holds two clients that own work, so a third of theirs is refused", + Effect.gen(function* () { + const refused = yield* initialize(another); + expect(refused.status, refused.text).toBe(503); + expect(refused.retryAfter).toBe("1"); + const reply = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Reply))(refused.text); + expect(reply.error?.code).toBe(-32013); + }), + ); + yield* evidence.step( + "Other members' clients are admitted past the bound without forgetting either", + Effect.gen(function* () { + // The second fills the third place; the next is admitted by forgetting it. + forgotten.push(yield* open(admins[0]!)); + const kept = yield* open(admins[1]!); + expect(yield* ping(admins[1]!, kept)).toBe(200); + }), + ); + yield* evidence.step( + "The paused program resumes through its own client", + Effect.gen(function* () { + const resumed = yield* model.use("Approve the paused program", (client, signal) => + client.callTool( + { + name: "resume", + arguments: { requestId: pending.requestId, response: { action: "accept" } }, + }, + undefined, + { signal }, + ), + ); + const completed = yield* Schema.decodeUnknownEffect(Completed)(resumed.structuredContent); + expect(completed.execution.value).toBe("approved"); + }), + ); + }).pipe(Effect.provideContext(services)); + + const native = yield* mcp.connect(prompted.key, "prompted-call", { + organization, + mode: "native", + // The MCP SDK turns a failed approval hook into a declined prompt, so its failure is kept here. + whileApproving: whilePrompted.pipe( + Effect.exit, + Effect.map((exit) => { + duringPrompt = exit; + }), + ), + }); + const answered = yield* native.use("Call a tool whose approval prompt waits", (client, signal) => + client.callTool({ name: "execute", arguments: { code: approve } }, undefined, { + signal, + timeout: 60_000, + }), + ); + if (Exit.isFailure(duringPrompt)) return yield* Effect.failCause(duringPrompt.cause); + yield* evidence.step( + "The call whose prompt waited completes, and the idle client admitted for it was forgotten", + Effect.gen(function* () { + expect(yield* native.elicitationCount).toBe(1); + const completed = yield* Schema.decodeUnknownEffect(Completed)(answered.structuredContent); + expect(completed.execution.value).toBe("approved"); + expect(yield* ping(admins[0]!, forgotten[0]!)).toBe(404); + }), + ); +}); + +layer(HostedLive, { excludeTestServices: true })("Self-host MCP client bound", (it) => { + it.effect(scenarios.mcpClientsIdleForgotten.title, (context) => + withHostedCase(context, checkIdleForgotten), + ); + it.effect(scenarios.mcpClientsPerUser.title, (context) => withHostedCase(context, checkPerUser)); + it.effect(scenarios.mcpClientsOwningWork.title, (context) => + withHostedCase(context, checkOwningWork.pipe(Effect.provide(McpClient.layer))), + ); +}); From 8e597ad2865cf7fb7d4e815b37f4020c1aee56e9 Mon Sep 17 00:00:00 2001 From: Rhys Sullivan <39114868+RhysSullivan@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:44:53 +0000 Subject: [PATCH 03/68] Export 06d2a833 --- apps/cli/CHANGELOG.md | 4 + apps/cli/package.json | 2 +- .../cloud/src/infrastructure/executor.ts | 13 +- apps/hosted/cloud/src/infrastructure/stage.ts | 25 ++ apps/hosted/cloud/src/main.ts | 3 + .../server/src/implementation/mcp-oauth.ts | 11 +- bun.lock | 2 +- e2e/README.md | 6 +- e2e/ci-selection.ts | 10 +- e2e/run.ts | 5 + e2e/sdk/suite.ts | 26 +- e2e/support/cloud-environment.ts | 9 + e2e/support/oauth-setup-issuer.ts | 41 +- e2e/support/removal-revocation-budget.ts | 7 + e2e/test-plan.ts | 56 ++- e2e/tests/ci-selection.spec.ts | 4 +- e2e/tests/local-oauth-token-limit.spec.ts | 96 +++++ .../organization-removal-revocation.spec.ts | 303 ++++++++++++++ e2e/vitest.config.ts | 9 +- packages/sdk/src/contracts/executor.ts | 15 +- packages/sdk/src/implementation/create.ts | 3 +- packages/sdk/src/implementation/oauth.ts | 44 +- packages/sdk/src/implementation/owners.ts | 376 +++++++++++------- 23 files changed, 894 insertions(+), 176 deletions(-) create mode 100644 e2e/support/removal-revocation-budget.ts create mode 100644 e2e/tests/local-oauth-token-limit.spec.ts create mode 100644 e2e/tests/organization-removal-revocation.spec.ts diff --git a/apps/cli/CHANGELOG.md b/apps/cli/CHANGELOG.md index 7783f070a5..c000f98cb6 100644 --- a/apps/cli/CHANGELOG.md +++ b/apps/cli/CHANGELOG.md @@ -1,5 +1,9 @@ # executor +## 2.0.0-beta.60 + +Beta of the Executor local runtime, CLI, desktop, and self-host Docker image. + ## 2.0.0-beta.59 Beta of the Executor local runtime, CLI, desktop, and self-host Docker image. diff --git a/apps/cli/package.json b/apps/cli/package.json index f5ad0bd42e..3608822085 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -1,6 +1,6 @@ { "name": "executor", - "version": "2.0.0-beta.59", + "version": "2.0.0-beta.60", "private": true, "description": "Run Executor locally and connect your agents to your apps.", "homepage": "https://executor.sh", diff --git a/apps/hosted/cloud/src/infrastructure/executor.ts b/apps/hosted/cloud/src/infrastructure/executor.ts index 4ca61a6fb0..7014479557 100644 --- a/apps/hosted/cloud/src/infrastructure/executor.ts +++ b/apps/hosted/cloud/src/infrastructure/executor.ts @@ -37,7 +37,13 @@ import { InvocationDatabase } from "./invocation-database.ts"; import { backgroundWait, CurrentRequest, ownTelemetryScope } from "./served-request.ts"; import { TelemetryDrainScope, TelemetryWaitReport } from "@executor-js/telemetry"; import { cloudSecrets } from "./secrets.ts"; -import { cloudOrigin, cloudResourceOrigins, productionStage, stageName } from "./stage.ts"; +import { + cloudOrigin, + cloudOwnerRevocationBudget, + cloudResourceOrigins, + productionStage, + stageName, +} from "./stage.ts"; import { cloudEmulators } from "./emulators.ts"; import { missingFirstPartyGitHubClient } from "./first-party-oauth-settings.ts"; import { cloudAccountSignIns } from "../implementation/oauth-proxy-settings.ts"; @@ -113,6 +119,10 @@ export const cloudExecutor = Effect.fn(function* ( // The same tool listing settings as the other hosts; a stage deployed without them keeps the // defaults. Memory limits are not read: every executor shares the isolate's store. const { toolListings } = yield* declarationConfig.pipe(Effect.orDie); + // Only `alchemy dev` binds the switch; see `cloudOwnerRevocationBudget`. + const ownerRevocationBudget = yield* cloudOwnerRevocationBudget( + (yield* Cloudflare.WorkerEnvironment).REMOVAL_REVOCATION_BUDGET_SWITCH === true, + ).pipe(Effect.orDie); const makeRuntime = yield* cloudRuntime(origin, databases); const workflows = yield* cloudWorkflows; const blobs = yield* cloudBlobs; @@ -235,6 +245,7 @@ export const cloudExecutor = Effect.fn(function* ( // A tool listing nobody waits for runs until the event's background work ends, and is // remembered as timed out if it has not finished by then. background, + ...(ownerRevocationBudget === undefined ? {} : { ownerRevocationBudget }), events: { sender: httpEventSender(egress), // The same event's client, which hosted permission checks already share. diff --git a/apps/hosted/cloud/src/infrastructure/stage.ts b/apps/hosted/cloud/src/infrastructure/stage.ts index ecc37014bc..e045a94a7f 100644 --- a/apps/hosted/cloud/src/infrastructure/stage.ts +++ b/apps/hosted/cloud/src/infrastructure/stage.ts @@ -391,6 +391,31 @@ export const authRateLimitSwitchBindings = Effect.gen(function* () { return { AUTH_RATE_LIMIT_SWITCH: (yield* AlchemyContext).dev }; }); +/** + * API Worker props: `REMOVAL_REVOCATION_BUDGET_SWITCH` is true only under `alchemy dev`, as + * `AUTH_RATE_LIMIT_SWITCH` is, so every deployed Worker gets `false`; see + * `cloudOwnerRevocationBudget`. + */ +export const removalRevocationBudgetBindings = Effect.gen(function* () { + return { REMOVAL_REVOCATION_BUDGET_SWITCH: (yield* AlchemyContext).dev }; +}); + +/** + * The time organization removal's purge spends revoking OAuth grants + * (`ExecutorInputs.ownerRevocationBudget`). Only a local Cloud shortens it, to + * `TEST_STAGE_REMOVAL_REVOCATION_BUDGET_MS`, so a scenario can run it out in seconds. + * `localRuntime` is the Worker's `REMOVAL_REVOCATION_BUDGET_SWITCH`; every deployed Worker keeps + * the SDK's default whatever its configuration says. + */ +export const cloudOwnerRevocationBudget = (localRuntime: boolean) => + Effect.gen(function* () { + // Read on every stage, so Alchemy binds it into the local Worker; only a local runtime uses it. + const configured = yield* Config.Number("TEST_STAGE_REMOVAL_REVOCATION_BUDGET_MS").pipe( + Config.option, + ); + return localRuntime ? Option.getOrUndefined(configured) : undefined; + }); + /** * Whether Better Auth's per-address limit applies. Every request a test runner sends comes from * one address, so automated environments may turn it off; no deployed stage outside them can: diff --git a/apps/hosted/cloud/src/main.ts b/apps/hosted/cloud/src/main.ts index 528c03734e..32da868bee 100644 --- a/apps/hosted/cloud/src/main.ts +++ b/apps/hosted/cloud/src/main.ts @@ -134,6 +134,7 @@ import { customDomain, productionApiWorkerName, productionStage, + removalRevocationBudgetBindings, stageName, } from "./infrastructure/stage.ts"; import { roleHostRoutes } from "./infrastructure/role-hosts.ts"; @@ -198,6 +199,8 @@ export default Api.make( ...(yield* removalStallBindings), // Only local e2e Clouds may turn the auth rate limit off; deployed Workers get `false`. ...(yield* authRateLimitSwitchBindings), + // Only local e2e Clouds may shorten removal's revocation budget; deployed Workers get `false`. + ...(yield* removalRevocationBudgetBindings), // A deployed stage identifies Executor to authorization servers by its own document. ...(origin === undefined ? {} : yield* clientMetadataBinding.pipe(Effect.orDie)), // Every deployed stage lists production's official app feed. diff --git a/apps/local/server/src/implementation/mcp-oauth.ts b/apps/local/server/src/implementation/mcp-oauth.ts index 7ba993876d..7ecd7d3f24 100644 --- a/apps/local/server/src/implementation/mcp-oauth.ts +++ b/apps/local/server/src/implementation/mcp-oauth.ts @@ -117,7 +117,16 @@ export const makeLocalMcpOAuth = ( cookiePrefix: "executor-local-oauth", ipAddress: { ipAddressHeaders: ["x-executor-client-ip"] }, }, - rateLimit: { enabled: true, storage: "database" as const }, + rateLimit: { + enabled: true, + storage: "database" as const, + // The limiter counts each address and path, and every caller of this loopback server has + // the same address, so a per-address token limit would be one limit for every local MCP + // client: one busy or broken client would stop every other client renewing its token. + // Nothing here can tell callers apart before the token request is read (client IDs are + // public and registered freely), and codes, verifiers and refresh tokens cannot be guessed. + customRules: { "/oauth2/token": false as const }, + }, }; yield* Effect.tryPromise({ try: async () => { diff --git a/bun.lock b/bun.lock index ce76ff1f07..95028b571b 100644 --- a/bun.lock +++ b/bun.lock @@ -40,7 +40,7 @@ }, "apps/cli": { "name": "executor", - "version": "2.0.0-beta.59", + "version": "2.0.0-beta.60", }, "apps/docs": { "name": "@executor-js/docs", diff --git a/e2e/README.md b/e2e/README.md index 436a1cd021..869ee26679 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -1029,7 +1029,11 @@ only the scenarios declaring `runtime: "rolled-back"`. Managed local Cloud runs with Better Auth's OAuth proxy on, as the proxy's production (its edge), as production does. `bun run e2e:cloud --oauth-proxy-preview` also starts a second local Cloud as that production and tests a stage that signs in through it, -running only the scenarios declaring `runtime: "oauth-proxy-preview"`. Production (`v2`), +running only the scenarios declaring `runtime: "oauth-proxy-preview"`. +`bun run e2e:cloud --removal-revocation-budget` starts it with organization +removal's revocation budget shortened to five seconds and runs only the +scenarios declaring `runtime: "revocation-budget"`; every other local Cloud +keeps the deployed five minutes. Production (`v2`), ordinary previews and every other deployed stage always retain rate limits, whatever their configuration; `bun run auth:rate-limit` (part of `check`) proves it. Local and diff --git a/e2e/ci-selection.ts b/e2e/ci-selection.ts index 561566a73a..fd7f0f8d4d 100644 --- a/e2e/ci-selection.ts +++ b/e2e/ci-selection.ts @@ -178,7 +178,7 @@ const jobs = { runner: 3, pattern: - "Cloud SSO SAML accepts|Cloud's operator OAuth client signs in|Cloud's own Executor for Google registration refuses|Safari reports only the page's own failures|Cloud cron triggers run their jobs|Cloud cron jobs record their outcome|Cloud support dialog lists every channel|Hosted feedback enforces its API contract|Executor's catalog calls an app's own cache methods|Executor app is installed with nothing left pending|Cloud MCP routes a request inside a session|Cloud MCP sessions continue after their session object is evicted|Request and workflow attempts at one team|remote skill catalog|a skill read without a revision|abandons a GitHub skills load|reads its catalog and the tool in one cache command|a cold call's wake is reported by that call alone|another organization's admin cannot read the link|account connections cannot cross organizations|Deploys wake webhook source setup|Cloud's schedule coordinator keeps nine slow scheduled runs|a webhook source reconciling for an activation that another supersedes|A skill catalog refreshed in the background after a dashboard batch read|Cloud MCP session objects run parallel tool calls|Cloud MCP session objects cancel a statement|Cloud MCP session objects discover the other apps|Cloud MCP session objects' database pool|Cloud's database pool runs a statement whose connection|Hosted MCP resume reports an approved call's own failure|Cloud refuses to remove an organization while one of its app workflows runs|Cloud v1 session handoff|Cloud accepts MCP requests v1 forwards|Cloud validates a v1 WorkOS API key|Hosted MCP operation and bearer-check spans name|Hosted management API request spans name only|Hosted request spans record the client, the credential|Cloud's gateway names an authenticated MCP request's organization|A person deletes their own user|Cloud invitations left pending after their inviter lost|On Cloud a slow tool call log write|A Cloud scenario's clean-up returns once its organization's removal is accepted|The end-of-run removal check answers each look within its request limit|The end-of-run removal check asks again after a dropped request|The end-of-run removal check keeps waiting for a removal recorded done|a run's sleep whose engine call failed is called again", + "Cloud SSO SAML accepts|Cloud's operator OAuth client signs in|Cloud's own Executor for Google registration refuses|Safari reports only the page's own failures|Cloud cron triggers run their jobs|Cloud cron jobs record their outcome|Cloud support dialog lists every channel|Hosted feedback enforces its API contract|Executor's catalog calls an app's own cache methods|Executor app is installed with nothing left pending|Cloud MCP routes a request inside a session|Cloud MCP sessions continue after their session object is evicted|Request and workflow attempts at one team|remote skill catalog|a skill read without a revision|abandons a GitHub skills load|reads its catalog and the tool in one cache command|a cold call's wake is reported by that call alone|another organization's admin cannot read the link|account connections cannot cross organizations|Deploys wake webhook source setup|Cloud's schedule coordinator keeps nine slow scheduled runs|a webhook source reconciling for an activation that another supersedes|A skill catalog refreshed in the background after a dashboard batch read|Cloud MCP session objects run parallel tool calls|Cloud MCP session objects cancel a statement|Cloud MCP session objects discover the other apps|Cloud MCP session objects' database pool|Cloud's database pool runs a statement whose connection|Hosted MCP resume reports an approved call's own failure|Cloud refuses to remove an organization while one of its app workflows runs|Removing an organization revokes the refresh token|Cloud v1 session handoff|Cloud accepts MCP requests v1 forwards|Cloud validates a v1 WorkOS API key|Hosted MCP operation and bearer-check spans name|Hosted management API request spans name only|Hosted request spans record the client, the credential|Cloud's gateway names an authenticated MCP request's organization|A person deletes their own user|Cloud invitations left pending after their inviter lost|On Cloud a slow tool call log write|A Cloud scenario's clean-up returns once its organization's removal is accepted|The end-of-run removal check answers each look within its request limit|The end-of-run removal check asks again after a dropped request|The end-of-run removal check keeps waiting for a removal recorded done|a run's sleep whose engine call failed is called again", }, // Cloud's hosts: role hosts, the edge and sign-in on `app.`. Run in `cloud-product`, their // load kept the team installation's workflow span from arriving within its 30-second wait, so @@ -294,6 +294,14 @@ const jobs = { pattern: "A test stage signs in through production's OAuth proxy|A test stage connects an account with production's OAuth callback", }, + // Managed Cloud keeps organization removal's deployed revocation budget; this job starts one with + // it shortened, so only this scenario's removals run it out. + "cloud-revocation-budget": { + target: "cloud", + runner: 6, + cloudMode: "revocation-budget", + pattern: "Removing an organization whose service never answers revocations", + }, } as const satisfies Record< string, | { target: "local" | "self-host"; pattern: string; shards?: number } diff --git a/e2e/run.ts b/e2e/run.ts index 0111320ed6..5910ea9d37 100644 --- a/e2e/run.ts +++ b/e2e/run.ts @@ -62,6 +62,11 @@ const command = Command.make( // Start a second managed Cloud as the OAuth proxy's production, run against a test stage that // signs in through it, and run only the scenarios that prove the proxy. oauthProxyPreview: Flag.Boolean("oauth-proxy-preview").pipe(Flag.withDefault(false)), + // Start managed Cloud with organization removal's revocation budget shortened, and run only the + // scenarios that run it out. + removalRevocationBudget: Flag.Boolean("removal-revocation-budget").pipe( + Flag.withDefault(false), + ), // Run one part of a local or self-host run; see `partPattern`. part: Flag.String("part").pipe(Flag.optional), }, diff --git a/e2e/sdk/suite.ts b/e2e/sdk/suite.ts index 388bef01aa..a79707bf40 100644 --- a/e2e/sdk/suite.ts +++ b/e2e/sdk/suite.ts @@ -18,6 +18,7 @@ import { scenariosForSuite, type CloudMode, type TestPlan } from "../test-plan.t import { readEvidence, combineEvidenceReports, reportRuntimeCrashes } from "../evidence-results.ts"; import { type EvidenceReport, type RunMetadata } from "../report-model.ts"; import { startCloudEnvironment } from "../support/cloud-environment.ts"; +import { removalRevocationBudgetMs } from "../support/removal-revocation-budget.ts"; import { lockedNpmRegistry } from "../support/npm-registry.ts"; import { publicCatalogs } from "../support/public-catalogs.ts"; import { type FixtureControl, fixtureControlEnvironment } from "./fixtures.ts"; @@ -64,6 +65,7 @@ export const runSuite = ({ authRateLimit = false, rollback = false, oauthProxyPreview = false, + removalRevocationBudget = false, attachment, }: { readonly target: "self-host" | "local" | "cloud" | "all" | "hosted"; @@ -84,6 +86,11 @@ export const runSuite = ({ * signs in through it, for the scenarios that prove the proxy. */ readonly oauthProxyPreview?: boolean; + /** + * Start managed Cloud with organization removal's revocation budget shortened to + * `removalRevocationBudgetMs`, for the scenarios that run it out. + */ + readonly removalRevocationBudget?: boolean; readonly attachment?: { readonly origin: string; readonly directory?: string; @@ -148,6 +155,18 @@ export const runSuite = ({ message: "The OAuth proxy preview runs only on managed Cloud, without --auth-rate-limit or --rollback. Use --target cloud without E2E_CLOUD_URL.", }); + if ( + removalRevocationBudget && + (authRateLimit || + rollback || + oauthProxyPreview || + selected !== "cloud" || + Option.isSome(cloud)) + ) + return yield* new RunFailed({ + message: + "The shortened revocation budget runs only on managed Cloud, without --auth-rate-limit, --rollback or --oauth-proxy-preview. Use --target cloud without E2E_CLOUD_URL.", + }); const interactive = yield* Config.Boolean("E2E_INTERACTIVE").pipe(Config.withDefault(false)); const observeUI = yield* Config.Boolean("E2E_UI_OBSERVE").pipe(Config.withDefault(false)); if (observeUI && (selected !== "cloud" || Option.isSome(cloud))) @@ -192,7 +211,9 @@ export const runSuite = ({ ? "rolled-back" : oauthProxyPreview ? "oauth-proxy-preview" - : "managed"; + : removalRevocationBudget + ? "revocation-budget" + : "managed"; const plan = scenariosForSuite(selected === "hosted" ? "hosted" : "all", cloudMode); const filter = yield* Effect.try({ try: () => new RegExp(name), @@ -239,7 +260,7 @@ export const runSuite = ({ runtime: target === "cloud" ? managedCloud - ? `Local Cloud Worker + Postgres · no saved credentials · auth rate limit ${authRateLimit ? "on" : "off"}${rollback ? " · sign-in on the deployment origin" : ""}${oauthProxyPreview ? " · a test stage signing in through a second local Cloud's OAuth proxy" : ""}` + ? `Local Cloud Worker + Postgres · no saved credentials · auth rate limit ${authRateLimit ? "on" : "off"}${rollback ? " · sign-in on the deployment origin" : ""}${oauthProxyPreview ? " · a test stage signing in through a second local Cloud's OAuth proxy" : ""}${removalRevocationBudget ? ` · organization removal revocation budget ${removalRevocationBudgetMs} ms` : ""}` : "Cloud endpoint" : target === "local" && Option.isSome(packagedEntry) ? "Installed npm CLI + PGlite per scenario" @@ -300,6 +321,7 @@ export const runSuite = ({ commit, observeUI, authRateLimit, + ...(removalRevocationBudget ? { removalRevocationBudgetMs } : {}), browserOrigin: rollback ? "deployment" : "app", ...Option.match(production, { onNone: () => ({}), diff --git a/e2e/support/cloud-environment.ts b/e2e/support/cloud-environment.ts index 1a326d8650..635f683128 100644 --- a/e2e/support/cloud-environment.ts +++ b/e2e/support/cloud-environment.ts @@ -104,6 +104,12 @@ export const startCloudEnvironment = (input: { * scenarios that prove it. */ readonly authRateLimit: boolean; + /** + * Organization removal's revocation budget, 5 minutes deployed. Only the Cloud of the scenarios + * that run it out sets it (`e2e:cloud --removal-revocation-budget`), so every other scenario's + * removals revoke under the deployed budget. Only `alchemy dev` honours it. + */ + readonly removalRevocationBudgetMs?: number; /** * Which host serves the dashboard and sign-in: `app.` of the origin, or, with the rollback * switch (`CLOUD_BROWSER_ORIGIN=deployment`), the origin itself. @@ -229,6 +235,9 @@ export const startCloudEnvironment = (input: { OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: `${collector}/v1/logs`, EXECUTOR_ENVIRONMENT: "test-local", TEST_STAGE_AUTH_RATE_LIMIT: String(input.authRateLimit), + ...(input.removalRevocationBudgetMs === undefined + ? {} + : { TEST_STAGE_REMOVAL_REVOCATION_BUDGET_MS: String(input.removalRevocationBudgetMs) }), VITE_POSTHOG_KEY: "synthetic-ingestion-key", VITE_POSTHOG_PATH: "/api/0123456789abcdef", VITE_POSTHOG_HOST: `http://127.0.0.1:${analyticsPort}`, diff --git a/e2e/support/oauth-setup-issuer.ts b/e2e/support/oauth-setup-issuer.ts index 511f072637..db976e4ae6 100644 --- a/e2e/support/oauth-setup-issuer.ts +++ b/e2e/support/oauth-setup-issuer.ts @@ -178,13 +178,22 @@ export const oauthSetupIssuer = Effect.gen(function* () { let refreshSubject = "synthetic-subject"; /** Lifetime of renewed tokens; unset, they last `expiresIn` like the first ones. */ let refreshedExpiresIn: number | undefined; - /** An RFC 7009 endpoint that records calls, or one that always fails. */ - let revocation: "none" | "recorded" | "failing" = "none"; + /** + * An RFC 7009 endpoint that records calls, one that always fails, or one that records each call + * and never answers it until the issuer closes. + */ + let revocation: "none" | "recorded" | "failing" | "stalled" = "none"; const revocations: Array<{ readonly token: "refresh" | "access" | "unknown"; readonly hint: string | null; readonly clientAuthenticated: boolean; }> = []; + /** + * Revocation requests that reached the service, counted by the arrival gate below as each one's + * headers arrive, and the waits for a number of them. + */ + let revocationArrivals = 0; + const arrivalWaits = new Set<() => void>(); const keyPair = generateKeyPairSync("ec", { namedCurve: "prime256v1" }); let rsaKey: KeyObject | undefined; /** Refresh tokens issued for each client; unless rotation is configured, refreshes keep them. */ @@ -847,6 +856,11 @@ export const oauthSetupIssuer = Effect.gen(function* () { client.secret !== null && presented.secret === client.secret, }); + if (revocation === "stalled") { + const released = yield* Deferred.make(); + releases.push(released); + yield* Deferred.await(released); + } return revocation === "failing" ? HttpServerResponse.empty({ status: 503 }) : HttpServerResponse.empty({ status: 200 }); @@ -949,6 +963,14 @@ export const oauthSetupIssuer = Effect.gen(function* () { ), ); const listener = yield* Effect.sync(() => createServer()); + // The arrival gate counts a revocation request when Node reads its headers, before the router's + // handler runs. A caller that gives up on the request closes it, which interrupts that handler, + // so a count kept there would depend on how soon this process ran it; this one does not. + listener.prependListener("request", (request) => { + if (request.method !== "POST" || request.url?.split("?")[0] !== "/revoke") return; + revocationArrivals++; + for (const wait of arrivalWaits) wait(); + }); const services = yield* Layer.build( HttpRouter.serve(routes, { disableLogger: true, disableListenLog: true }).pipe( Layer.provideMerge(NodeHttpServer.layer(() => listener, { host: "127.0.0.1", port })), @@ -1038,7 +1060,7 @@ export const oauthSetupIssuer = Effect.gen(function* () { readonly refreshSubject?: string; /** Lifetime of renewed tokens; null makes them last `expiresIn`. */ readonly refreshedExpiresIn?: number | null; - /** Advertise an RFC 7009 endpoint that records calls, or one that always fails. */ + /** Advertise an RFC 7009 endpoint that records calls, always fails, or never answers. */ readonly revocation?: typeof revocation; /** How the token and revocation endpoints read HTTP Basic client credentials. */ readonly basicCredentials?: typeof basicCredentials; @@ -1167,6 +1189,18 @@ export const oauthSetupIssuer = Effect.gen(function* () { expireAccessTokens: Effect.sync(() => { for (const token of issuedAccessTokens) expiredAccessTokens.add(token); }), + /** Wait until `count` revocation requests have reached the service (see the arrival gate). */ + revocationArrivals: (count: number) => + Effect.callback((resume) => { + const wait = () => { + if (revocationArrivals < count) return; + arrivalWaits.delete(wait); + resume(Effect.void); + }; + arrivalWaits.add(wait); + wait(); + return Effect.sync(() => arrivalWaits.delete(wait)); + }), /** Answer every held request; one held before processing stays unprocessed. */ release: Effect.suspend(() => { const pending = releases; @@ -1198,6 +1232,7 @@ export const oauthSetupIssuer = Effect.gen(function* () { lastExchangeAuth, nonceRequested, revocations: [...revocations], + revocationArrivals, revokedRefreshTokens: [...revokedRefreshTokens], resourceRequests: { ...resourceRequests }, resourceAuthorizations: [...resourceAuthorizations], diff --git a/e2e/support/removal-revocation-budget.ts b/e2e/support/removal-revocation-budget.ts new file mode 100644 index 0000000000..32e325650e --- /dev/null +++ b/e2e/support/removal-revocation-budget.ts @@ -0,0 +1,7 @@ +/** + * Organization removal's revocation budget on the local Cloud that `e2e:cloud + * --removal-revocation-budget` starts, in milliseconds; deployed, and on every other local Cloud, + * it is 5 minutes. It must stay under the 10 seconds one revocation in a purge may take, so the + * budget, not each revocation's own deadline, is what ends a revocation that never answers. + */ +export const removalRevocationBudgetMs = 5_000; diff --git a/e2e/test-plan.ts b/e2e/test-plan.ts index 4186a8014c..5be9f4407e 100644 --- a/e2e/test-plan.ts +++ b/e2e/test-plan.ts @@ -13,6 +13,7 @@ export const TargetPlan = Schema.Union([ "rate-limited", "rolled-back", "oauth-proxy-preview", + "revocation-budget", ]), ), }), @@ -74,6 +75,11 @@ const rateLimitedCloud = { status: "scheduled", runtime: "rate-limited" } as con const rolledBackCloud = { status: "scheduled", runtime: "rolled-back" } as const; /** Runs on a managed test stage that signs in through a second local Cloud's OAuth proxy. */ const oauthProxyPreviewCloud = { status: "scheduled", runtime: "oauth-proxy-preview" } as const; +/** + * Runs alone on a managed local Cloud whose organization removal revocation budget is shortened to + * `removalRevocationBudgetMs`; every other local Cloud keeps the deployed budget. + */ +const revocationBudgetCloud = { status: "scheduled", runtime: "revocation-budget" } as const; const na = (reason: string) => ({ status: "not-applicable", reason }) as const; const cloudOnboarding = { cloud: scheduled, @@ -7616,6 +7622,16 @@ export const scenarios = plan({ ), }, }, + localOAuthTokenLimit: { + file: "local-oauth-token-limit.spec.ts", + title: + "A local MCP client whose token requests keep failing does not stop another local client getting its tokens", + targets: { + local: scheduled, + "self-host": na("Self-host limits token requests by each caller's own address."), + cloud: na("Cloud limits token requests by each caller's own address."), + }, + }, localMcpOAuthWithoutResource: { file: "local-mcp-connections.spec.ts", title: "Local MCP OAuth without a resource parameter grants the plain /mcp URL", @@ -11341,6 +11357,30 @@ export const scenarios = plan({ local: na("Local has no hosted organizations and serves no owner removal."), }, }, + organizationRemovalRevocation: { + fixtures: "actors", + file: "organization-removal-revocation.spec.ts", + title: + "Removing an organization revokes the refresh token of each of its OAuth accounts at the service once", + targets: { + cloud: managedCloud, + "self-host": na("Self-host has a single instance organization and no organization removal."), + local: na("Local has no hosted organizations."), + }, + }, + organizationRemovalRevocationBudget: { + fixtures: "actors", + file: "organization-removal-revocation.spec.ts", + title: + "Removing an organization whose service never answers revocations finishes within its revocation budget and records how many OAuth grants it did not revoke", + targets: { + // Only a local Cloud of its own shortens the budget to fit a scenario; every other local + // Cloud and every deployed stage keep 5 minutes. + cloud: revocationBudgetCloud, + "self-host": na("Self-host has a single instance organization and no organization removal."), + local: na("Local has no hosted organizations."), + }, + }, organizationRemovalRecovery: { fixtures: "actors", file: "organization-removal-recovery.spec.ts", @@ -11509,14 +11549,17 @@ export const scenarios = plan({ * How the run reaches Cloud. Managed Cloud is local and turns the per-address auth limit off, as * deployed test stages do; a rate-limited run starts it with the limit on for the scenarios that * prove it, and runs only those. A rolled-back run starts it with its rollback switch on, sign-in - * on the deployment origin, and runs only the scenarios that prove the switch. + * on the deployment origin, and runs only the scenarios that prove the switch. A revocation-budget + * run starts it with organization removal's revocation budget shortened, and runs only the + * scenarios that run that budget out. */ export type CloudMode = | "managed" | "attached" | "rate-limited" | "rolled-back" - | "oauth-proxy-preview"; + | "oauth-proxy-preview" + | "revocation-budget"; const cloudRuntimeReasons = { managed: "Requires the managed local Cloud target and its local collectors.", @@ -11527,6 +11570,8 @@ const cloudRuntimeReasons = { "Requires a managed local Cloud with its rollback switch on: e2e:cloud --rollback.", "oauth-proxy-preview": "Requires a managed test stage signing in through a second local Cloud's OAuth proxy: e2e:cloud --oauth-proxy-preview.", + "revocation-budget": + "Requires a managed local Cloud with organization removal's revocation budget shortened: e2e:cloud --removal-revocation-budget.", } as const; /** @@ -11559,7 +11604,8 @@ export const scenariosForSuite = ( cloud.runtime === undefined ? cloudMode !== "rate-limited" && cloudMode !== "rolled-back" && - cloudMode !== "oauth-proxy-preview" + cloudMode !== "oauth-proxy-preview" && + cloudMode !== "revocation-budget" : cloud.runtime === cloudMode; return runs ? scenario @@ -11573,7 +11619,9 @@ export const scenariosForSuite = ( ? "Runs on Cloud with sign-in on app., without the rollback switch." : cloudMode === "oauth-proxy-preview" ? "Runs on Cloud as the OAuth proxy's production, not on a stage signing in through it." - : "Runs on Cloud without the per-address auth limit." + : cloudMode === "revocation-budget" + ? "Runs on Cloud with organization removal's deployed revocation budget." + : "Runs on Cloud without the per-address auth limit." : cloudRuntimeReasons[cloud.runtime], ), }, diff --git a/e2e/tests/ci-selection.spec.ts b/e2e/tests/ci-selection.spec.ts index b42ef4d3e4..556ce61d06 100644 --- a/e2e/tests/ci-selection.spec.ts +++ b/e2e/tests/ci-selection.spec.ts @@ -52,6 +52,7 @@ const jobs = [ "cloud-rate-limit", "cloud-rollback", "cloud-oauth-proxy-preview", + "cloud-revocation-budget", ]; /** The outputs that start the E2E runners: each sharded job's parts and the Cloud runners. */ const runnerOutputs = ["local-shards", "self-host-shards", "cloud-runners"]; @@ -628,7 +629,7 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { ), "cloud-workers, cloud-locks, cloud-batch, cloud-autumn", "cloud-domains, cloud-rate-limit, cloud-rollback, cloud-oauth-proxy-preview", - "cloud-removal-recovery, cloud-export-hang, cloud-listings", + "cloud-removal-recovery, cloud-export-hang, cloud-listings, cloud-revocation-budget", ]); // Each Cloud job's pattern is on exactly one runner and empty on the others. The runner // runs it unchanged, except cloud-product past what one local Cloud holds: each of its @@ -2697,6 +2698,7 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { "cloud-rate-limit", "cloud-rollback", "cloud-oauth-proxy-preview", + "cloud-revocation-budget", ]) expect(noCloud.log).toMatch( new RegExp(`- the ${job} job on cloud: (\\d+) of \\1 scenarios did not run`), diff --git a/e2e/tests/local-oauth-token-limit.spec.ts b/e2e/tests/local-oauth-token-limit.spec.ts new file mode 100644 index 0000000000..d7f13fcec5 --- /dev/null +++ b/e2e/tests/local-oauth-token-limit.spec.ts @@ -0,0 +1,96 @@ +/** + * Every MCP client of the local server reaches it from the loopback address, so token requests + * one client makes never stop another client from getting its tokens. + */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Schema } from "effect"; +import { HttpClient, HttpClientRequest } from "effect/http"; +import { randomBytes } from "node:crypto"; +import { scenarios } from "../test-plan.ts"; +import { TestLive, withCase } from "../support/case.ts"; +import { Evidence } from "../support/evidence.ts"; +import { pairLocalOperator } from "../support/mcp-consent.ts"; +import { consentTo, revokeClientGrants } from "../support/mcp-connections.ts"; +import { Target } from "../support/platform.ts"; + +const Registered = Schema.Struct({ client_id: Schema.NonEmptyString }); +const TokenError = Schema.Struct({ error: Schema.String }); +/** More than the hosted products allow one address in a minute. */ +const refusedRequests = 30; + +layer(TestLive, { excludeTestServices: true })("Local OAuth token limit", (it) => { + it.effect(scenarios.localOAuthTokenLimit.title, (context) => + withCase( + context, + Effect.gen(function* () { + const target = yield* Target, + http = yield* HttpClient.HttpClient, + evidence = yield* Evidence; + const origin = target.metadata.origin; + const operator = yield* pairLocalOperator; + const clients: string[] = []; + yield* revokeClientGrants(operator, () => clients); + + // One local client registers and then keeps presenting a refresh token the server never + // issued, as a client with a broken token store does. + const broken = yield* Effect.scoped( + Effect.gen(function* () { + const response = yield* http.execute( + yield* HttpClientRequest.post(`${origin}/api/auth/oauth2/register`).pipe( + HttpClientRequest.setHeaders({ origin }), + HttpClientRequest.bodyJson({ + client_name: "Broken local client", + redirect_uris: ["http://127.0.0.1:9/callback"], + token_endpoint_auth_method: "none", + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + }), + ), + ); + expect(response.status).toBe(201); + const registered = yield* response.json.pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Registered)), + ); + return registered.client_id; + }), + ); + const refusals = yield* evidence.step( + `The broken client makes ${refusedRequests} refresh requests in a row`, + Effect.forEach(Array.from({ length: refusedRequests }), () => + Effect.scoped( + Effect.gen(function* () { + const response = yield* http.execute( + HttpClientRequest.post(`${origin}/api/auth/oauth2/token`).pipe( + HttpClientRequest.bodyUrlParams({ + grant_type: "refresh_token", + client_id: broken, + refresh_token: randomBytes(32).toString("base64url"), + }), + ), + ); + const answer = yield* response.json.pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Schema.UndefinedOr(TokenError))), + Effect.orElseSucceed(() => undefined), + ); + return { status: response.status, error: answer?.error }; + }), + ), + ), + ); + // Another local client signs in straight after and gets its tokens. + const consent = yield* evidence.step( + "Another local client signs in", + consentTo(operator, undefined), + ); + clients.push(consent.clientId); + expect(consent.status).toBe(200); + yield* evidence.step("The other client exchanges its code for tokens", consent.tokens); + // Each request is refused for its own token, never for how many requests came before it. + expect(refusals.filter((refusal) => refusal.status === 429)).toEqual([]); + expect(new Set(refusals.map((refusal) => refusal.error))).toEqual( + new Set(["invalid_grant"]), + ); + }), + ), + ); +}); diff --git a/e2e/tests/organization-removal-revocation.spec.ts b/e2e/tests/organization-removal-revocation.spec.ts new file mode 100644 index 0000000000..ea1c362ea7 --- /dev/null +++ b/e2e/tests/organization-removal-revocation.spec.ts @@ -0,0 +1,303 @@ +/** Removing an organization revokes its OAuth accounts' grants at the provider, as deleting one does. */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Schedule, Schema } from "effect"; +import { FetchHttpClient, HttpClient } from "effect/http"; +import { randomUUID } from "node:crypto"; +import { Actors } from "../support/actors.ts"; +import { Api, body } from "../support/api.ts"; +import { connectionsPath } from "../support/app-accounts.ts"; +import { oauthMcpAppFiles } from "../support/authored-templates.ts"; +import { HostedLive, withHostedCase } from "../support/case.ts"; +import { cloudLocks } from "../support/cloud-locks.ts"; +import { Organization, Resource } from "../support/contracts.ts"; +import { type DeliveredSpan, Evidence, Telemetry } from "../support/evidence.ts"; +import { oauthSetupIssuer } from "../support/oauth-setup-issuer.ts"; +import { removalRevocationBudgetMs } from "../support/removal-revocation-budget.ts"; +import { scenarios } from "../test-plan.ts"; + +const SignIn = Schema.Struct({ authorizationUrl: Schema.String }); +const Detail = Schema.Struct({ revocation: Schema.Literals(["automatic", "manual"]) }); +const Status = Schema.Array(Schema.Struct({ status: Schema.Literals(["running", "done"]) })); +/** The removal workflow runs after the response that accepts it. */ +class StillRunning extends Error {} +/** A span the scenario reads has not been delivered yet. */ +class NotDelivered extends Error {} + +/** A new organization of the owner's, removed at the end if the scenario has not removed it. */ +const organization = (name: string) => + Effect.gen(function* () { + const actors = yield* Actors, + api = yield* Api, + locks = yield* cloudLocks; + const suffix = randomUUID().slice(0, 8); + const created = yield* body( + Organization, + yield* api.request(actors.owner, "POST", "/api/auth/organization/create", { + name: `${name} ${suffix}`, + slug: `${name.toLowerCase()}-${suffix}`, + keepCurrentActiveOrganization: true, + }), + ); + const prefix = `/api/organizations/${created.id}`; + let removed = false; + yield* Effect.addFinalizer(() => + removed ? Effect.void : api.request(actors.owner, "DELETE", prefix).pipe(Effect.ignore), + ); + /** Remove the organization and wait until its removal workflow has run every step. */ + const remove = Effect.gen(function* () { + const accepted = yield* api.request(actors.owner, "DELETE", prefix); + expect(accepted.status, JSON.stringify(accepted.body)).toBe(200); + removed = true; + expect(accepted.body).toMatchObject({ organization: created.id }); + // Every step has run, the second purge of the owner's records included. + yield* locks + .run({ + sql: "select status from hosted_organization_removal where organization_id = $1", + params: [created.id], + }) + .pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Status)), + Effect.flatMap((rows) => + rows[0]?.status === "done" + ? Effect.void + : Effect.fail(new StillRunning(`Removal of ${created.id} has not finished`)), + ), + Effect.retry({ + while: (error) => error instanceof StillRunning, + schedule: Schedule.spaced("500 millis"), + }), + Effect.timeout("60 seconds"), + ); + }); + return { id: created.id, prefix, suffix, remove }; + }); + +/** Deploy an app that signs in to `issuer` with OAuth, and return a way to sign in one account. */ +const oauthApp = (prefix: string, name: string, issuer: string) => + Effect.gen(function* () { + const actors = yield* Actors, + api = yield* Api, + http = yield* HttpClient.HttpClient; + const deployed = yield* api.request(actors.owner, "POST", `${prefix}/apps/deploy`, { + name, + files: oauthMcpAppFiles(name, `${issuer}/mcp`), + }); + expect(deployed.status, JSON.stringify(deployed.body)).toBe(200); + const app = yield* body(Resource, deployed); + /** A new account, through the whole sign-in: each new connection saves a new account. */ + return (label: string) => + Effect.gen(function* () { + const connection = yield* body( + Resource, + yield* api.request( + actors.owner, + "POST", + connectionsPath(`${prefix}/apps/${app.id}`, "user", "service"), + {}, + ), + ); + const started = yield* api.request( + actors.owner, + "POST", + `${prefix}/connections/${connection.id}/oauth/start`, + { method: "oauth", label }, + ); + expect(started.status, JSON.stringify(started.body)).toBe(200); + const { authorizationUrl } = yield* body(SignIn, started); + const callbackUrl = yield* Effect.scoped( + Effect.gen(function* () { + const consent = yield* HttpClient.withScope(http).get(authorizationUrl); + expect(consent.status).toBe(302); + const location = consent.headers.location; + if (location === undefined) + return yield* Effect.die("Issuer did not return a callback"); + return location; + }), + ).pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" })); + const completed = yield* api.request( + actors.owner, + "POST", + `${prefix}/connections/${connection.id}/oauth/complete`, + { callbackUrl }, + ); + expect(completed.status, JSON.stringify(completed.body)).toBe(200); + return yield* body(Resource, completed); + }); + }); + +layer(HostedLive, { excludeTestServices: true })("Organization removal revocation", (it) => { + it.effect(scenarios.organizationRemovalRevocation.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const actors = yield* Actors, + api = yield* Api, + evidence = yield* Evidence; + const issuer = yield* oauthSetupIssuer; + yield* issuer.configure({ refreshTokens: true, revocation: "recorded" }); + const created = yield* organization("Revoked"); + + const account = yield* evidence.step( + "The organization holds an account signed in with OAuth", + Effect.gen(function* () { + const signIn = yield* oauthApp( + created.prefix, + `Revoked ${created.suffix} service`, + issuer.origin, + ); + const saved = yield* signIn("Organization account"); + // Deleting this account on its own would revoke its grant. + const detail = yield* api.request( + actors.owner, + "GET", + `${created.prefix}/accounts/${saved.id}`, + ); + expect(yield* body(Detail, detail)).toEqual({ revocation: "automatic" }); + return saved; + }), + ); + expect((yield* issuer.metrics).revocations).toEqual([]); + + yield* evidence.step( + "The owner removes the organization and its removal finishes", + Effect.gen(function* () { + yield* created.remove; + expect( + (yield* api.request(actors.owner, "GET", `${created.prefix}/accounts/${account.id}`)) + .status, + ).toBe(403); + }), + ); + + // The removal revoked the refresh token once with the grant's own client, and the second + // purge found nothing more to revoke. + expect((yield* issuer.metrics).revocations).toEqual([ + { token: "refresh", hint: "refresh_token", clientAuthenticated: true }, + ]); + }), + ), + ); + + it.effect(scenarios.organizationRemovalRevocationBudget.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const evidence = yield* Evidence, + telemetry = yield* Telemetry; + // The service accepts each revocation and never answers it. + const issuer = yield* oauthSetupIssuer; + yield* issuer.configure({ refreshTokens: true, revocation: "stalled" }); + const created = yield* organization("Unrevoked"); + // More accounts than the purge revokes at once (eight), so some are never started. + const accounts = 10; + + yield* evidence.step( + `The organization holds ${accounts} accounts signed in with OAuth`, + Effect.gen(function* () { + const signIn = yield* oauthApp( + created.prefix, + `Unrevoked ${created.suffix} service`, + issuer.origin, + ); + for (let index = 0; index < accounts; index++) + yield* signIn(`Organization account ${index + 1}`); + }), + ); + + // This scenario's own local Cloud shortens the budget to `removalRevocationBudgetMs`. + yield* evidence.step( + "The owner removes the organization and its removal finishes", + created.remove, + ); + // The first eight reached the service and were cut off; the other two were never sent. The + // service's arrival gate counts each request as it arrives, so the count does not depend on + // when this process handled it, and the removal has finished, so no more can follow. + yield* evidence.step( + "Eight revocations reached the service", + issuer.revocationArrivals(8).pipe(Effect.timeout("10 seconds")), + ); + const { revocationArrivals, revocations } = yield* issuer.metrics; + expect(revocationArrivals).toBe(8); + // Each one the service read is the grant's refresh token, sent with its own client. + for (const revoked of revocations) + expect(revoked).toEqual({ + token: "refresh", + hint: "refresh_token", + clientAuthenticated: true, + }); + + const counts = yield* evidence.step( + "The purge records how many grants it did not revoke", + Effect.gen(function* () { + const steps = yield* telemetry + .search( + "organization.removal.step", + { organization: created.id }, + { "executor.removal.step": "purge-owner-store" }, + ) + .pipe( + Effect.flatMap((found) => + found.data.length > 0 + ? Effect.succeed(found.data.map(({ traceId }) => traceId)) + : Effect.fail(new NotDelivered("The purge step's span has not arrived")), + ), + Effect.retry({ + while: (error) => error instanceof NotDelivered, + schedule: Schedule.spaced("500 millis"), + times: 40, + }), + ); + // The first purge deleted the grants; the second found none. + const purge = (spans: ReadonlyArray) => + spans.find( + (span) => + span.operationName === "sdk.owners.remove" && + span.tags["oauth.revocation.grants"] === String(accounts), + ); + /** The purge's own revocations, one span each. */ + const revoked = (spans: ReadonlyArray, parent: DeliveredSpan) => + spans.filter( + (span) => + span.operationName === "oauth.revokeGrant" && span.parentSpanId === parent.spanId, + ); + const spans = yield* telemetry.settled(steps, (spans) => { + const found = purge(spans); + return found !== undefined && revoked(spans, found).length >= 8; + }); + const found = purge(spans); + if (found === undefined) return yield* Effect.die("The purge's span went missing"); + const revocationSpans = revoked(spans, found); + const end = Date.parse(found.startTime) + found.durationMs; + const firstRevocation = Math.min( + ...revocationSpans.map((span) => Date.parse(span.startTime)), + ); + const logs = yield* Effect.forEach(steps, telemetry.logs); + return { + grants: found.tags["oauth.revocation.grants"], + settled: found.tags["oauth.revocation.settled"], + cutOff: found.tags["oauth.revocation.cut_off"], + unattempted: found.tags["oauth.revocation.unattempted"], + revocationSpans: revocationSpans.length, + warned: logs.some((records) => records.includes("stopped revoking OAuth grants")), + purgeMs: found.durationMs, + revokingMs: end - firstRevocation, + }; + }), + ); + expect(counts).toMatchObject({ + grants: "10", + settled: "0", + cutOff: "8", + unattempted: "2", + revocationSpans: 8, + warned: true, + }); + // The purge revoked until its budget ran out, and no longer. Each revocation in a purge + // may take 10 seconds, so a budget the purge did not enforce would keep it revoking until + // then; the 2 seconds above the budget leave room only for a slow machine. + expect(counts.purgeMs).toBeGreaterThanOrEqual(removalRevocationBudgetMs); + expect(counts.revokingMs).toBeLessThanOrEqual(removalRevocationBudgetMs + 2_000); + }), + ), + ); +}); diff --git a/e2e/vitest.config.ts b/e2e/vitest.config.ts index a9064efb11..ed4908da1a 100644 --- a/e2e/vitest.config.ts +++ b/e2e/vitest.config.ts @@ -10,7 +10,14 @@ if (!directory) throw new Error("Use bun run e2e to start an isolated target fir const target = Schema.decodeUnknownSync(Target)(process.env.E2E_TARGET); const suite = Schema.decodeUnknownSync(Schema.Literals(["all", "hosted"]))(process.env.E2E_SUITE); const cloudMode = Schema.decodeUnknownSync( - Schema.Literals(["managed", "attached", "rate-limited", "rolled-back", "oauth-proxy-preview"]), + Schema.Literals([ + "managed", + "attached", + "rate-limited", + "rolled-back", + "oauth-proxy-preview", + "revocation-budget", + ]), )(process.env.E2E_CLOUD_MODE); export default defineConfig({ test: { diff --git a/packages/sdk/src/contracts/executor.ts b/packages/sdk/src/contracts/executor.ts index 9cf2aabac6..eb3f8151c7 100644 --- a/packages/sdk/src/contracts/executor.ts +++ b/packages/sdk/src/contracts/executor.ts @@ -6,7 +6,15 @@ import { type WebhookSourceDispatcher, } from "./webhooks.ts"; /** The shared Executor interface and remote client options; projected from ExecutorApi. */ -import { Context, type Effect, type Redacted, type Result, type Stream, Schema } from "effect"; +import { + Context, + type Duration, + type Effect, + type Redacted, + type Result, + type Stream, + Schema, +} from "effect"; import type { HttpApi, HttpApiEndpoint, HttpApiGroup } from "effect/http-api"; import type { WebhookSetupApi } from "./webhook-setup.ts"; import type { ExecutorApi } from "./http.ts"; @@ -308,6 +316,11 @@ export interface ExecutorInputs { * Without it, stale declarations revalidate first and revocation runs inline. */ readonly background?: import("./declarations.ts").BackgroundWork; + /** + * How long `owners.remove` spends asking providers to revoke the OAuth grants it deleted, all + * of them together; 5 minutes by default. Only a test host shortens it. + */ + readonly ownerRevocationBudget?: Duration.Input; } /** A hex-encoded 256-bit key encrypts saved credentials with AES-GCM; a custom store replaces that. */ diff --git a/packages/sdk/src/implementation/create.ts b/packages/sdk/src/implementation/create.ts index f36b07bd53..b086a673fb 100644 --- a/packages/sdk/src/implementation/create.ts +++ b/packages/sdk/src/implementation/create.ts @@ -285,7 +285,8 @@ export const createExecutor = ( activate: (input) => apps.activate(input).pipe(Effect.tap((app) => activated(app.id))), checkCredentials, }, - owners: makeOwners(db), + // The purge's caller waits for its revocations, so they never join background work. + owners: makeOwners(db, oauth.revokeGrant, options.ownerRevocationBudget), publications: catalog.publications, registry: catalog.registry, skills: makeSkills(db, runtime, crypto, declarations, blobs), diff --git a/packages/sdk/src/implementation/oauth.ts b/packages/sdk/src/implementation/oauth.ts index 62df2b085e..c9368db954 100644 --- a/packages/sdk/src/implementation/oauth.ts +++ b/packages/sdk/src/implementation/oauth.ts @@ -6,6 +6,7 @@ import { Array as Arr, Clock, Context, + type Duration, Effect, Exit, Fiber, @@ -3219,27 +3220,33 @@ export const makeOAuth = ( /** * Best-effort revocation of a grant whose account was already deleted. Nothing here can fail or - * undo the deletion. + * undo the deletion. `deadline` bounds this one revocation below the protocol's own request + * timeout; one that runs out is recorded as failed. */ - const revokeGrant = (removed: { - readonly account: AccountId; - readonly provider: string; - readonly encrypted: Uint8Array; - }) => - settledRevocation( - Effect.gen(function* () { - yield* Effect.annotateCurrentSpan("oauth.provider.id", removed.provider); - const stored = yield* decrypt(removed.account, removed.encrypted, OAuthGrant); - // A grant to the operator's client is revoked at the client's configured endpoint. - const grant = yield* operatingGrant(stored); - if (grant === undefined) return "unsupported" as const; - return yield* revokeTokens(grant, grantClientKind(stored), { - refreshToken: grant.grant === "client_credentials" ? undefined : grant.refreshToken, - accessToken: grant.fields["access_token"], - }); - }), + const revokeGrant = ( + removed: { + readonly account: AccountId; + readonly provider: string; + readonly encrypted: Uint8Array; + }, + deadline?: Duration.Input, + ) => { + const revocation = Effect.gen(function* () { + yield* Effect.annotateCurrentSpan("oauth.provider.id", removed.provider); + const stored = yield* decrypt(removed.account, removed.encrypted, OAuthGrant); + // A grant to the operator's client is revoked at the client's configured endpoint. + const grant = yield* operatingGrant(stored); + if (grant === undefined) return "unsupported" as const; + return yield* revokeTokens(grant, grantClientKind(stored), { + refreshToken: grant.grant === "client_credentials" ? undefined : grant.refreshToken, + accessToken: grant.fields["access_token"], + }); + }); + return settledRevocation( + deadline === undefined ? revocation : Effect.timeout(revocation, deadline), "oauth.revokeGrant", ); + }; /** Revoke after the deletion commits; see `revokeLater`. */ const revokeRemoved = (removed: Parameters[0]) => revokeLater(revokeGrant(removed)); @@ -3297,5 +3304,6 @@ export const makeOAuth = ( usableAll, usableEach, revokeRemoved, + revokeGrant, }; }; diff --git a/packages/sdk/src/implementation/owners.ts b/packages/sdk/src/implementation/owners.ts index bdebb77823..5dff581fbf 100644 --- a/packages/sdk/src/implementation/owners.ts +++ b/packages/sdk/src/implementation/owners.ts @@ -1,10 +1,11 @@ /** One transactional purge for an owner that no longer exists. */ -import { Effect } from "effect"; +import { type Duration, Effect, Option } from "effect"; import type { Executor } from "../contracts/executor.ts"; import { OwnerWebhooksActive } from "../contracts/owner.ts"; import { AppWorkflowsActive } from "../contracts/apps.ts"; import { AccountWorkflowsActive } from "../contracts/account.ts"; import { AccountId, OwnerId, WebhookId } from "../contracts/shared.ts"; +import type { RemovedGrant } from "./accounts.ts"; import { query, transaction, type Query } from "./database.ts"; import { removeToolSearch } from "./tool-search-store.ts"; @@ -35,8 +36,36 @@ const assertNoWorkInFlight = (tx: Query, owner: OwnerId, accountIds: ReadonlyArr } }); +/** How many removed grants are revoked at their providers at once. */ +const revocationConcurrency = 8; + +/** + * How long one revocation in a purge may take. A revocation is one small request that a working + * endpoint answers in well under a second. The protocol's 30-second request timeout, which a single + * account's removal keeps, covers every OAuth request rather than being chosen for this one; at that + * timeout a stalled provider would let a purge get through only 80 grants in the default budget. + */ +const revocationDeadline: Duration.Input = "10 seconds"; + +/** + * How long a purge spends revoking, all grants together, by default. Organization removal runs the + * purge as one durable step that Cloudflare Workflows ends at 10 minutes, and the purge's own + * transaction shares that step. With the deadline above, a provider that never answers still + * gets at least 240 revocation requests (all of them time out); a working one, thousands. + */ +const defaultRevocationBudget: Duration.Input = "5 minutes"; + /** Owner-keyed rows and the app/account-keyed rows that hang off them, deleted in dependency order. */ -export const makeOwners = (db: Query): Executor["owners"] => ({ +export const makeOwners = ( + db: Query, + /** + * Best-effort provider-side revocation, bounded by `deadline`; it never fails and runs only after + * the purge commits. + */ + revokeRemoved: (removed: RemovedGrant, deadline: Duration.Input) => Effect.Effect, + /** See `ExecutorInputs.ownerRevocationBudget`. */ + revocationBudget: Duration.Input = defaultRevocationBudget, +): Executor["owners"] => ({ check: (input: Parameters[0]) => transaction(db, (tx) => Effect.gen(function* () { @@ -53,161 +82,230 @@ export const makeOwners = (db: Query): Executor["owners"] => ({ }), ).pipe(Effect.withSpan("sdk.owners.check")), remove: (input: Parameters[0]) => - transaction(db, (tx) => - Effect.gen(function* () { - const owner = input.owner; - // Workflow start locks apps before accounts. Hold that same order through the purge. - yield* query(() => - tx.updateMany("apps", { where: (b) => b("owner", "=", owner), set: { owner } }), - ); - yield* query(() => - tx.updateMany("accounts", { where: (b) => b("owner", "=", owner), set: { owner } }), - ); - const apps = yield* query(() => - tx.findMany("apps", { select: ["id"], where: (b) => b("owner", "=", owner) }), - ); - const accounts = yield* query(() => - tx.findMany("accounts", { select: ["id"], where: (b) => b("owner", "=", owner) }), - ); - const webhooks = yield* query(() => - tx.findMany("webhooks", { - select: ["id", "status"], - where: (b) => b("owner", "=", owner), - }), - ); - // A registration still held at the provider is the caller's to remove; never abandon it. - const live = webhooks.filter((webhook) => webhook.status !== "stopped"); - if (live.length > 0) - return yield* new OwnerWebhooksActive({ - owner, - subscriptions: live.map((webhook) => WebhookId.make(webhook.id)), - }); - const appIds = apps.map((app) => app.id); - const accountIds = accounts.map((account) => account.id); - const webhookIds = webhooks.map((webhook) => webhook.id); - yield* assertNoWorkInFlight(tx, owner, accountIds); - const runs = yield* query(() => - tx.findMany("workflowRuns", { - select: ["id"], - where: (b) => b("owner", "=", owner), - }), - ); - if (runs.length > 0) { + Effect.gen(function* () { + const { removed, grants } = yield* transaction(db, (tx) => + Effect.gen(function* () { + const owner = input.owner; + // Workflow start locks apps before accounts. Hold that same order through the purge. yield* query(() => - tx.deleteMany("workflowAccounts", { - where: (b) => - b( - "run", - "in", - runs.map((run) => run.id), - ), - }), + tx.updateMany("apps", { where: (b) => b("owner", "=", owner), set: { owner } }), ); yield* query(() => - tx.deleteMany("workflowRuns", { where: (b) => b("owner", "=", owner) }), + tx.updateMany("accounts", { where: (b) => b("owner", "=", owner), set: { owner } }), ); - } - if (webhookIds.length > 0) { - yield* query(() => - tx.deleteMany("webhookAccounts", { - where: (b) => b("subscription", "in", webhookIds), + const apps = yield* query(() => + tx.findMany("apps", { select: ["id"], where: (b) => b("owner", "=", owner) }), + ); + const accounts = yield* query(() => + tx.findMany("accounts", { + select: ["id", "provider"], + where: (b) => b("owner", "=", owner), }), ); - yield* query(() => tx.deleteMany("webhooks", { where: (b) => b("owner", "=", owner) })); - } - // The due scan selects on schedule state alone, so a surviving schedule keeps - // claiming and failing forever. Delete by owner, not by app, so a schedule whose - // app row already went stays reachable. Same order as apps.remove. - yield* query(() => - tx.deleteMany("scheduledRuns", { where: (b) => b("owner", "=", owner) }), - ); - yield* query(() => tx.deleteMany("schedules", { where: (b) => b("owner", "=", owner) })); - // Webhook sources belong to the app owner; delete by owner for the same reason as schedules. - yield* query(() => - tx.deleteMany("webhookSources", { where: (b) => b("owner", "=", owner) }), - ); - // Event subscriptions too, so a subscription whose app row already went stays reachable. - const subscriptions = yield* query(() => - tx.findMany("eventSubscriptions", { - select: ["id"], - where: (b) => b("owner", "=", owner), - }), - ); - if (subscriptions.length > 0) { - yield* query(() => - tx.deleteMany("eventDeliveries", { - where: (b) => - b( - "subscription", - "in", - subscriptions.map((subscription) => subscription.id), - ), + const webhooks = yield* query(() => + tx.findMany("webhooks", { + select: ["id", "status"], + where: (b) => b("owner", "=", owner), }), ); - yield* query(() => - tx.deleteMany("eventSubscriptions", { where: (b) => b("owner", "=", owner) }), + // A registration still held at the provider is the caller's to remove; never abandon it. + const live = webhooks.filter((webhook) => webhook.status !== "stopped"); + if (live.length > 0) + return yield* new OwnerWebhooksActive({ + owner, + subscriptions: live.map((webhook) => WebhookId.make(webhook.id)), + }); + const appIds = apps.map((app) => app.id); + const accountIds = accounts.map((account) => account.id); + const webhookIds = webhooks.map((webhook) => webhook.id); + yield* assertNoWorkInFlight(tx, owner, accountIds); + const runs = yield* query(() => + tx.findMany("workflowRuns", { + select: ["id"], + where: (b) => b("owner", "=", owner), + }), ); - } - if (appIds.length > 0) { - yield* query(() => tx.deleteMany("events", { where: (b) => b("app", "in", appIds) })); - yield* query(() => tx.deleteMany("appRecords", { where: (b) => b("app", "in", appIds) })); + if (runs.length > 0) { + yield* query(() => + tx.deleteMany("workflowAccounts", { + where: (b) => + b( + "run", + "in", + runs.map((run) => run.id), + ), + }), + ); + yield* query(() => + tx.deleteMany("workflowRuns", { where: (b) => b("owner", "=", owner) }), + ); + } + if (webhookIds.length > 0) { + yield* query(() => + tx.deleteMany("webhookAccounts", { + where: (b) => b("subscription", "in", webhookIds), + }), + ); + yield* query(() => tx.deleteMany("webhooks", { where: (b) => b("owner", "=", owner) })); + } + // The due scan selects on schedule state alone, so a surviving schedule keeps + // claiming and failing forever. Delete by owner, not by app, so a schedule whose + // app row already went stays reachable. Same order as apps.remove. yield* query(() => - tx.deleteMany("accountChecks", { where: (b) => b("app", "in", appIds) }), + tx.deleteMany("scheduledRuns", { where: (b) => b("owner", "=", owner) }), ); - yield* removeToolSearch(tx, appIds); - yield* query(() => tx.deleteMany("apps", { where: (b) => b("owner", "=", owner) })); - } - if (accountIds.length > 0) { + yield* query(() => tx.deleteMany("schedules", { where: (b) => b("owner", "=", owner) })); + // Webhook sources belong to the app owner; delete by owner for the same reason as schedules. yield* query(() => - tx.deleteMany("accountChecks", { where: (b) => b("account", "in", accountIds) }), + tx.deleteMany("webhookSources", { where: (b) => b("owner", "=", owner) }), ); - yield* query(() => - tx.deleteMany("oauthGrants", { where: (b) => b("id", "in", accountIds) }), + // Event subscriptions too, so a subscription whose app row already went stays reachable. + const subscriptions = yield* query(() => + tx.findMany("eventSubscriptions", { + select: ["id"], + where: (b) => b("owner", "=", owner), + }), ); - yield* query(() => tx.deleteMany("accounts", { where: (b) => b("owner", "=", owner) })); - } - const connections = yield* query(() => - tx.findMany("accountConnections", { - select: ["id", "oauthAttempt"], - where: (b) => b("owner", "=", owner), - }), - ); - const attempts = connections - .map((connection) => connection.oauthAttempt) - .filter((attempt): attempt is string => attempt !== null); - if (attempts.length > 0) + if (subscriptions.length > 0) { + yield* query(() => + tx.deleteMany("eventDeliveries", { + where: (b) => + b( + "subscription", + "in", + subscriptions.map((subscription) => subscription.id), + ), + }), + ); + yield* query(() => + tx.deleteMany("eventSubscriptions", { where: (b) => b("owner", "=", owner) }), + ); + } + if (appIds.length > 0) { + yield* query(() => tx.deleteMany("events", { where: (b) => b("app", "in", appIds) })); + yield* query(() => + tx.deleteMany("appRecords", { where: (b) => b("app", "in", appIds) }), + ); + yield* query(() => + tx.deleteMany("accountChecks", { where: (b) => b("app", "in", appIds) }), + ); + yield* removeToolSearch(tx, appIds); + yield* query(() => tx.deleteMany("apps", { where: (b) => b("owner", "=", owner) })); + } + // The grants deleted here are revoked once the purge commits. A repeated purge finds none, + // so each grant is revoked at most once. + const grants: Array = []; + if (accountIds.length > 0) { + yield* query(() => + tx.deleteMany("accountChecks", { where: (b) => b("account", "in", accountIds) }), + ); + const stored = yield* query(() => + tx.findMany("oauthGrants", { + select: ["id", "encrypted"], + where: (b) => b("id", "in", accountIds), + }), + ); + const encrypted = new Map(stored.map((grant) => [grant.id, grant.encrypted])); + for (const account of accounts) { + const bytes = encrypted.get(account.id); + if (bytes !== undefined) + grants.push({ account: account.id, provider: account.provider, encrypted: bytes }); + } + yield* query(() => + tx.deleteMany("oauthGrants", { where: (b) => b("id", "in", accountIds) }), + ); + yield* query(() => tx.deleteMany("accounts", { where: (b) => b("owner", "=", owner) })); + } + const connections = yield* query(() => + tx.findMany("accountConnections", { + select: ["id", "oauthAttempt"], + where: (b) => b("owner", "=", owner), + }), + ); + const attempts = connections + .map((connection) => connection.oauthAttempt) + .filter((attempt): attempt is string => attempt !== null); + if (attempts.length > 0) + yield* query(() => + tx.deleteMany("oauthAttempts", { where: (b) => b("id", "in", attempts) }), + ); + if (connections.length > 0) + yield* query(() => + tx.deleteMany("accountConnections", { where: (b) => b("owner", "=", owner) }), + ); yield* query(() => - tx.deleteMany("oauthAttempts", { where: (b) => b("id", "in", attempts) }), + tx.deleteMany("toolApprovals", { where: (b) => b("owner", "=", owner) }), ); - if (connections.length > 0) + // Grants keep their own copy of a client, so other owners' accounts keep renewing. yield* query(() => - tx.deleteMany("accountConnections", { where: (b) => b("owner", "=", owner) }), + tx.deleteMany("storedOAuthClients", { where: (b) => b("owner", "=", owner) }), ); - yield* query(() => - tx.deleteMany("toolApprovals", { where: (b) => b("owner", "=", owner) }), - ); - // Grants keep their own copy of a client, so other owners' accounts keep renewing. - yield* query(() => - tx.deleteMany("storedOAuthClients", { where: (b) => b("owner", "=", owner) }), - ); - yield* query(() => - tx.deleteMany("storedOAuthClientCredentials", { where: (b) => b("owner", "=", owner) }), - ); - // Apps reference their active version, so retained code is removed last. - const versions = yield* query(() => - tx.findMany("deployments", { select: ["id"], where: (b) => b("owner", "=", owner) }), - ); - if (versions.length > 0) yield* query(() => - tx.deleteMany("deployments", { where: (b) => b("owner", "=", owner) }), + tx.deleteMany("storedOAuthClientCredentials", { where: (b) => b("owner", "=", owner) }), ); - return { - owner, - apps: appIds.length, - accounts: accountIds.length, - versions: versions.length, - connections: connections.length, - }; - }), - ).pipe(Effect.withSpan("sdk.owners.remove")), + // Apps reference their active version, so retained code is removed last. + const versions = yield* query(() => + tx.findMany("deployments", { select: ["id"], where: (b) => b("owner", "=", owner) }), + ); + if (versions.length > 0) + yield* query(() => + tx.deleteMany("deployments", { where: (b) => b("owner", "=", owner) }), + ); + return { + removed: { + owner, + apps: appIds.length, + accounts: accountIds.length, + versions: versions.length, + connections: connections.length, + }, + grants, + }; + }), + ); + // Revoke only after the purge is durable, and before the call returns: a durable caller + // such as organization removal ends its step here, and nothing would revoke a grant left to + // work the step does not wait for. The outcomes cannot change the result. + // + // The pass is bounded so it ends inside that step's time limit. When the budget runs out, + // revocations still in flight are cut off and grants not yet started are never revoked: + // their records are already deleted, so a retry finds nothing to revoke. Those tokens stay + // valid at the provider until it expires them, as every grant did before removal revoked + // any. The span and a warning log record how many, never which. + let started = 0; + let settled = 0; + const finished = yield* Effect.forEach( + grants, + (grant) => + Effect.suspend(() => { + started++; + // Counted only when it finishes: one the budget interrupts is cut off, not settled. + return revokeRemoved(grant, revocationDeadline).pipe( + Effect.andThen( + Effect.sync(() => { + settled++; + }), + ), + ); + }), + { concurrency: revocationConcurrency, discard: true }, + ).pipe(Effect.timeoutOption(revocationBudget)); + const counts = { + grants: grants.length, + settled, + cutOff: started - settled, + unattempted: grants.length - started, + }; + yield* Effect.annotateCurrentSpan({ + "oauth.revocation.grants": counts.grants, + "oauth.revocation.settled": counts.settled, + "oauth.revocation.cut_off": counts.cutOff, + "oauth.revocation.unattempted": counts.unattempted, + }); + if (Option.isNone(finished)) + yield* Effect.logWarning( + "Owner removal stopped revoking OAuth grants at its time budget; the rest stay valid at their providers", + ).pipe(Effect.annotateLogs(counts)); + return removed; + }).pipe(Effect.withSpan("sdk.owners.remove")), }); From 27fcf8a8b0923e61c192822a3a5b4f3f4edd5c5c Mon Sep 17 00:00:00 2001 From: Rhys Sullivan <39114868+RhysSullivan@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:51:17 +0000 Subject: [PATCH 04/68] Export ab006006 --- .../cloud/src/infrastructure/data-steps.ts | 46 +- .../cloud/src/infrastructure/runtime.ts | 20 +- .../src/implementation/executor-services.ts | 10 +- e2e/npm-packages.json | 39 + e2e/support/catalog-snapshots.json | 44 + e2e/support/managed-server.ts | 11 + e2e/support/public-catalogs.ts | 49 + e2e/test-plan.ts | 128 ++ e2e/tests/catalog-copy-rebuild.spec.ts | 1191 +++++++++++++++++ .../src/contracts/catalog-copy-rebuild.ts | 238 ++++ .../src/contracts/data-steps.ts | 65 +- packages/app-management/src/data-steps.ts | 7 + .../implementation/catalog-copy-rebuild.ts | 675 ++++++++++ .../implementation/catalog-copy-snapshots.ts | 547 ++++++++ .../implementation/catalog-copy-upgrade.ts | 483 +++++++ .../src/implementation/data-steps.ts | 85 +- .../src/implementation/host-data-steps.ts | 70 +- packages/sdk/src/contracts/executor.ts | 31 +- packages/sdk/src/contracts/runtime.ts | 6 +- packages/sdk/src/contracts/version.ts | 5 +- packages/sdk/src/core.ts | 2 + packages/sdk/src/implementation/apps.ts | 60 +- packages/sdk/src/implementation/create.ts | 8 + .../src/implementation/remote-app-runner.ts | 68 +- .../src/implementation/worker-source-map.ts | 5 +- .../sdk/src/implementation/workerd-client.ts | 42 +- packages/sdk/src/workerd.ts | 1 + scripts/catalog-copy-snapshots.commits | 47 + scripts/catalog-copy-snapshots.ts | 439 ++++++ scripts/e2e-npm-packages.ts | 4 +- 30 files changed, 4362 insertions(+), 64 deletions(-) create mode 100644 e2e/support/catalog-snapshots.json create mode 100644 e2e/tests/catalog-copy-rebuild.spec.ts create mode 100644 packages/app-management/src/contracts/catalog-copy-rebuild.ts create mode 100644 packages/app-management/src/implementation/catalog-copy-rebuild.ts create mode 100644 packages/app-management/src/implementation/catalog-copy-snapshots.ts create mode 100644 packages/app-management/src/implementation/catalog-copy-upgrade.ts create mode 100644 scripts/catalog-copy-snapshots.commits create mode 100644 scripts/catalog-copy-snapshots.ts diff --git a/apps/hosted/cloud/src/infrastructure/data-steps.ts b/apps/hosted/cloud/src/infrastructure/data-steps.ts index 5928c75b5c..3867d7c2fa 100644 --- a/apps/hosted/cloud/src/infrastructure/data-steps.ts +++ b/apps/hosted/cloud/src/infrastructure/data-steps.ts @@ -9,9 +9,14 @@ * Each tick's outcome counts the items it handled: `partial` or `failed` when some or all of them * ended with an outcome their step retries. A tick that only waited for a lease or a backoff, or * ran out of time, records `completed`. + * + * The catalog-copy rebuild applies in stages: `CLOUD_CATALOG_COPY_REBUILD_SCOPE` names the copies + * a stage may change (none when unset), and `CLOUD_CATALOG_COPY_REBUILD_PACE` the compiler builds + * one tick starts for it, in report and apply alike. See notes/catalog-copy-rebuild.md. */ import { AppManagementHost } from "@executor-js/app-management"; import { + catalogCopyRebuildScope, hostDataSteps, runDataSteps, type AgentGrantExpiry, @@ -31,6 +36,18 @@ import { jobUnitCounts } from "../contracts/job-outcome.ts"; /** A tick stops starting items after this long, then resumes from its cursor on the next tick. */ const tickBudgetMs = 20_000; +/** + * The compiler builds one tick starts for the catalog-copy rebuild when no deploy sets a pace. + * Measured on a test stage (notes/catalog-copy-rebuild.md, "Load"). + */ +const catalogCopyRebuildPace = 2; + +/** + * Retry passes before a catalog copy still failing is recorded `gave-up`: about 30 seconds, + * doubling to an hour, so about a day of retries. + */ +const catalogCopyRebuildPasses = 24; + /** * The last step that `apply` applies when no deploy names one. Steps after it report however * `CLOUD_DATA_STEPS` is set, so a new step ships in report mode even where earlier steps apply. @@ -68,6 +85,21 @@ export const cloudDataSteps = (agentGrants: AgentGrantExpiry) => Config.withDefault(""), ); const applyThrough = named === "" ? reviewedThrough : named; + const scopeText = yield* Config.String("CLOUD_CATALOG_COPY_REBUILD_SCOPE").pipe( + Config.withDefault(""), + ); + // An unreadable scope selects nothing rather than a guess at what was meant. + const scope = yield* catalogCopyRebuildScope(scopeText).pipe( + Effect.catchTag("CatalogCopyRebuildScopeInvalid", (error) => + Effect.logError("CLOUD_CATALOG_COPY_REBUILD_SCOPE cannot be read", error.token).pipe( + Effect.andThen(catalogCopyRebuildScope("")), + ), + ), + ); + const paceText = yield* Config.String("CLOUD_CATALOG_COPY_REBUILD_PACE").pipe( + Config.withDefault(""), + ); + const pace = /^\d+$/u.test(paceText) ? Number(paceText) : catalogCopyRebuildPace; // The build framework step rewrites retained builds in the same bucket the executor reads. const blobs = yield* cloudBlobs; return Effect.gen(function* () { @@ -82,6 +114,13 @@ export const cloudDataSteps = (agentGrants: AgentGrantExpiry) => agentGrants, executorAppRedeployed: executorDefaultRedeployed(wake), appCopies: hostedAppCopies(executor), + // Cloud lists the catalog-copy rebuild; it reports until a deploy names it (above). + catalogCopyRebuild: { + rebuilt: () => wake, + scope, + pace, + passes: catalogCopyRebuildPasses, + }, }); const run = (selected: typeof steps, selectedMode: typeof mode) => runDataSteps(selected, { @@ -104,7 +143,12 @@ export const cloudDataSteps = (agentGrants: AgentGrantExpiry) => : tickOutcome(applied); }).pipe( Effect.withSpan("job.data-steps", { - attributes: { "data_step.mode": mode, "data_step.apply_through": applyThrough }, + attributes: { + "data_step.mode": mode, + "data_step.apply_through": applyThrough, + "data_step.catalog_rebuild_run": scope.run, + "data_step.catalog_rebuild_pace": pace, + }, }), ); }).pipe(Effect.orDie); diff --git a/apps/hosted/cloud/src/infrastructure/runtime.ts b/apps/hosted/cloud/src/infrastructure/runtime.ts index 8e76aeff52..0937a75348 100644 --- a/apps/hosted/cloud/src/infrastructure/runtime.ts +++ b/apps/hosted/cloud/src/infrastructure/runtime.ts @@ -16,6 +16,7 @@ import { assembleWorkerBundle, declarationFailed, remoteAppRunner, + RunnerUnanswered, runsInFacet, } from "@executor-js/sdk/workerd"; import { HostRequirementsError, DeclaredRequirements, HostResponse } from "apps/contracts"; @@ -164,12 +165,18 @@ export const cloudRuntime = Effect.fn(function* ( duration: compilerDeadline, orElse: () => compilerDidNotAnswer, }), + // The compiler answers every build it judged, failed ones included; a call that + // failed without an answer is the host's failure, not the source's. Effect.catchTag("RpcCallError", (error) => { const cause = error.cause; return Effect.fail( cause instanceof Error && /^Worker exceeded memory limit\.?$/.test(cause.message) ? new BuildMemoryExceeded() - : failed("compile", cause instanceof Error ? cause : error), + : new RuntimeBuildFailed({ + stage: "compile", + message: describeBuildCause(cause instanceof Error ? cause : error), + unanswered: true, + }), ); }), // Builds share a compiler isolate, so another build can exhaust its memory. The @@ -199,8 +206,17 @@ export const cloudRuntime = Effect.fn(function* ( Effect.flatMap(Effect.fail), ), ), + // The runner answers every declaration it ran, the app's own failure included; a call + // that failed without an answer is the host's failure, not the source's. Its message + // is the same either way. Effect.mapError((cause) => - declarationFailed(cause, { mainModule: bundle.mainModule, sourceMap, files }), + cause instanceof RunnerUnanswered + ? declarationFailed( + cause.failure, + { mainModule: bundle.mainModule, sourceMap, files }, + true, + ) + : declarationFailed(cause, { mainModule: bundle.mainModule, sourceMap, files }), ), Effect.withSpan("runtime.cloud.requirements"), ); diff --git a/apps/hosted/self-host/src/implementation/executor-services.ts b/apps/hosted/self-host/src/implementation/executor-services.ts index 916f27d5e3..dc810f728f 100644 --- a/apps/hosted/self-host/src/implementation/executor-services.ts +++ b/apps/hosted/self-host/src/implementation/executor-services.ts @@ -1,7 +1,11 @@ import { hostedAppCapabilities } from "@executor-js/hosted-server/app-management"; import { executorSelfHostApiDocument } from "../contracts/api.ts"; import { AppGitOrigins, AppManagementHost } from "@executor-js/app-management"; -import { expireIdleAgentGrants, runStartupDataSteps } from "@executor-js/app-management/data-steps"; +import { + expireIdleAgentGrants, + runStartupDataSteps, + startupCatalogCopyRebuild, +} from "@executor-js/app-management/data-steps"; import { SelfHostAuth, selfHostAuth } from "../auth.ts"; /** Self-host SDK uses the same PGlite connection as Better Auth. */ import type { HostEgress } from "@executor-js/utils/url-policy"; @@ -161,6 +165,9 @@ export const selfHostExecutorServices = ( yield* Effect.forkScoped(deliverEvents(executor)); // The schema is current and nothing serves or builds yet; the caller holds the data lock. const auth = yield* selfHostAuth; + // Self-host applies at startup without a reviewed report, so the catalog-copy rebuild is + // listed only when its operator turns it on. + const catalogCopyRebuild = yield* startupCatalogCopyRebuild; yield* runStartupDataSteps( { executor, @@ -170,6 +177,7 @@ export const selfHostExecutorServices = ( // and its first pass reconciles the sources a redeploy left pending. executorAppRedeployed: executorDefaultRedeployed(Effect.void), appCopies: hostedAppCopies(executor), + ...(catalogCopyRebuild === undefined ? {} : { catalogCopyRebuild }), }, "private_hosted", ); diff --git a/e2e/npm-packages.json b/e2e/npm-packages.json index 78cb6532e7..761e825131 100644 --- a/e2e/npm-packages.json +++ b/e2e/npm-packages.json @@ -115,10 +115,25 @@ "range": "0.0.1-beta.84", "transitive": false }, + { + "name": "apps", + "range": "0.0.1-beta.88", + "transitive": false + }, { "name": "apps", "range": "0.0.1-beta.95", "transitive": false + }, + { + "name": "apps", + "range": "0.0.1-beta.100", + "transitive": false + }, + { + "name": "apps", + "range": "0.0.1-beta.140", + "transitive": false } ], "packages": { @@ -262,6 +277,14 @@ "@cloudflare/workers-types": "5.20260729.1" } }, + "0.0.1-beta.100": { + "tarball": "https://registry.npmjs.org/apps/-/apps-0.0.1-beta.100.tgz", + "integrity": "sha512-d7Gb2310EALNN9QEtSLm4Gq4oH2Iv4FXUowdItWmfLO3l5HHOqlGLq6PXp5SRTzotWcOILNck4mFn/E162g9Xw==", + "dependencies": { + "effect": "4.0.1", + "@cloudflare/workers-types": "5.20260729.1" + } + }, "0.0.1-beta.14": { "tarball": "https://registry.npmjs.org/apps/-/apps-0.0.1-beta.14.tgz", "integrity": "sha512-JuNza1zRwpcDAJ8B0jeREmVNWqLsiggQHO6sqhO5WdYjovu+/d4RKBxccJUmvHs/Yy5t46DLAKn9B/Awobn2nw==", @@ -271,6 +294,14 @@ "@cloudflare/workers-types": "5.20260729.1" } }, + "0.0.1-beta.140": { + "tarball": "https://registry.npmjs.org/apps/-/apps-0.0.1-beta.140.tgz", + "integrity": "sha512-qBpZnqwdxFYDxlVVHGxtHYADftrfn4aYiUkpvUXcvyvUPtBruttNqGD8zNWedY6/3LbUq5PMxks0Uq5bknmKVw==", + "dependencies": { + "effect": "4.1.4", + "@cloudflare/workers-types": "5.20260729.1" + } + }, "0.0.1-beta.2": { "tarball": "https://registry.npmjs.org/apps/-/apps-0.0.1-beta.2.tgz", "integrity": "sha512-eC6cfh4JLryjv8YEIWe7uApWVwh+be57zGNtyxLGGbp8IxYVJj0uwWaFcYMOvXpryZ7AVnWDXvX0fWUHrb/BSw==", @@ -332,6 +363,14 @@ "@cloudflare/workers-types": "5.20260729.1" } }, + "0.0.1-beta.88": { + "tarball": "https://registry.npmjs.org/apps/-/apps-0.0.1-beta.88.tgz", + "integrity": "sha512-XtgWhq0zPrz3VQkE7ox3aoqPyqp+zWOkqwUVHOPDoNQSOkM3uiEHhsfweWdOBLOYEJcts/ntovEzYIcufQHeeQ==", + "dependencies": { + "effect": "4.0.1", + "@cloudflare/workers-types": "5.20260729.1" + } + }, "0.0.1-beta.9": { "tarball": "https://registry.npmjs.org/apps/-/apps-0.0.1-beta.9.tgz", "integrity": "sha512-KHvpdK+dPRWLGWPnVpLcUs44QuYVBbBsVpbWgS6x3VSe2KEbGFPryvWDsIw2AUFxahqRAXiyRQC2S+zUpjshsA==", diff --git a/e2e/support/catalog-snapshots.json b/e2e/support/catalog-snapshots.json new file mode 100644 index 0000000000..5797a34953 --- /dev/null +++ b/e2e/support/catalog-snapshots.json @@ -0,0 +1,44 @@ +{ + "popupsmart-2026-10-13": { + "package": "@executor.sh/popupsmart", + "files": [ + { + "path": "README.md", + "content": "# Popupsmart\n\nExports the leads collected by a Popupsmart popup campaign (form data, UTM metadata and trigger integrations) through one `listLeads` tool with date filters and `take`/`skip` paging.\n\nInterface: hand-written tool over Popupsmart's official lead-export API, `GET https://app.popupsmart.com/api/leads`, documented at https://popupsmart.com/help/detail/how-to-auto-download-leads-using-an-api. Popupsmart publishes no OpenAPI document, GraphQL API or MCP server.\n\nAuth: API key. Copy it from the Popupsmart dashboard under personal data > API key; it is sent as the `x-token` header. The campaign ID (also from the dashboard) is passed per call as `campaignId`, sent as `x-campaign-id`. There is no OAuth.\n\nKnown gaps: the API only reads leads, so there are no mutations. The vendor returns the last 1 day by default and at most 90 days per request. The health check cannot validate the key against a real campaign, so it only fails on a 401.\n" + }, + { + "path": "icon.ts", + "content": "import type { AppIcon } from \"apps\";\n\n// Generated by scripts/icon.ts from the vendor's logo.\nexport const icons: readonly AppIcon[] = [\n {\n \"src\": \"data:image/svg+xml;base64,PHN2Zwp4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCndpZHRoPSIxZW0iCmhlaWdodD0iMWVtIgp2aWV3Qm94PSIwIDAgNjAgNjAiCmZpbGw9IiMwMDk3ZmYiCj4KPHBhdGgKICBpZD0icG9wdXBzbWFydCIKICBkPSJNNTYuNjI3LDEyLjI3OWEyMi40NDEsMjIuNDQxLDAsMCwwLTkuNTQ5LTkuMDc0Yy00LjEyMi0yLjA4OC04Ljk1MS0zLjItMTUuNzIyLTMuMkgyOC42NDRjLTYuNzY5LDAtMTEuNiwxLjExMi0xNS43MiwzLjJhMjIuNDI1LDIyLjQyNSwwLDAsMC05LjU1MSw5LjA3MkMxLjE3NCwxNi4xOTEsMCwyMC43ODMsMCwyNy4yMTR2NS41NzhjMCw2LjQzNCwxLjE3MywxMS4wMjQsMy4zNzMsMTQuOTM0QTIyLjQxMiwyMi40MTIsMCwwLDAsMTIuOTI0LDU2LjhjNC4xMiwyLjA5NCw4Ljk0OSwzLjIwNiwxNS43MiwzLjIwNmgyLjcxMWM2Ljc3MSwwLDExLjYtMS4xMTIsMTUuNzItMy4yMDZhMjIuNDI3LDIyLjQyNywwLDAsMCw5LjU1MS05LjA3MmMyLjItMy45MSwzLjM3My04LjUsMy4zNzMtMTQuOTM0VjI3LjIxNkM2MCwyMC43OCw1OC44MjcsMTYuMTksNTYuNjI3LDEyLjI3OVpNMzAsNDUuMDA2Yy0uMjM3LDAtLjQ3My0uMDA1LS43MDgtLjAxNWwtLjIxMS0uMDEyYy0uMTQtLjAwOC0uMjgtLjAxOS0uNDE5LS4wMzEtLjEyMy0uMDExLS4yNDUtLjAyMi0uMzY3LS4wMzZsLS4xOTEtLjAyNGExNC45NzksMTQuOTc5LDAsMCwxLTIuNjcyLS41OVY0NC4zYTE0Ljg2MSwxNC44NjEsMCwwLDEtNi4yOTQtMy45NTUsMS40MDYsMS40MDYsMCwxLDAtMi4wMzYsMS45NCwxNy42NDgsMTcuNjQ4LDAsMCwwLDguMzMsNC45NDR2LjM1NGE1LjIxNCw1LjIxNCwwLDEsMS0xMC40MjgsMFYzMC4wNDZjMC0uMDEzLDAtLjAyNiwwLS4wMzlhMTUsMTUsMCwxLDEsMTUsMTVaIgogIHRyYW5zZm9ybT0idHJhbnNsYXRlKDAgLTAuMDA1KSIKLz4KPC9zdmc+\",\n \"mimeType\": \"image/svg+xml\"\n }\n];\n" + }, + { + "path": "index.ts", + "content": "import {\n accountRouter,\n decodeJson,\n defineApp,\n defineProvider,\n json,\n object,\n query,\n router,\n secrets,\n string,\n} from \"apps\";\nimport { icons } from \"./icon.js\";\n\nconst base = \"https://app.popupsmart.com/api/leads\";\n\nconst popupsmart = defineProvider({\n name: \"Popupsmart\",\n hosts: [\"app.popupsmart.com\"],\n auth: {\n apiKey: secrets({\n label: \"API key\",\n fields: object({ token: string({ minLength: 1 }) }),\n }),\n },\n // Every endpoint also needs a campaign id, which is a per-call input here, so the key alone cannot be\n // fully checked. Request one lead for a placeholder campaign; only a 401 means the key itself is bad.\n async health({ account, fetch, signal }) {\n const response = await fetch(`${base}?take=1`, {\n signal,\n headers: { \"x-token\": account.fields.token, \"x-campaign-id\": \"health-check\" },\n });\n if (response.status === 401) throw new Error(\"Popupsmart rejected the API key (401)\");\n },\n});\n\ntype Fetch = typeof fetch;\n\nfunction build(token: string, fetcher: Fetch, signal: AbortSignal | undefined) {\n return router({\n listLeads: query(\n {\n description:\n \"List the leads collected by one Popupsmart campaign. campaignId is the campaign's ID from the Popupsmart dashboard. Each lead has formData (the submitted fields), meta (UTM parameters) and triggerIntegrations. Optional filters, pass an empty string to omit: startDate and endDate as YYYY-MM-DD (the vendor defaults to the last 1 day and allows at most 90 days); take is the page size as a number string (default 50); skip is the number of leads to skip (default 0). Page by increasing skip by take.\",\n input: object({\n campaignId: string({ minLength: 1 }),\n startDate: string(),\n endDate: string(),\n take: string(),\n skip: string(),\n }),\n },\n async (_ctx, { campaignId, startDate, endDate, take, skip }) => {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries({ startDate, endDate, take, skip })) {\n if (value !== \"\") params.set(key, value);\n }\n const qs = params.toString();\n const response = await fetcher(qs === \"\" ? base : `${base}?${qs}`, {\n signal,\n headers: { \"x-token\": token, \"x-campaign-id\": campaignId },\n });\n return decodeJson(response, json());\n },\n ),\n });\n}\n\nexport default defineApp(\n { accounts: { popupsmart: popupsmart.many() }, icons },\n async ({ accounts, fetch, signal }) => ({\n tools: router(\n await accountRouter(accounts.popupsmart, (account) => build(account.fields.token, fetch, signal), { signal }),\n {\n title: \"Popupsmart\",\n description: \"Export the leads collected by a Popupsmart popup campaign.\",\n icons,\n },\n ),\n }),\n);\n" + }, + { + "path": "package.json", + "content": "{\n \"name\": \"@executor.sh/popupsmart\",\n \"description\": \"Export the leads collected by a Popupsmart popup campaign: form data, UTM metadata and trigger integrations.\",\n \"private\": true,\n \"type\": \"module\",\n \"dependencies\": {\n \"apps\": \"0.0.1-beta.88\"\n },\n \"executor\": {\n \"title\": \"Popupsmart\"\n }\n}\n" + } + ] + }, + "popupsmart-2026-11-17": { + "package": "@executor.sh/popupsmart", + "files": [ + { + "path": "README.md", + "content": "# Popupsmart\n\nExports the leads collected by a Popupsmart popup campaign (form data, UTM metadata and trigger integrations) through one `listLeads` tool with date filters and `take`/`skip` paging.\n\nInterface: hand-written tool over Popupsmart's official lead-export API, `GET https://app.popupsmart.com/api/leads`, documented at https://popupsmart.com/help/detail/how-to-auto-download-leads-using-an-api. Popupsmart publishes no OpenAPI document, GraphQL API or MCP server.\n\nAuth: API key. Copy it from the Popupsmart dashboard under personal data > API key; it is sent as the `x-token` header. The campaign ID (also from the dashboard) is passed per call as `campaignId`, sent as `x-campaign-id`. There is no OAuth.\n\nKnown gaps: the API only reads leads, so there are no mutations. The vendor returns the last 1 day by default and at most 90 days per request. The health check cannot validate the key against a real campaign, so it only fails on a 401.\n" + }, + { + "path": "icon.ts", + "content": "import type { AppIcon } from \"apps\";\n\n// Generated by scripts/icon.ts from the vendor's logo.\nexport const icons: readonly AppIcon[] = [\n {\n \"src\": \"data:image/svg+xml;base64,PHN2Zwp4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCndpZHRoPSIxZW0iCmhlaWdodD0iMWVtIgp2aWV3Qm94PSIwIDAgNjAgNjAiCmZpbGw9IiMwMDk3ZmYiCj4KPHBhdGgKICBpZD0icG9wdXBzbWFydCIKICBkPSJNNTYuNjI3LDEyLjI3OWEyMi40NDEsMjIuNDQxLDAsMCwwLTkuNTQ5LTkuMDc0Yy00LjEyMi0yLjA4OC04Ljk1MS0zLjItMTUuNzIyLTMuMkgyOC42NDRjLTYuNzY5LDAtMTEuNiwxLjExMi0xNS43MiwzLjJhMjIuNDI1LDIyLjQyNSwwLDAsMC05LjU1MSw5LjA3MkMxLjE3NCwxNi4xOTEsMCwyMC43ODMsMCwyNy4yMTR2NS41NzhjMCw2LjQzNCwxLjE3MywxMS4wMjQsMy4zNzMsMTQuOTM0QTIyLjQxMiwyMi40MTIsMCwwLDAsMTIuOTI0LDU2LjhjNC4xMiwyLjA5NCw4Ljk0OSwzLjIwNiwxNS43MiwzLjIwNmgyLjcxMWM2Ljc3MSwwLDExLjYtMS4xMTIsMTUuNzItMy4yMDZhMjIuNDI3LDIyLjQyNywwLDAsMCw5LjU1MS05LjA3MmMyLjItMy45MSwzLjM3My04LjUsMy4zNzMtMTQuOTM0VjI3LjIxNkM2MCwyMC43OCw1OC44MjcsMTYuMTksNTYuNjI3LDEyLjI3OVpNMzAsNDUuMDA2Yy0uMjM3LDAtLjQ3My0uMDA1LS43MDgtLjAxNWwtLjIxMS0uMDEyYy0uMTQtLjAwOC0uMjgtLjAxOS0uNDE5LS4wMzEtLjEyMy0uMDExLS4yNDUtLjAyMi0uMzY3LS4wMzZsLS4xOTEtLjAyNGExNC45NzksMTQuOTc5LDAsMCwxLTIuNjcyLS41OVY0NC4zYTE0Ljg2MSwxNC44NjEsMCwwLDEtNi4yOTQtMy45NTUsMS40MDYsMS40MDYsMCwxLDAtMi4wMzYsMS45NCwxNy42NDgsMTcuNjQ4LDAsMCwwLDguMzMsNC45NDR2LjM1NGE1LjIxNCw1LjIxNCwwLDEsMS0xMC40MjgsMFYzMC4wNDZjMC0uMDEzLDAtLjAyNiwwLS4wMzlhMTUsMTUsMCwxLDEsMTUsMTVaIgogIHRyYW5zZm9ybT0idHJhbnNsYXRlKDAgLTAuMDA1KSIKLz4KPC9zdmc+\",\n \"mimeType\": \"image/svg+xml\"\n }\n];\n" + }, + { + "path": "index.ts", + "content": "import {\n accountRouter,\n decodeJson,\n defineApp,\n defineProvider,\n json,\n object,\n query,\n router,\n secrets,\n string,\n} from \"apps\";\nimport { icons } from \"./icon.js\";\n\nconst base = \"https://app.popupsmart.com/api/leads\";\n\nconst popupsmart = defineProvider({\n name: \"Popupsmart\",\n hosts: [\"app.popupsmart.com\"],\n auth: {\n apiKey: secrets({\n label: \"API key\",\n fields: object({ token: string({ minLength: 1 }) }),\n }),\n },\n // Every endpoint also needs a campaign id, which is a per-call input here, so the key alone cannot be\n // fully checked. Request one lead for a placeholder campaign; only a 401 means the key itself is bad.\n async health({ account, fetch, signal }) {\n const response = await fetch(`${base}?take=1`, {\n signal,\n headers: { \"x-token\": account.fields.token, \"x-campaign-id\": \"health-check\" },\n });\n if (response.status === 401) throw new Error(\"Popupsmart rejected the API key (401)\");\n },\n});\n\ntype Fetch = typeof fetch;\n\nfunction build(token: string, fetcher: Fetch, signal: AbortSignal | undefined) {\n return router({\n listLeads: query(\n {\n description:\n \"List the leads collected by one Popupsmart campaign. campaignId is the campaign's ID from the Popupsmart dashboard. Each lead has formData (the submitted fields), meta (UTM parameters) and triggerIntegrations. Optional filters, pass an empty string to omit: startDate and endDate as YYYY-MM-DD (the vendor defaults to the last 1 day and allows at most 90 days); take is the page size as a number string (default 50); skip is the number of leads to skip (default 0). Page by increasing skip by take.\",\n input: object({\n campaignId: string({ minLength: 1 }),\n startDate: string(),\n endDate: string(),\n take: string(),\n skip: string(),\n }),\n },\n async (_ctx, { campaignId, startDate, endDate, take, skip }) => {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries({ startDate, endDate, take, skip })) {\n if (value !== \"\") params.set(key, value);\n }\n const qs = params.toString();\n const response = await fetcher(qs === \"\" ? base : `${base}?${qs}`, {\n signal,\n headers: { \"x-token\": token, \"x-campaign-id\": campaignId },\n });\n return decodeJson(response, json());\n },\n ),\n });\n}\n\nexport default defineApp(\n { user: { accounts: { popupsmart: popupsmart.many() } }, icons },\n async ({ user, fetch, signal }) => ({\n tools: router(\n await accountRouter(user?.accounts.popupsmart ?? [], (account) => build(account.fields.token, fetch, signal), { signal }),\n {\n title: \"Popupsmart\",\n description: \"Export the leads collected by a Popupsmart popup campaign.\",\n icons,\n },\n ),\n }),\n);\n" + }, + { + "path": "package.json", + "content": "{\n \"name\": \"@executor.sh/popupsmart\",\n \"description\": \"Export the leads collected by a Popupsmart popup campaign: form data, UTM metadata and trigger integrations.\",\n \"private\": true,\n \"type\": \"module\",\n \"dependencies\": {\n \"apps\": \"0.0.1-beta.100\"\n },\n \"executor\": {\n \"title\": \"Popupsmart\"\n }\n}\n" + } + ] + } +} diff --git a/e2e/support/managed-server.ts b/e2e/support/managed-server.ts index f7fe5dae7a..2edafee1ac 100644 --- a/e2e/support/managed-server.ts +++ b/e2e/support/managed-server.ts @@ -64,6 +64,17 @@ export const OperatorSettings = Schema.Struct({ EXECUTOR_OAUTH_CLIENT_METADATA_URL: Schema.optionalKey(Schema.NonEmptyString), /** The build an upgrade installs. */ EXECUTOR_BUILD_VERSION: Schema.optionalKey(Schema.NonEmptyString), + /** The npm registry builds install from, as when an operator's mirror is out of reach. */ + EXECUTOR_NPM_REGISTRY: Schema.optionalKey(Schema.NonEmptyString), + /** + * E2E only: the product's calls to its compiler fail as a lost connection does, for every build + * (`all`) or only builds a deploy keeps (`retained`). An empty value ends the outage. + */ + EXECUTOR_TEST_COMPILER_UNAVAILABLE: Schema.optionalKey(Schema.Literals(["all", "retained", ""])), + /** The copies the next start's catalog-copy rebuild stage may change; unset, every copy. */ + EXECUTOR_CATALOG_COPY_REBUILD_SCOPE: Schema.optionalKey(Schema.String), + /** E2E only: the most compiler builds each start's catalog-copy rebuild starts, as Cloud's pace. */ + EXECUTOR_TEST_CATALOG_COPY_REBUILD_PACE: Schema.optionalKey(Schema.NonEmptyString), /** * The operator's OAuth clients (notes/oauth.md, "First-party clients"): test client definitions * an E2E host adds to the reviewed ones, and the credentials of the clients scenarios turn on. diff --git a/e2e/support/public-catalogs.ts b/e2e/support/public-catalogs.ts index 8bc4d111fb..5024988430 100644 --- a/e2e/support/public-catalogs.ts +++ b/e2e/support/public-catalogs.ts @@ -11,6 +11,7 @@ import { Effect, Layer } from "effect"; import { HttpRouter, HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http"; import { createServer } from "node:http"; import { appsVersion } from "./apps-release.ts"; +import snapshots from "./catalog-snapshots.json" with { type: "json" }; const icon = (fill: string) => ``; @@ -111,8 +112,56 @@ export default defineApp({ user: { accounts: { tracker: tracker.many() } } }, as })); `; +type SnapshotFile = { readonly path: string; readonly content: string }; + +/** + * Real catalog sources from the integrations repository's history, byte for byte + * (`catalog-snapshots.json`): Popupsmart as the feed served it on 2026-10-13 (apps beta.88) and + * on 2026-11-17 (beta.100, the catalog's own move of the same source). The feed serves them by ID + * but does not list them, so the catalog scenarios see only the synthetic apps. + * catalog-copy-rebuild.spec.ts installs them, plus two stand-ins: the October source with an + * edited README, which is no published snapshot, and the October source under the package name + * of a package whose tool names change on beta.140. + */ +export const catalogSnapshots = { + october: { id: "popupsmart-2026-10-13", package: "@executor.sh/popupsmart" }, + november: { id: "popupsmart-2026-11-17", package: "@executor.sh/popupsmart" }, + altered: { id: "popupsmart-altered", package: "@executor.sh/popupsmart" }, + held: { id: "netsapiens-stand-in", package: "@executor.sh/netsapiens" }, +} as const; +const october: ReadonlyArray = snapshots["popupsmart-2026-10-13"].files; +/** The snapshot files of `id`, as the feed serves them. */ +export const catalogSnapshotFiles = ( + id: (typeof catalogSnapshots)[keyof typeof catalogSnapshots]["id"], +): ReadonlyArray => + id === catalogSnapshots.october.id + ? october + : id === catalogSnapshots.november.id + ? snapshots["popupsmart-2026-11-17"].files + : id === catalogSnapshots.altered.id + ? october.map((file) => + file.path === "README.md" ? { ...file, content: `${file.content}\nEdited.\n` } : file, + ) + : october.map((file) => + file.path === "package.json" + ? { + ...file, + content: file.content.replace( + `"${catalogSnapshots.october.package}"`, + `"${catalogSnapshots.held.package}"`, + ), + } + : file, + ); + /** Each app's complete source, as the feed serves it. */ const catalogSources: Readonly> = { + ...Object.fromEntries( + Object.values(catalogSnapshots).map((snapshot) => [ + `apps/${snapshot.id}.json`, + { package: snapshot.package, files: catalogSnapshotFiles(snapshot.id) }, + ]), + ), [officialApps.mail.source]: { package: officialApps.mail.package, files: [ diff --git a/e2e/test-plan.ts b/e2e/test-plan.ts index 5be9f4407e..9d2067f5b5 100644 --- a/e2e/test-plan.ts +++ b/e2e/test-plan.ts @@ -6581,6 +6581,134 @@ export const scenarios = plan({ ), }, }, + catalogCopyRebuild: { + fixtures: "actors", + legacyStorage: true, + serverEnvironment: { EXECUTOR_DATA_STEPS: "report", EXECUTOR_CATALOG_COPY_REBUILD: "on" }, + file: "catalog-copy-rebuild.spec.ts", + title: + "Untouched catalog copies are rebuilt once on beta.140 from their own source, and a report writes nothing", + targets: { + "self-host": scheduled, + cloud: na( + "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", + ), + local: na("Local never lists the catalog copy rebuild."), + }, + }, + catalogCopyRebuildUnreachableRegistry: { + fixtures: "actors", + serverEnvironment: { EXECUTOR_DATA_STEPS: "report", EXECUTOR_CATALOG_COPY_REBUILD: "on" }, + file: "catalog-copy-rebuild.spec.ts", + title: + "A catalog copy rebuild that cannot reach the npm registry is retried at the next start, not skipped", + targets: { + "self-host": scheduled, + cloud: na( + "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", + ), + local: na("Local never lists the catalog copy rebuild."), + }, + }, + catalogCopyRebuildCompilerUnavailable: { + fixtures: "actors", + serverEnvironment: { EXECUTOR_DATA_STEPS: "report", EXECUTOR_CATALOG_COPY_REBUILD: "on" }, + file: "catalog-copy-rebuild.spec.ts", + title: + "A catalog copy rebuild whose compiler does not answer is retried at the next start, not skipped", + targets: { + "self-host": scheduled, + cloud: na( + "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", + ), + local: na("Local never lists the catalog copy rebuild."), + }, + }, + catalogCopyRebuildConcurrentActivation: { + fixtures: "actors", + legacyStorage: true, + serverEnvironment: { EXECUTOR_DATA_STEPS: "report", EXECUTOR_CATALOG_COPY_REBUILD: "on" }, + file: "catalog-copy-rebuild.spec.ts", + title: "A catalog copy rebuild never deploys over a version activated while it builds", + targets: { + "self-host": scheduled, + cloud: na( + "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", + ), + local: na("Local never lists the catalog copy rebuild."), + }, + }, + catalogCopyRebuildInterrupted: { + fixtures: "actors", + serverEnvironment: { EXECUTOR_DATA_STEPS: "report", EXECUTOR_CATALOG_COPY_REBUILD: "on" }, + file: "catalog-copy-rebuild.spec.ts", + title: + "A catalog copy rebuild stopped after its deploy is finished by the next start, not redeployed", + targets: { + "self-host": scheduled, + cloud: na( + "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", + ), + local: na("Local never lists the catalog copy rebuild."), + }, + }, + catalogCopyRebuildStaged: { + fixtures: "actors", + serverEnvironment: { EXECUTOR_DATA_STEPS: "report", EXECUTOR_CATALOG_COPY_REBUILD: "on" }, + file: "catalog-copy-rebuild.spec.ts", + title: + "A catalog copy rebuild applies only to its stage's scope, and a wider stage rebuilds the copies left", + targets: { + "self-host": scheduled, + cloud: na( + "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", + ), + local: na("Local never lists the catalog copy rebuild."), + }, + }, + catalogCopyRebuildGivesUp: { + fixtures: "actors", + serverEnvironment: { EXECUTOR_DATA_STEPS: "report", EXECUTOR_CATALOG_COPY_REBUILD: "on" }, + file: "catalog-copy-rebuild.spec.ts", + title: + "A catalog copy rebuild whose registry never comes back gives up after three starts, and the next stage tries again", + targets: { + "self-host": scheduled, + cloud: na( + "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", + ), + local: na("Local never lists the catalog copy rebuild."), + }, + }, + catalogCopyRebuildPaced: { + fixtures: "actors", + serverEnvironment: { EXECUTOR_DATA_STEPS: "report", EXECUTOR_CATALOG_COPY_REBUILD: "on" }, + file: "catalog-copy-rebuild.spec.ts", + title: + "A paced catalog copy rebuild starts no more compiler builds per run than its pace, and deploys a copy it stopped after its check at the next run", + targets: { + "self-host": scheduled, + cloud: na( + "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", + ), + local: na("Local never lists the catalog copy rebuild."), + }, + }, + catalogCopyRebuildIntentKept: { + fixtures: "actors", + legacyStorage: true, + serverEnvironment: { EXECUTOR_DATA_STEPS: "report", EXECUTOR_CATALOG_COPY_REBUILD: "on" }, + file: "catalog-copy-rebuild.spec.ts", + title: + "A catalog copy rebuild left part way stays to be finished when the app cannot be read, through the retry bound and into a stage that does not name it", + targets: { + "self-host": scheduled, + cloud: na( + "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", + ), + local: na("Local never lists the catalog copy rebuild."), + }, + }, buildFrameworkMigration: { fixtures: "actors", serverEnvironment: { EXECUTOR_DATA_STEPS: "report" }, diff --git a/e2e/tests/catalog-copy-rebuild.spec.ts b/e2e/tests/catalog-copy-rebuild.spec.ts new file mode 100644 index 0000000000..2760cc6e20 --- /dev/null +++ b/e2e/tests/catalog-copy-rebuild.spec.ts @@ -0,0 +1,1191 @@ +/** + * Installed catalog copies keep the `apps` framework they were built with, so a framework fix + * (E-042's account merge, in beta.140) never reaches them. The one-off + * `13_rebuild_catalog_copies_on_current_apps` data step rebuilds untouched copies from their own + * installed source on beta.140 with only the reviewed upgrade, and leaves every other copy alone. + * + * Self-host lists the step only when its operator turns it on; these scenarios start the product + * with it on and data steps held in report mode. They install real Popupsmart sources from the + * catalog's history through the official feed: the October source (beta.88, before requirements + * had scopes) and the November source (beta.100). + * + * The first scenario adds the October source redeployed with an edit, and with an edit committed + * to `main`; the October source with an edited README, which is no published snapshot; a stand-in + * for a package whose tool names change on beta.140; a synthetic app on the host's release; and a + * copy of an app the organization deployed itself under a catalog package's name, which is no + * catalog install. A report start writes nothing: the rows of every table the step could touch + * hash the same before and after it. An apply start rebuilds the two untouched copies to exactly + * the files the catalog's own move to beta.100 wrote, with the pin on beta.140, and keeps their + * requirements, provider IDs, linked accounts and tools (names, descriptions, output schemas and + * the input each account takes); every other copy is unchanged. Activating the replaced version + * restores the October source with the same accounts and tools, and a later start changes + * nothing. + * + * The others break an apply part way, as the product's own storage and network can: an npm + * registry out of reach, a compiler that does not answer, an activation that lands while the step + * builds, and a `main` commit that fails after the deploy. Each copy is left as its owner would expect, and the next start finishes + * what the step began, even when that start's stage no longer covers it. + * + * Apply runs in stages. Each scope the operator sets is its own run: copies outside it are left + * exactly as they were and stay eligible, a finished stage does not run again, and a wider stage + * rebuilds the rest. An outage that never ends gives up after three starts, so the host finishes + * its data steps; the next stage tries those copies again. A copy left part way stays to be + * finished through a failed read, the bound and a stage that does not name it. + * + * A paced run (an e2e-only setting on self-host, as Cloud paces each tick) starts no more compiler + * builds than its pace: at one build a start, a copy is checked at one start and deployed at the + * next. + */ +import { expect, layer } from "@effect/vitest"; +import { Config, Effect, FileSystem, Schema } from "effect"; +import { createHash, randomUUID } from "node:crypto"; +import { scenarios } from "../test-plan.ts"; +import { Api, body } from "../support/api.ts"; +import { Actors } from "../support/actors.ts"; +import { HostedLive, withHostedCase } from "../support/case.ts"; +import { Target } from "../support/platform.ts"; +import { Committed, Workspace } from "../support/app-authoring.ts"; +import { serverControl } from "../support/server-control.ts"; +import { dataStepSummaries, nextDataStepSummary } from "../support/data-steps.ts"; +import { appsVersion, declaredApps } from "../support/apps-release.ts"; +import { legacyStorage } from "../support/legacy-storage.ts"; +import { Resource } from "../support/contracts.ts"; +import { linkedAccountIds } from "../support/app-accounts.ts"; +import { + catalogSnapshotFiles, + catalogSnapshots, + officialApps, +} from "../support/public-catalogs.ts"; + +const step = "13_rebuild_catalog_copies_on_current_apps"; +/** The release the step rebuilds on. */ +const targetRelease = "0.0.1-beta.140"; +const october = "0.0.1-beta.88"; +const november = "0.0.1-beta.100"; + +/** The journal run of the apply stage with this scope, named as the product names it. */ +const stageRun = (scope: string) => { + const tokens = [...new Set(scope.split(/[\s,]+/u).filter((token) => token !== ""))].toSorted(); + const hex = createHash("sha256").update(tokens.join(" ")).digest("hex").slice(0, 16); + return `apply:scope-${hex}`; +}; + +type Files = ReadonlyArray<{ readonly path: string; readonly content: string }>; +const sorted = (files: Files) => files.toSorted((left, right) => (left.path < right.path ? -1 : 1)); +/** `files` with only the manifest's `apps` release changed, in place. */ +const repinned = (files: Files, from: string, to: string): Files => + files.map((file) => + file.path === "package.json" + ? { ...file, content: file.content.replace(`"apps": "${from}"`, `"apps": "${to}"`) } + : file, + ); +/** What a rebuilt October or November copy runs and holds on `main`: the catalog's own move. */ +const rebuiltFiles = () => + sorted(repinned(catalogSnapshotFiles(catalogSnapshots.november.id), november, targetRelease)); +const octoberFiles = () => sorted(catalogSnapshotFiles(catalogSnapshots.october.id)); + +const Requirement = Schema.Struct({ + provider: Schema.String, + scope: Schema.String, + cardinality: Schema.String, +}); +const App = Schema.Struct({ + id: Schema.String, + code: Schema.String, + name: Schema.String, + activeVersion: Schema.NullOr(Schema.String), + requirements: Schema.Struct({ accounts: Schema.Record(Schema.String, Requirement) }), +}); +type App = typeof App.Type; +const Versions = Schema.Array(Schema.Struct({ id: Schema.String })); +const RunningSource = Schema.Struct({ + files: Schema.Array(Schema.Struct({ path: Schema.String, content: Schema.String })), +}); +/** A page of the tool listing: each tool's name, kind, description and schemas. */ +const Tools = Schema.Struct({ + items: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)), + next: Schema.optional(Schema.String), +}); +const Sum = Schema.Struct({ sum: Schema.String }); + +type Json = { readonly [key: string]: unknown }; +const isObject = (value: unknown): value is Json => + typeof value === "object" && value !== null && !Array.isArray(value); +/** JSON with object keys sorted and empty `$defs` left out, so equal schemas compare equal. */ +const canonical = (value: unknown): unknown => + Array.isArray(value) + ? value.map(canonical) + : isObject(value) + ? Object.fromEntries( + Object.entries(value) + .filter( + ([key, item]) => + !(key === "$defs" && isObject(item) && Object.keys(item).length === 0), + ) + .toSorted(([left], [right]) => (left < right ? -1 : 1)) + .map(([key, item]) => [key, canonical(item)]), + ) + : value; +/** + * An account router's input schema as account ID -> the input that account takes. Each branch + * names its accounts as `accountId`'s `const` or `enum`. + */ +const inputsByAccount = (schema: unknown) => { + const branches = isObject(schema) && Array.isArray(schema.anyOf) ? schema.anyOf : [schema]; + const inputs: Record = {}; + for (const branch of branches) { + if (!isObject(branch) || !isObject(branch.properties)) return JSON.stringify(canonical(schema)); + const { accountId, ...properties } = branch.properties; + const ids = !isObject(accountId) + ? [] + : typeof accountId.const === "string" + ? [accountId.const] + : Array.isArray(accountId.enum) + ? accountId.enum + : []; + const input = JSON.stringify(canonical({ ...branch, properties })); + for (const id of ids) inputs[String(id)] = input; + } + return Object.keys(inputs).length === 0 + ? JSON.stringify(canonical(schema)) + : JSON.stringify(canonical(inputs)); +}; + +/** The product's API for the organization's apps, and the step's log, for one scenario. */ +const rebuildFixture = Effect.gen(function* () { + const actors = yield* Actors; + const api = yield* Api; + const target = yield* Target; + const log = `${target.directory}/server.log`; + const organization = actors.organization.id; + const owner = `organization:${organization}`; + const prefix = `/api/organizations/${organization}`; + const request = (method: "GET" | "POST" | "DELETE", path: string, data?: unknown) => + api.request(actors.owner, method, `${prefix}${path}`, data); + const ok = (schema: Schema.ConstraintDecoder) => + Effect.flatMap((response: { readonly status: number; readonly body: unknown }) => { + expect(response.status, JSON.stringify(response.body)).toBe(200); + return body(schema, response); + }); + const created: App[] = []; + yield* Effect.addFinalizer(() => + Effect.forEach(created, (app) => request("DELETE", `/apps/${app.id}`)).pipe(Effect.ignore), + ); + const remember = (app: App) => Effect.sync(() => created.push(app)); + const install = (entry: string, name: string) => + request("POST", "/apps/install", { + entry, + name: `${name} ${randomUUID().slice(0, 8)}`, + }).pipe(ok(App), Effect.tap(remember)); + const get = (app: App) => request("GET", `/apps/${app.id}`).pipe(ok(App)); + const workspace = (app: App) => request("GET", `/apps/${app.id}/workspace`).pipe(ok(Workspace)); + const main = (app: App) => workspace(app).pipe(Effect.map((source) => sorted(source.files))); + const running = (app: App) => + request("GET", `/apps/${app.id}/source`).pipe( + ok(RunningSource), + Effect.map((result) => sorted(result.files)), + ); + const versions = (app: App) => + request("GET", `/apps/${app.id}/versions`).pipe( + ok(Versions), + Effect.map((list) => list.map((version) => version.id).toSorted()), + ); + const summaries = dataStepSummaries(log, step).pipe(Effect.map((all) => all.length)); + /** Run `start` and return the summary the step's pass logged in it. */ + const nextSummary = (start: Effect.Effect) => + Effect.gen(function* () { + const seen = yield* summaries; + yield* start; + return yield* nextDataStepSummary(log, step, seen); + }); + /** Stop the product and have its later starts apply data steps. */ + const holdApply = Effect.gen(function* () { + yield* serverControl("stop"); + yield* serverControl("data-steps", 200, { mode: "apply" }); + }); + + const links = (app: App) => linkedAccountIds(actors.owner, `${prefix}/apps/${app.id}`); + + /** A synthetic account connected from `app`, which links it for the app's requirement. */ + const connect = (app: App, label: string) => + Effect.gen(function* () { + const pending = yield* request( + "POST", + `/apps/${app.id}/accounts/user/popupsmart/connections`, + {}, + ).pipe(ok(Resource)); + const account = (yield* request("POST", `/connections/${pending.id}/submit`, { + method: "apiKey", + label, + fields: { token: `synthetic-${randomUUID()}` }, + }).pipe(ok(Resource))).id; + yield* Effect.addFinalizer(() => + request("DELETE", `/accounts/${account}`).pipe(Effect.ignore), + ); + return account; + }); + + // The product started with the step on and held, so it reported before these apps existed. + expect(yield* nextDataStepSummary(log, step, 0)).toMatchObject({ + mode: "report", + status: "complete", + }); + return { + actors, + target, + owner, + prefix, + request, + ok, + remember, + install, + get, + workspace, + main, + running, + versions, + summaries, + nextSummary, + holdApply, + links, + connect, + }; +}); + +layer(HostedLive, { excludeTestServices: true })("Catalog copy rebuild data step", (it) => { + it.effect( + scenarios.catalogCopyRebuild.title, + (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { + owner, + request, + ok, + remember, + install, + get, + workspace, + main, + running, + versions, + summaries, + nextSummary, + holdApply, + links, + connect, + } = yield* rebuildFixture; + /** + * Every tool by name, with what each linked account accepts. beta.140's account router + * merges accounts whose input is the same into one branch (`accountId` an `enum` rather + * than one `const` branch per account), drops an empty `$defs` and adds `kindConfirmed`, + * so the comparison reads the input per account: the same accounts must accept the same + * input, and every other field (kind, description, output schema) must be unchanged. + * Popupsmart lists one tool per account router, on one page. + */ + const tools = (app: App) => + request("GET", `/apps/${app.id}/tools`).pipe( + ok(Tools), + Effect.tap((page) => Effect.sync(() => expect(page.next).toBeUndefined())), + Effect.map((page) => + page.items + .map((item) => { + const { + version: _version, + deployment: _deployment, + kindConfirmed: _kindConfirmed, + inputSchema, + ...tool + } = item; + return JSON.stringify({ ...tool, inputs: inputsByAccount(inputSchema) }); + }) + .toSorted(), + ), + ); + // Untouched copies: the October source (protocol 12) with two accounts, the November + // source (protocol 13) with one. + const novemberFiles = sorted(catalogSnapshotFiles(catalogSnapshots.november.id)); + expect(declaredApps(octoberFiles())).toBe(october); + expect(declaredApps(novemberFiles)).toBe(november); + const untouched = yield* install(catalogSnapshots.october.id, "Popupsmart October"); + yield* connect(untouched, "First"); + yield* connect(untouched, "Second"); + const current = yield* install(catalogSnapshots.november.id, "Popupsmart November"); + yield* connect(current, "Only"); + // Edited: a later version runs other files than the install. + const redeployed = yield* install(catalogSnapshots.october.id, "Popupsmart redeployed"); + yield* request("POST", `/apps/${redeployed.id}/deploy`, { + files: catalogSnapshotFiles(catalogSnapshots.altered.id), + }).pipe(ok(Schema.Struct({ app: App }))); + // Edited: main holds work that was never deployed. + const drafted = yield* install(catalogSnapshots.october.id, "Popupsmart drafted"); + yield* request("POST", `/apps/${drafted.id}/commits`, { + expected: (yield* workspace(drafted)).revision.commit, + files: catalogSnapshotFiles(catalogSnapshots.altered.id), + message: "Edit the README", + }).pipe(ok(Committed)); + // Unmapped: installed from a source no catalog commit published. + const altered = yield* install(catalogSnapshots.altered.id, "Popupsmart altered"); + // Held: a package whose tool names change on beta.140. + const held = yield* install(catalogSnapshots.held.id, "Netsapiens"); + // Current: already on the host's release. + const synthetic = yield* install(officialApps.mail.id, "Synthetic mail"); + expect(declaredApps(yield* running(synthetic))).toBe(appsVersion); + // Not a catalog install: a copy of an app the organization deployed itself, under a + // catalog package's name and with the October files. A copy records its parent's name + // and an `app:` origin, so only the name looks like the catalog's. + const owned = yield* request("POST", "/apps/deploy", { + name: `@executor.sh/popupsmart-${randomUUID().slice(0, 8)}`, + files: catalogSnapshotFiles(catalogSnapshots.october.id), + }).pipe(ok(App), Effect.tap(remember)); + const copied = yield* request("POST", "/apps/copies", { + from: { app: owned.id }, + name: `Popupsmart owned copy ${randomUUID().slice(0, 8)}`, + }).pipe(ok(App), Effect.tap(remember)); + expect(yield* running(copied)).toEqual(octoberFiles()); + + const apps = [untouched, current, redeployed, drafted, altered, held, synthetic, copied]; + const state = Effect.forEach(apps, (app) => + Effect.all({ + app: get(app), + versions: versions(app), + running: running(app), + main: main(app), + links: links(app), + }), + ); + const before = yield* state; + const toolsBefore = { + untouched: yield* tools(untouched), + current: yield* tools(current), + }; + // With linked accounts the copies list their tools; an empty list would prove nothing. + expect(toolsBefore.untouched.length).toBeGreaterThan(0); + expect(toolsBefore.current.length).toBeGreaterThan(0); + + // Every row of the tables the step could change, for these apps, as one hash per + // table. The journal is the only thing a report may write. + const ids = apps.map((app) => `'${app.id}'`).join(", "); + const tables = { + apps: `select t::text as row from executor_apps t where id in (${ids})`, + versions: `select t::text as row from executor_deployments t where code in (select code from executor_apps where id in (${ids}))`, + links: `select t::text as row from hosted_app_account_links t where app in (${ids})`, + accounts: `select t::text as row from executor_accounts t where id in (select account from hosted_app_account_links where app in (${ids}))`, + records: `select t::text as row from executor_app_records t where app in (${ids})`, + schedules: `select t::text as row from executor_schedules t where app in (${ids})`, + subscriptions: `select t::text as row from executor_webhooks t where app in (${ids})`, + profiles: `select t::text as row from executor_installations t where app in (${ids})`, + }; + const checksums = Effect.gen(function* () { + const [first, ...rest] = Object.values(tables).map((query) => ({ + sql: `select md5(coalesce(string_agg(row, '|' order by row), '')) as sum from (${query}) rows`, + })); + if (first === undefined) return yield* Effect.die("No tables to hash"); + const results = yield* legacyStorage([first, ...rest]); + const sums = yield* Effect.forEach(results, (rows) => + Schema.decodeUnknownEffect(Sum)(rows[0]), + ); + return Object.fromEntries( + Object.keys(tables).map((name, index) => [name, sums[index]]), + ); + }); + // The hashes stop the product; the report start starts it again. + const hashedBefore = yield* checksums; + const report = yield* nextSummary(serverControl("start")); + expect(report).toMatchObject({ mode: "report", status: "complete", pass: 1 }); + expect(report.owners[owner]).toEqual({ + rebuild: 2, + edited: 2, + unmapped: 1, + "held-tool-names": 1, + current: 1, + "not-catalog": 1, + }); + expect(yield* checksums).toEqual(hashedBefore); + yield* serverControl("start"); + expect(yield* state).toEqual(before); + + // Apply: the mode changes only while the product is stopped. + yield* holdApply; + const applied = yield* nextSummary(serverControl("start")); + // With the step on and no scope, the stage covers every copy. + expect(applied).toMatchObject({ + mode: "apply", + run: stageRun("all"), + status: "complete", + pass: 1, + }); + expect(applied.owners[owner]).toEqual({ + rebuilt: 2, + edited: 2, + unmapped: 1, + "held-tool-names": 1, + current: 1, + "not-catalog": 1, + }); + + // Both untouched copies now run, and main holds, exactly the catalog's own November + // source with the pin on beta.140: the October copy got the same move the catalog made. + const expected = rebuiltFiles(); + const after = yield* state; + for (const [index, app] of [untouched, current].entries()) { + const was = before[index]!; + const now = after[index]!; + expect(now.app.id).toBe(app.id); + expect(now.app.activeVersion).not.toBe(was.app.activeVersion); + expect(now.running).toEqual(expected); + expect(now.main).toEqual(expected); + // Same requirement names, scopes, cardinalities and provider IDs; same accounts. + expect(now.app.requirements).toEqual(was.app.requirements); + expect(now.links).toEqual(was.links); + // The replaced version is retained. + expect(now.versions).toEqual([...was.versions, now.app.activeVersion ?? ""].toSorted()); + } + expect(yield* tools(untouched)).toEqual(toolsBefore.untouched); + expect(yield* tools(current)).toEqual(toolsBefore.current); + // Every other copy is unchanged, the owned copy included. + for (const index of [2, 3, 4, 5, 6, 7]) + expect(after[index], apps[index]?.name).toEqual(before[index]); + + // Undo: activating the replaced version restores the October source, with the same + // provider, accounts and tools. + const rebuiltVersion = after[0]?.app.activeVersion ?? null; + yield* request("POST", `/apps/${untouched.id}/activate`, { + version: before[0]?.app.activeVersion, + expectedVersion: rebuiltVersion, + }).pipe(ok(Schema.Unknown)); + const undone = yield* get(untouched); + expect(undone.activeVersion).toBe(before[0]?.app.activeVersion); + expect(undone.requirements).toEqual(before[0]?.app.requirements); + expect(yield* running(untouched)).toEqual(octoberFiles()); + expect(yield* links(untouched)).toEqual(before[0]?.links); + expect(yield* tools(untouched)).toEqual(toolsBefore.untouched); + + // A later start runs nothing and changes nothing. + const quiet = yield* summaries; + const settled = yield* state; + yield* serverControl("restart"); + expect(yield* summaries).toBe(quiet); + expect(yield* state).toEqual(settled); + }), + ), + // The product starts five times and builds on beta.88, beta.100 and beta.140. + { timeout: 300_000 }, + ); + + it.effect( + scenarios.catalogCopyRebuildUnreachableRegistry.title, + (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { owner, install, get, main, running, versions, nextSummary, holdApply } = + yield* rebuildFixture; + const registry = yield* Config.NonEmptyString("E2E_NPM_REGISTRY"); + const copy = yield* install(catalogSnapshots.october.id, "Popupsmart offline"); + const before = { app: yield* get(copy), versions: yield* versions(copy) }; + + // The first apply start cannot reach any registry, as on an offline host or with its + // mirror down: nothing listens on port 1. The step's builds need apps beta.140 from + // npm, which no earlier build on this product installed. + yield* holdApply; + yield* serverControl("environment", 200, { EXECUTOR_NPM_REGISTRY: "http://127.0.0.1:1" }); + const offline = yield* nextSummary(serverControl("start")); + // Nothing about the source is known, so the copy is retried rather than recorded as a + // copy that does not build, which no later start would revisit. + expect(offline).toMatchObject({ mode: "apply", status: "retrying", pass: 1 }); + expect(offline.owners[owner]).toEqual({ failed: 1 }); + expect(yield* get(copy)).toEqual(before.app); + expect(yield* versions(copy)).toEqual(before.versions); + + // With the registry back, the next start rebuilds it. + yield* serverControl("stop"); + yield* serverControl("environment", 200, { EXECUTOR_NPM_REGISTRY: registry }); + const online = yield* nextSummary(serverControl("start")); + expect(online).toMatchObject({ mode: "apply", status: "complete", pass: 2 }); + expect(online.owners[owner]).toEqual({ rebuilt: 1 }); + expect(yield* running(copy)).toEqual(rebuiltFiles()); + expect(yield* main(copy)).toEqual(rebuiltFiles()); + expect((yield* get(copy)).requirements).toEqual(before.app.requirements); + }), + ), + // The product starts three times and builds on beta.88 and beta.140. + { timeout: 240_000 }, + ); + + it.effect( + scenarios.catalogCopyRebuildCompilerUnavailable.title, + (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { owner, install, get, main, running, versions, nextSummary, holdApply } = + yield* rebuildFixture; + // Two copies of one source: a pass builds each upgraded source once for all its copies, + // so a failure kept for the first would decide the second. + const copies = [ + yield* install(catalogSnapshots.october.id, "Popupsmart first"), + yield* install(catalogSnapshots.october.id, "Popupsmart second"), + ]; + const before = yield* Effect.forEach(copies, (copy) => + Effect.all({ app: get(copy), versions: versions(copy) }), + ); + const unchanged = Effect.gen(function* () { + for (const [index, copy] of copies.entries()) { + expect(yield* get(copy)).toEqual(before[index]?.app); + expect(yield* versions(copy)).toEqual(before[index]?.versions); + expect(yield* running(copy)).toEqual(octoberFiles()); + } + }); + + // The first apply start's calls to the compiler fail without an answer, as when the + // compiler is down: the step's check builds never reach it. Nothing about the source is + // known, so both copies are retried rather than recorded as copies that do not build, + // which no later start would revisit. + yield* holdApply; + yield* serverControl("environment", 200, { EXECUTOR_TEST_COMPILER_UNAVAILABLE: "all" }); + const down = yield* nextSummary(serverControl("start")); + expect(down).toMatchObject({ mode: "apply", status: "retrying", pass: 1 }); + expect(down.owners[owner]).toEqual({ failed: 2 }); + yield* unchanged; + + // The next start's check builds answer, and only the deploys that keep their build go + // unanswered: the same, after the step said it was rebuilding them. + yield* serverControl("stop"); + yield* serverControl("environment", 200, { + EXECUTOR_TEST_COMPILER_UNAVAILABLE: "retained", + }); + const deploys = yield* nextSummary(serverControl("start")); + expect(deploys).toMatchObject({ mode: "apply", status: "retrying", pass: 2 }); + expect(deploys.owners[owner]).toEqual({ failed: 2 }); + yield* unchanged; + + // With the compiler back, the next start rebuilds both. + yield* serverControl("stop"); + yield* serverControl("environment", 200, { EXECUTOR_TEST_COMPILER_UNAVAILABLE: "" }); + const back = yield* nextSummary(serverControl("start")); + expect(back).toMatchObject({ mode: "apply", status: "complete", pass: 3 }); + expect(back.owners[owner]).toEqual({ rebuilt: 2 }); + for (const [index, copy] of copies.entries()) { + expect(yield* running(copy)).toEqual(rebuiltFiles()); + expect(yield* main(copy)).toEqual(rebuiltFiles()); + expect((yield* get(copy)).requirements).toEqual(before[index]?.app.requirements); + } + }), + ), + // The product starts four times and builds on beta.88 and beta.140. + { timeout: 300_000 }, + ); + + it.effect( + scenarios.catalogCopyRebuildConcurrentActivation.title, + (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { owner, request, ok, install, get, main, running, versions, nextSummary } = + yield* rebuildFixture; + // Each copy runs its install. The first also retains an edited version, deployed and + // then replaced by the install again, which a person can activate at any time. + const switched = yield* install(catalogSnapshots.october.id, "Popupsmart switched"); + const edited = yield* request("POST", `/apps/${switched.id}/deploy`, { + files: catalogSnapshotFiles(catalogSnapshots.altered.id), + }).pipe(ok(Schema.Struct({ app: App }))); + yield* request("POST", `/apps/${switched.id}/activate`, { + version: switched.activeVersion, + expectedVersion: edited.app.activeVersion, + }).pipe(ok(Schema.Unknown)); + const reactivated = yield* install(catalogSnapshots.october.id, "Popupsmart reactivated"); + const apps = [switched, reactivated]; + const state = Effect.forEach(apps, (app) => + Effect.all({ + app: get(app), + versions: versions(app), + running: running(app), + main: main(app), + }), + ); + const before = yield* state; + expect(before[0]?.running).toEqual(octoberFiles()); + + // A person activates a version while the step builds its deploy: once the deploy has + // reserved its order, the product stores exactly what an activation stores. For the + // first copy that is the edited version; for the second, the version it already runs. + // Each fires once, on the deploy's reservation (the only write that moves the deploy + // order alone). The product is stopped while the fixture is written. + const races = [ + { app: switched.id, activate: edited.app.activeVersion ?? "" }, + { app: reactivated.id, activate: reactivated.activeVersion ?? "" }, + ]; + yield* legacyStorage([ + { + sql: "CREATE TABLE executor_test_race (app text primary key, activate text not null)", + }, + ...races.map((race) => ({ + sql: "INSERT INTO executor_test_race (app, activate) VALUES ($1, $2)", + params: [race.app, race.activate], + })), + { + sql: `CREATE FUNCTION executor_test_race() RETURNS trigger LANGUAGE plpgsql AS $$ + DECLARE chosen text; + BEGIN + DELETE FROM executor_test_race WHERE app = NEW.id RETURNING activate INTO chosen; + IF chosen IS NOT NULL THEN + UPDATE executor_apps SET active_deployment = chosen, + deploy_sequence = NEW.deploy_sequence + 1, + activated_sequence = NEW.deploy_sequence + 1 + WHERE id = NEW.id; + END IF; + RETURN NULL; + END $$`, + }, + { + sql: `CREATE TRIGGER executor_test_race AFTER UPDATE OF deploy_sequence ON executor_apps + FOR EACH ROW WHEN (NEW.deploy_sequence = OLD.deploy_sequence + 1 + AND NEW.activated_sequence = OLD.activated_sequence + AND NEW.active_deployment IS NOT DISTINCT FROM OLD.active_deployment) + EXECUTE FUNCTION executor_test_race()`, + }, + ]); + yield* serverControl("data-steps", 200, { mode: "apply" }); + const raced = yield* nextSummary(serverControl("start")); + // The person's activation wins; the step's deploy records nothing and is retried. + expect(raced).toMatchObject({ mode: "apply", status: "retrying", pass: 1 }); + expect(raced.owners[owner]).toEqual({ conflict: 2 }); + const during = yield* state; + expect(during[0]?.app.activeVersion).toBe(edited.app.activeVersion); + expect(during[1]?.app.activeVersion).toBe(reactivated.activeVersion); + for (const index of [0, 1]) { + // No version of the step's is retained, and main still holds the install. + expect(during[index]?.versions).toEqual(before[index]?.versions); + expect(during[index]?.main).toEqual(octoberFiles()); + } + expect(during[0]?.running).toEqual( + sorted(catalogSnapshotFiles(catalogSnapshots.altered.id)), + ); + + // The next start finds the first copy running the person's edit and leaves it; the + // second runs its install still, untouched, and is rebuilt. + const settled = yield* nextSummary(serverControl("restart")); + expect(settled).toMatchObject({ mode: "apply", status: "complete", pass: 2 }); + expect(settled.owners[owner]).toEqual({ edited: 1, rebuilt: 1 }); + const after = yield* state; + expect(after[0]).toEqual(during[0]); + expect(after[1]?.running).toEqual(rebuiltFiles()); + expect(after[1]?.main).toEqual(rebuiltFiles()); + }), + ), + // The product starts four times and builds on beta.88 and beta.140. + { timeout: 240_000 }, + ); + + it.effect( + scenarios.catalogCopyRebuildInterrupted.title, + (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { + target, + owner, + request, + ok, + install, + get, + workspace, + main, + running, + versions, + nextSummary, + } = yield* rebuildFixture; + const fs = yield* FileSystem.FileSystem; + // Two copies: the step finishes the first; someone undoes the second before it can. + const copy = yield* install(catalogSnapshots.october.id, "Popupsmart interrupted"); + const undone = yield* install(catalogSnapshots.october.id, "Popupsmart undone"); + const copies = [copy, undone]; + // Reading main creates each app's repository from the install's files. + for (const app of copies) + expect(sorted((yield* workspace(app)).files)).toEqual(octoberFiles()); + const installed = yield* Effect.forEach(copies, versions); + + // Main's branch is locked, as by a Git process that did not finish: the step's deploy + // succeeds and its commit to main fails after it. + const locks = copies.map( + (app) => `${target.directory}/data/repositories/${app.code}.git/refs/heads/main.lock`, + ); + yield* serverControl("stop"); + for (const lock of locks) yield* fs.writeFileString(lock, ""); + yield* serverControl("data-steps", 200, { mode: "apply" }); + const stopped = yield* nextSummary(serverControl("start")); + // Each app runs the rebuild with main still on the install: that is not done, and the + // step says so rather than recording a rebuilt app. + expect(stopped).toMatchObject({ mode: "apply", status: "retrying", pass: 1 }); + expect(stopped.owners[owner]).toEqual({ rebuilding: 2 }); + const deployed = yield* Effect.forEach(copies, get); + for (const [index, app] of copies.entries()) { + expect(deployed[index]?.activeVersion).not.toBe(app.activeVersion); + expect(yield* running(app)).toEqual(rebuiltFiles()); + expect(yield* main(app)).toEqual(octoberFiles()); + } + // Someone puts the second back on its install, as the documented undo does. + yield* request("POST", `/apps/${undone.id}/activate`, { + version: undone.activeVersion, + expectedVersion: deployed[1]?.activeVersion, + }).pipe(ok(Schema.Unknown)); + + // The next start runs another stage, whose scope names neither copy, and still finishes + // the first rebuild: main gets what runs, and nothing is deployed again. The second's + // undo stands: no new deploy, main left on the install. + yield* serverControl("stop"); + for (const lock of locks) yield* fs.remove(lock); + const elsewhere = `app:app_${randomUUID()}`; + yield* serverControl("environment", 200, { + EXECUTOR_CATALOG_COPY_REBUILD_SCOPE: elsewhere, + }); + const finished = yield* nextSummary(serverControl("start")); + expect(finished).toMatchObject({ + mode: "apply", + run: stageRun(elsewhere), + status: "complete", + pass: 1, + }); + expect(finished.owners[owner]).toEqual({ rebuilt: 1, "rolled-back": 1 }); + for (const [index, app] of copies.entries()) + expect(yield* versions(app)).toEqual( + [...installed[index]!, deployed[index]?.activeVersion ?? ""].toSorted(), + ); + expect((yield* get(copy)).activeVersion).toBe(deployed[0]?.activeVersion); + expect(yield* running(copy)).toEqual(rebuiltFiles()); + expect(yield* main(copy)).toEqual(rebuiltFiles()); + expect((yield* get(undone)).activeVersion).toBe(undone.activeVersion); + expect(yield* running(undone)).toEqual(octoberFiles()); + expect(yield* main(undone)).toEqual(octoberFiles()); + }), + ), + // The product starts four times and builds on beta.88 and beta.140. + { timeout: 240_000 }, + ); + + it.effect( + scenarios.catalogCopyRebuildStaged.title, + (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { + actors, + owner, + install, + get, + main, + running, + versions, + summaries, + nextSummary, + holdApply, + links, + connect, + } = yield* rebuildFixture; + const copies = [ + yield* install(catalogSnapshots.october.id, "Popupsmart first stage"), + yield* install(catalogSnapshots.october.id, "Popupsmart second stage"), + yield* install(catalogSnapshots.october.id, "Popupsmart last stage"), + ]; + // Each copy has a linked account, which every stage must leave linked. + for (const copy of copies) yield* connect(copy, "Stage"); + const state = Effect.forEach(copies, (copy) => + Effect.all({ + app: get(copy), + versions: versions(copy), + running: running(copy), + main: main(copy), + links: links(copy), + }), + ); + const before = yield* state; + const rebuilt = (index: number, now: Effect.Success) => { + expect(now[index]?.app.activeVersion).not.toBe(before[index]?.app.activeVersion); + expect(now[index]?.running).toEqual(rebuiltFiles()); + expect(now[index]?.main).toEqual(rebuiltFiles()); + expect(now[index]?.app.requirements).toEqual(before[index]?.app.requirements); + expect(now[index]?.links).toEqual(before[index]?.links); + }; + const [first, second, last] = copies; + if (first === undefined || second === undefined || last === undefined) + return yield* Effect.die("Three copies"); + + // The first stage names one copy. The others are not read or changed: same version, + // versions, running files, main and linked accounts. + yield* holdApply; + const one = `app:${first.id}`; + yield* serverControl("environment", 200, { EXECUTOR_CATALOG_COPY_REBUILD_SCOPE: one }); + const firstStage = yield* nextSummary(serverControl("start")); + expect(firstStage).toMatchObject({ + mode: "apply", + run: stageRun(one), + status: "complete", + pass: 1, + }); + expect(firstStage.owners[owner]).toEqual({ rebuilt: 1, "out-of-scope": 2 }); + const afterFirst = yield* state; + rebuilt(0, afterFirst); + expect(afterFirst[1]).toEqual(before[1]); + expect(afterFirst[2]).toEqual(before[2]); + + // A finished stage does not run again. + const quiet = yield* summaries; + yield* serverControl("restart"); + expect(yield* summaries).toBe(quiet); + expect(yield* state).toEqual(afterFirst); + + // A wider stage with a maximum changes only that many more copies, in ID order. Once it + // has, every later copy is out of its scope without a read, so the copy the first stage + // rebuilt reads `current` only when it comes before the one this stage rebuilds. + const capped = "all max:1"; + const [earlier, later] = [second, last].toSorted((left, right) => + left.id < right.id ? -1 : 1, + ); + if (earlier === undefined || later === undefined) return yield* Effect.die("Two copies"); + yield* serverControl("stop"); + yield* serverControl("environment", 200, { EXECUTOR_CATALOG_COPY_REBUILD_SCOPE: capped }); + const secondStage = yield* nextSummary(serverControl("start")); + expect(secondStage).toMatchObject({ + run: stageRun(capped), + status: "complete", + pass: 1, + }); + expect(secondStage.owners[owner]).toEqual( + first.id < earlier.id + ? { current: 1, rebuilt: 1, "out-of-scope": 1 } + : { rebuilt: 1, "out-of-scope": 2 }, + ); + const afterSecond = yield* state; + expect(afterSecond[0]).toEqual(afterFirst[0]); + const earlierIndex = copies.indexOf(earlier); + const laterIndex = copies.indexOf(later); + rebuilt(earlierIndex, afterSecond); + expect(afterSecond[laterIndex]).toEqual(before[laterIndex]); + + // The organization's stage rebuilds the copy left, and changes neither of the others. + const organization = `organization:${actors.organization.id}`; + yield* serverControl("stop"); + yield* serverControl("environment", 200, { + EXECUTOR_CATALOG_COPY_REBUILD_SCOPE: organization, + }); + const lastStage = yield* nextSummary(serverControl("start")); + expect(lastStage).toMatchObject({ + run: stageRun(organization), + status: "complete", + pass: 1, + }); + expect(lastStage.owners[owner]).toEqual({ current: 2, rebuilt: 1 }); + const afterLast = yield* state; + expect(afterLast[0]).toEqual(afterSecond[0]); + expect(afterLast[earlierIndex]).toEqual(afterSecond[earlierIndex]); + rebuilt(laterIndex, afterLast); + }), + ), + // The product starts six times and builds on beta.88 and beta.140. + { timeout: 300_000 }, + ); + + it.effect( + scenarios.catalogCopyRebuildGivesUp.title, + (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { + actors, + owner, + install, + get, + running, + versions, + summaries, + nextSummary, + holdApply, + } = yield* rebuildFixture; + const registry = yield* Config.NonEmptyString("E2E_NPM_REGISTRY"); + // Two copies of different sources, each with its own check build. + const copies = [ + yield* install(catalogSnapshots.october.id, "Popupsmart outage"), + yield* install(catalogSnapshots.november.id, "Popupsmart outage November"), + ]; + const before = yield* Effect.forEach(copies, (copy) => + Effect.all({ app: get(copy), versions: versions(copy) }), + ); + const unchanged = Effect.forEach(copies, (copy, index) => + Effect.gen(function* () { + expect(yield* get(copy)).toEqual(before[index]?.app); + expect(yield* versions(copy)).toEqual(before[index]?.versions); + }), + ); + // The registry stays out of reach. Each start records both copies `failed`; the third + // start gives up on them, so the host's data steps complete instead of holding every + // later start. + yield* holdApply; + yield* serverControl("environment", 200, { EXECUTOR_NPM_REGISTRY: "http://127.0.0.1:1" }); + for (const pass of [1, 2, 3]) { + const summary = yield* nextSummary( + pass === 1 ? serverControl("start") : serverControl("restart"), + ); + if (pass < 3) { + expect(summary).toMatchObject({ mode: "apply", status: "retrying", pass }); + expect(summary.owners[owner]).toEqual({ failed: 2 }); + } else { + expect(summary).toMatchObject({ mode: "apply", status: "complete", pass }); + expect(summary.owners[owner]).toEqual({ "gave-up": 2 }); + } + yield* unchanged; + } + + // The stage is finished: with the registry back, a start runs nothing. + yield* serverControl("stop"); + yield* serverControl("environment", 200, { EXECUTOR_NPM_REGISTRY: registry }); + const quiet = yield* summaries; + yield* serverControl("start"); + expect(yield* summaries).toBe(quiet); + yield* unchanged; + + // The next stage tries them afresh and rebuilds both. + const organization = `organization:${actors.organization.id}`; + yield* serverControl("stop"); + yield* serverControl("environment", 200, { + EXECUTOR_CATALOG_COPY_REBUILD_SCOPE: organization, + }); + const next = yield* nextSummary(serverControl("start")); + expect(next).toMatchObject({ run: stageRun(organization), status: "complete" }); + expect(next.owners[owner]).toEqual({ rebuilt: 2 }); + for (const copy of copies) expect(yield* running(copy)).toEqual(rebuiltFiles()); + }), + ), + // The product starts six times and builds on beta.88, beta.100 and beta.140. + { timeout: 300_000 }, + ); + + it.effect( + scenarios.catalogCopyRebuildPaced.title, + (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { + owner, + install, + get, + main, + running, + versions, + summaries, + nextSummary, + holdApply, + } = yield* rebuildFixture; + // Two copies of different sources, so neither's check build serves the other. Items run + // in ID order. + const copies = [ + yield* install(catalogSnapshots.october.id, "Popupsmart paced"), + yield* install(catalogSnapshots.november.id, "Popupsmart paced November"), + ].toSorted((left, right) => (left.id < right.id ? -1 : 1)); + const state = Effect.forEach(copies, (copy) => + Effect.all({ + app: get(copy), + versions: versions(copy), + running: running(copy), + main: main(copy), + }), + ); + const before = yield* state; + const rebuilt = (index: number, now: Effect.Success) => { + expect(now[index]?.app.activeVersion).not.toBe(before[index]?.app.activeVersion); + expect(now[index]?.running).toEqual(rebuiltFiles()); + expect(now[index]?.main).toEqual(rebuiltFiles()); + // One deploy: the check build kept nothing, and the deploy was not repeated. + expect(now[index]?.versions).toEqual( + [...(before[index]?.versions ?? []), now[index]?.app.activeVersion ?? ""].toSorted(), + ); + }; + + // Each start may start one compiler build. A copy takes two, its check build and its + // deploy, so each start does half a copy and ends no pass. + yield* holdApply; + yield* serverControl("environment", 200, { + EXECUTOR_TEST_CATALOG_COPY_REBUILD_PACE: "1", + }); + const quiet = yield* summaries; + // The first start checks the first copy, and stops before its deploy. + yield* serverControl("start"); + expect(yield* summaries).toBe(quiet); + expect(yield* state).toEqual(before); + + // The next deploys it without checking it again, and stops before the second copy. + yield* serverControl("restart"); + expect(yield* summaries).toBe(quiet); + const afterDeploy = yield* state; + rebuilt(0, afterDeploy); + expect(afterDeploy[1]).toEqual(before[1]); + + // The next checks the second copy. + yield* serverControl("restart"); + expect(yield* summaries).toBe(quiet); + expect(yield* state).toEqual(afterDeploy); + + // The next deploys it, and the pass ends. + const done = yield* nextSummary(serverControl("restart")); + expect(done).toMatchObject({ + mode: "apply", + run: stageRun("all"), + status: "complete", + pass: 1, + }); + expect(done.owners[owner]).toEqual({ rebuilt: 2 }); + const after = yield* state; + expect(after[0]).toEqual(afterDeploy[0]); + rebuilt(1, after); + }), + ), + // The product starts five times and builds on beta.88, beta.100 and beta.140. + { timeout: 300_000 }, + ); + + it.effect( + scenarios.catalogCopyRebuildIntentKept.title, + (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { target, owner, install, get, workspace, main, running, versions, nextSummary } = + yield* rebuildFixture; + const fs = yield* FileSystem.FileSystem; + // Two copies, in the order the step handles them. Each start's failure to read the + // second is caused right after the step records the first. + const copies = [ + yield* install(catalogSnapshots.october.id, "Popupsmart kept"), + yield* install(catalogSnapshots.october.id, "Popupsmart unread"), + ].toSorted((left, right) => (left.id < right.id ? -1 : 1)); + const [first, unread] = copies; + if (first === undefined || unread === undefined) return yield* Effect.die("Two copies"); + for (const app of copies) + expect(sorted((yield* workspace(app)).files)).toEqual(octoberFiles()); + const installed = yield* Effect.forEach(copies, versions); + const lock = (app: App) => + `${target.directory}/data/repositories/${app.code}.git/refs/heads/main.lock`; + + // Both commits to main fail after the deploy, as in the interrupted scenario: each copy + // runs its rebuild with main still on the install, and the step says it is not done. + yield* serverControl("stop"); + for (const app of copies) yield* fs.writeFileString(lock(app), ""); + yield* serverControl("data-steps", 200, { mode: "apply" }); + const stopped = yield* nextSummary(serverControl("start")); + expect(stopped).toMatchObject({ mode: "apply", status: "retrying", pass: 1 }); + expect(stopped.owners[owner]).toEqual({ rebuilding: 2 }); + const deployed = yield* Effect.forEach(copies, get); + const partWay = Effect.forEach(copies, (app, index) => + Effect.gen(function* () { + expect((yield* get(app)).activeVersion).toBe(deployed[index]?.activeVersion); + expect(yield* running(app)).toEqual(rebuiltFiles()); + expect(yield* main(app)).toEqual(octoberFiles()); + }), + ); + + // From now on, whenever the step records the first copy, the second's active version + // can no longer be read (its stored requirements are not requirements), as when storage + // fails; the step's own record of the second puts it back. The listing at the start of + // each pass reads it intact. The first copy's main stays locked, so each start records + // it; the second's lock is gone. + const unreadVersion = deployed[1]?.activeVersion ?? ""; + yield* serverControl("stop"); + yield* fs.remove(lock(unread)); + yield* legacyStorage([ + { + sql: `CREATE TABLE executor_test_read_fault AS + SELECT id, requirements, ''::text AS after_item, ''::text AS unread_item + FROM executor_deployments WITH NO DATA`, + }, + { + sql: `INSERT INTO executor_test_read_fault + SELECT id, requirements, $1, $2 FROM executor_deployments WHERE id = $3`, + params: [first.id, unread.id, unreadVersion], + }, + { + sql: `CREATE FUNCTION executor_test_read_fault() RETURNS trigger LANGUAGE plpgsql AS $$ + DECLARE fault executor_test_read_fault%ROWTYPE; + BEGIN + SELECT * INTO fault FROM executor_test_read_fault; + IF NEW.name <> '${step}' THEN RETURN NULL; END IF; + IF NEW.item = fault.after_item THEN + UPDATE executor_deployments SET requirements = '"unreadable"' WHERE id = fault.id; + ELSIF NEW.item = fault.unread_item THEN + UPDATE executor_deployments SET requirements = fault.requirements WHERE id = fault.id; + END IF; + RETURN NULL; + END $$`, + }, + { + sql: `CREATE TRIGGER executor_test_read_fault + AFTER INSERT OR UPDATE ON private_hosted_data_step_items + FOR EACH ROW EXECUTE FUNCTION executor_test_read_fault()`, + }, + ]); + + // The second copy cannot be read at either retry of the stage. It stays to be finished: + // `rebuilding`, then `unfinished` at the host's bound, never `failed` or `gave-up`, which + // a later pass would check afresh and read as `current` with main left on the install. + const retried = yield* nextSummary(serverControl("start")); + expect(retried).toMatchObject({ mode: "apply", status: "retrying", pass: 2 }); + expect(retried.owners[owner]).toEqual({ rebuilding: 2 }); + yield* partWay; + const bounded = yield* nextSummary(serverControl("restart")); + expect(bounded).toMatchObject({ mode: "apply", status: "complete", pass: 3 }); + expect(bounded.owners[owner]).toEqual({ unfinished: 2 }); + yield* partWay; + + // A later stage that names neither copy still finishes both, the second through one + // more failed read. + const elsewhere = `app:app_${randomUUID()}`; + yield* serverControl("stop"); + yield* serverControl("environment", 200, { + EXECUTOR_CATALOG_COPY_REBUILD_SCOPE: elsewhere, + }); + const unreadable = yield* nextSummary(serverControl("start")); + expect(unreadable).toMatchObject({ + mode: "apply", + run: stageRun(elsewhere), + status: "retrying", + pass: 1, + }); + expect(unreadable.owners[owner]).toEqual({ rebuilding: 2 }); + yield* partWay; + + // With storage and main back, the next start finishes both: main gets what runs, and + // nothing is deployed again. + yield* serverControl("stop"); + yield* fs.remove(lock(first)); + yield* legacyStorage([ + { sql: "DROP TRIGGER executor_test_read_fault ON private_hosted_data_step_items" }, + { sql: "DROP FUNCTION executor_test_read_fault()" }, + { sql: "DROP TABLE executor_test_read_fault" }, + ]); + const finished = yield* nextSummary(serverControl("start")); + expect(finished).toMatchObject({ + mode: "apply", + run: stageRun(elsewhere), + status: "complete", + pass: 2, + }); + expect(finished.owners[owner]).toEqual({ rebuilt: 2 }); + for (const [index, app] of copies.entries()) { + expect((yield* get(app)).activeVersion).toBe(deployed[index]?.activeVersion); + expect(yield* running(app)).toEqual(rebuiltFiles()); + expect(yield* main(app)).toEqual(rebuiltFiles()); + expect(yield* versions(app)).toEqual( + [...installed[index]!, deployed[index]?.activeVersion ?? ""].toSorted(), + ); + } + }), + ), + // The product starts six times and builds on beta.88 and beta.140. + { timeout: 300_000 }, + ); +}); diff --git a/packages/app-management/src/contracts/catalog-copy-rebuild.ts b/packages/app-management/src/contracts/catalog-copy-rebuild.ts new file mode 100644 index 0000000000..8d4b22c18a --- /dev/null +++ b/packages/app-management/src/contracts/catalog-copy-rebuild.ts @@ -0,0 +1,238 @@ +/** + * One-off data step: rebuild untouched copies of official catalog apps from their own installed + * source on a current `apps` release, so framework fixes reach them (E-042: the account merge's + * CPU cost and too-large replies, fixed in `0.0.1-beta.140`). + * + * A catalog install copies the feed's files unchanged, and a version keeps the framework it was + * built with; Executor never upgrades an app on its own. This step never reads the catalog: it + * rebuilds each copy's own files with only the mechanical upgrade its release needs, and only when + * the result is one of the reviewed targets listed in `catalog-copy-snapshots.ts`. See + * notes/catalog-copy-rebuild.md for the invariants, failure states, stop switch and undo. + */ +import { Schema } from "effect"; + +/** The journal name. It never changes; each apply stage records its own run under it. */ +export const catalogCopyRebuildStepName = "13_rebuild_catalog_copies_on_current_apps"; + +/** The release copies are rebuilt on: the first with the account merge fix (E-042). */ +export const catalogCopyRebuildTargetRelease = "0.0.1-beta.140"; + +/** + * The package scope of official catalog apps, as `copiedFrom.name` records it. Items are the apps + * whose origin names a package in it; only a feed install's origin passes (`not-catalog`). + */ +export const catalogPackageScope = "@executor.sh/"; + +/** + * Packages whose existing tool names change on the target release: an operation path that + * collides is suffixed differently, and two netsapiens tools call another endpoint under the same + * name. Saved approvals, grants and calls name tools, so their copies are held, not rebuilt, until + * someone decides. Measured on the catalog's source at beta.100 against beta.140 (2026-11-17). + */ +export const catalogCopyHeldPackages: ReadonlyArray = [ + "@executor.sh/appcircle", + "@executor.sh/aweber", + "@executor.sh/checkcherry", + "@executor.sh/netsapiens", +]; + +/** + * Packages that gain tools on the target release (operations an older release skipped now + * compile) while every existing tool keeps its name. They are rebuilt; the report counts them + * apart so the added tools are visible. Measured as for {@link catalogCopyHeldPackages}. + */ +export const catalogCopyToolsAddedPackages: ReadonlyArray = [ + "0codekit", + "apptivegrid", + "autotask", + "beatapi", + "billsby", + "box", + "browserless", + "btcpayserver", + "cashfree", + "chatbotkit", + "clickup", + "commercelayer", + "crowdin", + "crustdata", + "customgpt", + "datto-rmm", + "deployhq", + "didit", + "document360", + "drchrono", + "dropboxsign", + "exa", + "finnhub", + "fireworksai", + "gettyimages", + "honcho", + "huntress", + "imagerouter", + "itmplatform", + "jinko", + "judgeme", + "lemlist", + "looker", + "make", + "microsoftpowerbi", + "mindbody", + "miro", + "mistralai", + "nango", + "nocodb", + "nozbeteams", + "nutrient-dws", + "nylas", + "onesignal", + "openlayer", + "openrouter", + "orgo", + "pandadoc", + "parallel", + "perplexityai", + "phrase", + "predictleads", + "render", + "revolt", + "rollbar", + "salesmsg", + "sellsy", + "sequenzy", + "shipengine", + "shopware", + "smartrecruiters-api-key", + "snowflake", + "spendesk", + "tave", + "telnyx", + "tempo", + "vectorshift", + "xata", + "xquik", + "zoho", + "zohodesk", +].map((name) => `${catalogPackageScope}${name}`); + +/** + * Items are apps whose `copiedFrom.name` is in the catalog's package scope. Report outcomes name + * what `apply` would do; apply outcomes what it did. Every outcome but `rebuilt*`, + * `rolled-back`, `rebuilding`, `conflict` and `failed` changes nothing. + * + * - `rebuild` / `rebuilt`: untouched, the upgraded source is a reviewed target, it builds on the + * target release and declares the same requirements. Rebuilt with only the reviewed upgrade. + * - `rebuild-adds-tools` / `rebuilt-adds-tools`: the same, for a package in + * {@link catalogCopyToolsAddedPackages}. + * - `not-catalog`: the origin is not an install from an official app feed (a copy of another app + * records its parent's display name, which anyone can set), or the running files' own package + * is not the one the origin names. Not rebuilt. + * - `held-tool-names`: every copy of a package in {@link catalogCopyHeldPackages}, by the package + * its running files declare, whatever its state. Not rebuilt. + * - `current`: the running source already pins the target release or a later one. + * - `edited`: the running source is not the app's first version's, or `main` holds other work. + * - `unmapped`: the running source declares no exact release, or it is the install's but its + * upgrade is not a reviewed target: no published catalog snapshot, or a shape the upgrade does + * not recognize. + * - `background-work`: the app has schedules, webhook subscriptions, workflow runs or profiles. A + * new version would reconcile them, so the step leaves the app alone. + * - `requirements-changed`: the upgraded source declares other requirements than the running + * version (names, scopes, cardinalities, provider IDs, SQL or events). Nothing + * changed. + * - `rolled-back`: (apply) the deployed version's requirements differed after all, so the + * replaced version was activated again at once; or a rebuild left part way was undone before + * the next pass finished it. A new version is retained but not active. + * - `build-failed`: the upgraded source does not build on the target release. Nothing changed. + * - `undeployed`: nothing runs. + * - `rebuilding`: (apply) recorded once the check build passed, before the deploy; it stays only + * when the app was left part way (deployed, but not yet checked, rolled back or committed to + * `main`), or when a failure while finishing it says nothing of what the app runs. Retried: the + * next pass finishes that app, deploying it without another check build if the deploy never + * activated. A paced run stops a copy before its deploy with this record and nothing else. + * - `conflict`: the app was deployed or activated, or its `main` changed, while it was handled. + * Retried. + * - `failed`: storage, Git or the build service failed for this app, or its build could not + * install a dependency (an npm registry out of reach). Nothing changed. Retried. An app being + * finished from a `rebuilding` or `unfinished` record stays `rebuilding` instead. + * - `removed`: the app was deleted before it could be handled. + * - `out-of-scope`: (apply) the app is not in this stage's scope, or the stage already changed its + * maximum count of copies. Nothing read or changed; a later, wider stage handles it afresh. + * - `gave-up`: (apply) the app ended `failed` or `conflict` on every pass up to the host's bound. + * Nothing changed; a later stage tries it afresh. + * - `unfinished`: (apply) the app stayed `rebuilding` up to the host's bound: its rebuild may be + * active with `main` not yet updated, or it may still run its install after a check build that + * passed and a deploy that kept failing. The next stage finishes it first, whatever its scope, + * deploying it in the second case. + */ +export const CatalogCopyRebuildOutcome = Schema.Literals([ + "rebuild", + "rebuild-adds-tools", + "rebuilt", + "rebuilt-adds-tools", + "not-catalog", + "held-tool-names", + "current", + "edited", + "unmapped", + "background-work", + "requirements-changed", + "rolled-back", + "build-failed", + "undeployed", + "rebuilding", + "conflict", + "failed", + "removed", + "out-of-scope", + "gave-up", + "unfinished", +]); +export type CatalogCopyRebuildOutcome = typeof CatalogCopyRebuildOutcome.Type; + +/** The commit that records the rebuilt source on `main`. */ +export const catalogCopyRebuildMessage = (from: string, to: string) => + `Update the apps framework from ${from} to ${to}\n\nExecutor rebuilt this catalog app from its own installed source on a current framework release. Only the framework version and, for releases before 0.0.1-beta.90, the account declaration's scope changed.`; + +/** + * Which copies one apply stage may change, from the host's configuration (Cloud + * `CLOUD_CATALOG_COPY_REBUILD_SCOPE`, self-host `EXECUTOR_CATALOG_COPY_REBUILD_SCOPE`): tokens + * separated by spaces or commas. + * + * - `all`: every copy; otherwise only copies named by the tokens below. + * - `organization:`: the copies an organization owns. + * - `app:`: one copy. + * - `max:`: change at most `n` copies in this stage (rebuilt, rolled back or left part way), + * with `all` or the tokens above. + * + * Empty selects nothing. Each distinct scope is its own stage, an apply run named by a digest of + * the scope (`apply:scope-`): a finished stage completes its run, and a new scope starts + * another run whose first pass walks every copy again. Copies outside it are recorded + * `out-of-scope` and never read. + */ +export interface CatalogCopyRebuildScope { + /** The stage's journal run. */ + readonly run: string; + readonly all: boolean; + /** Owner IDs, as items name them (`organization:`). */ + readonly owners: ReadonlySet; + readonly apps: ReadonlySet; + readonly max: number | undefined; +} + +/** The scope configuration could not be read; nothing is applied. */ +export class CatalogCopyRebuildScopeInvalid extends Schema.TaggedError()( + "CatalogCopyRebuildScopeInvalid", + { token: Schema.String }, +) {} + +/** + * The outcomes of copies a stage changed, which its `max` counts: deployed and active, put back + * after its deploy, or left part way. + */ +export const catalogCopyRebuildChanged: ReadonlyArray = [ + "rebuilding", + "rebuilt", + "rebuilt-adds-tools", + "rolled-back", + "unfinished", +]; diff --git a/packages/app-management/src/contracts/data-steps.ts b/packages/app-management/src/contracts/data-steps.ts index 51841bd466..2cd648e052 100644 --- a/packages/app-management/src/contracts/data-steps.ts +++ b/packages/app-management/src/contracts/data-steps.ts @@ -14,12 +14,38 @@ import { Schema } from "effect"; export const DataStepMode = Schema.Literals(["report", "apply"]); export type DataStepMode = typeof DataStepMode.Type; +/** + * What the journal holds for an item in this run before it is handled again. An apply that changes + * an item in several writes records an in-progress outcome before the first (`record`), so a run + * that stopped part way finds it (`previous`) and finishes the item rather than reading its + * half-changed state as someone else's. The outcome must be one of the step's retry outcomes, so a + * stopped pass revisits the item; the item's final outcome replaces it. + */ +export interface DataStepItemProgress { + /** + * The item's latest recorded outcome in this run. In an apply run that has none for it, its + * outcome in the step's latest earlier apply run that recorded it, so an item a stopped stage + * left part way is finished by the next stage (see {@link DataStep.applyRun}). + */ + readonly previous: string | undefined; + /** Record `outcome` for the item now, before it is handled further. Apply only. */ + readonly record: (outcome: string) => Effect.Effect; + /** How many items of this run have one of `outcomes` recorded now. */ + readonly count: (outcomes: ReadonlyArray) => Effect.Effect; +} + /** One unit of a step's work. Reports identify it by its ID and owner ID only. */ export interface DataStepItem { readonly id: string; readonly owner: string; - /** Handle this item and name the outcome. Failures are outcomes; report mode never writes. */ - readonly run: (mode: DataStepMode) => Effect.Effect; + /** + * Handle this item and name the outcome. Failures are outcomes; report mode never writes. An + * item may instead return {@link dataStepPaused} when its step's pace stopped it part way. + */ + readonly run: ( + mode: DataStepMode, + progress: DataStepItemProgress, + ) => Effect.Effect; } export interface DataStep { @@ -39,8 +65,37 @@ export interface DataStep { * of its result under a new report label. Otherwise an applied step has nothing to report. */ readonly reportsAfterApply?: boolean; + /** + * The journal run that `apply` records under, `apply` unless set. A step applied in stages + * names each stage's run, so a finished stage completes its own run and a later stage starts + * another, whose first pass walks every item again. Later steps wait for the current one. + */ + readonly applyRun?: string; + /** + * Bound retries: from pass `passes` on, an item that ends with one of `outcomes`' keys records + * the mapped outcome instead, which the step must not retry, so the run completes. Without it a + * step retries an item for as long as it keeps failing. + */ + readonly exhausted?: { + readonly passes: number; + readonly outcomes: Readonly>; + }; + /** + * Whether the run may start another item now. When it answers false the run stops as it does at + * its deadline and the next run resumes from its cursor. An item whose work comes in several + * paced parts asks its step's own pace before each, and returns {@link dataStepPaused} when it + * may not start the next. Only hosts whose runs have a deadline pace, and e2e runs. + */ + readonly more?: Effect.Effect; } +/** + * What an item returns when its step's pace stopped it part way, before work the pace counts. The + * run records nothing for the item and stops as it does at its deadline; the next run handles the + * item again. Progress the item must keep, it records first (`record`). + */ +export const dataStepPaused = "data-step:paused"; + /** Which product's journal tables a host uses; each is created by that product's migrations. */ export type DataStepJournal = "private_hosted" | "private_local"; @@ -78,6 +133,12 @@ export interface DataStepRun { /** The prefix of the single log line each finished pass writes, followed by its JSON summary. */ export const dataStepLogPrefix = "Data step pass finished: "; +/** An item's in-progress outcome could not be recorded; the item must not go on to write. */ +export class DataStepProgressUnrecorded extends Schema.TaggedError()( + "DataStepProgressUnrecorded", + {}, +) {} + /** The journal or a step's item list could not be read. Startup stops; Cloud retries next tick. */ export class DataStepUnavailable extends Schema.TaggedError()( "DataStepUnavailable", diff --git a/packages/app-management/src/data-steps.ts b/packages/app-management/src/data-steps.ts index 22307358f6..88842fcf5c 100644 --- a/packages/app-management/src/data-steps.ts +++ b/packages/app-management/src/data-steps.ts @@ -3,6 +3,7 @@ export * from "./contracts/data-steps.ts"; export * from "./contracts/framework-pin.ts"; export * from "./contracts/executor-app-redeploy.ts"; export * from "./contracts/local-owners.ts"; +export * from "./contracts/catalog-copy-rebuild.ts"; export { createDataStepJournal, runDataSteps } from "./implementation/data-steps.ts"; export type { DataStepRunOptions } from "./implementation/data-steps.ts"; export { frameworkPinStep, pinnedOnly } from "./implementation/framework-pin.ts"; @@ -32,5 +33,11 @@ export type { AgentGrantExpiry, AgentGrantHost } from "./implementation/idle-age export { hostDataSteps, runStartupDataSteps, + startupCatalogCopyRebuild, startupDataStepMode, } from "./implementation/host-data-steps.ts"; +export { + catalogCopyRebuildScope, + catalogCopyRebuildStep, +} from "./implementation/catalog-copy-rebuild.ts"; +export type { CatalogCopyRebuildHost } from "./implementation/catalog-copy-rebuild.ts"; diff --git a/packages/app-management/src/implementation/catalog-copy-rebuild.ts b/packages/app-management/src/implementation/catalog-copy-rebuild.ts new file mode 100644 index 0000000000..bf71c7e495 --- /dev/null +++ b/packages/app-management/src/implementation/catalog-copy-rebuild.ts @@ -0,0 +1,675 @@ +/** + * Rebuild untouched copies of official catalog apps from their own installed source on the target + * `apps` release, once. See notes/catalog-copy-rebuild.md. + * + * Report mode reads only: the app, its version rows, its versions' source straight from the + * host's store (`readVersionSource`, never `apps.source`, whose Cloud store fills a cache on a + * miss), its `main` history (never the working tree, whose first read on Cloud stores a cache + * object and can create the repository), the SQL rows of its background work, and a build that + * keeps nothing (`apps.build`). Every write is in `apply` and `finish` below. + * + * Apply changes an app in several writes: deploy (which activates), then either a rollback or the + * commit to `main`. It records `rebuilding` for the app once its check build passed, before the + * deploy, so a pass that stopped part way, or a run whose pace stopped it before the deploy, finds + * the record and finishes that app (`resume`) rather than reading the new version as someone + * else's or building its check again. + * + * Apply runs in stages: each scope (`CatalogCopyRebuildScope`) is its own journal run, and copies + * outside it are recorded `out-of-scope` without a read. An app an earlier stage left part way is + * finished first, whatever the current scope. + */ +import { + readVersionSource, + sourceFilesEqual, + type App, + type AppCopyOrigin, + type AppRequirements, + type BlobStorage, + type Executor, + type SourceFiles, + type StorageError, + type VersionBuildFailed, + type VersionId, +} from "@executor-js/sdk/core"; +import { Effect, Schema } from "effect"; +import { SqlClient } from "effect/sql"; +import { + dataStepPaused, + type DataStep, + type DataStepItemProgress, + type DataStepMode, +} from "../contracts/data-steps.ts"; +import { + CatalogCopyRebuildScopeInvalid, + catalogCopyRebuildChanged, + catalogCopyHeldPackages, + catalogCopyRebuildMessage, + catalogCopyRebuildTargetRelease, + catalogCopyToolsAddedPackages, + catalogPackageScope, + type CatalogCopyRebuildOutcome, + type CatalogCopyRebuildScope, +} from "../contracts/catalog-copy-rebuild.ts"; +import { + compareReleases, + declaredPackage, + declaredRelease, + sourceDigest, + upgradedFiles, +} from "./catalog-copy-upgrade.ts"; + +/** + * The host services the step reads and writes through. A host lists the step only when it passes + * `catalogCopyRebuild`: Cloud always, self-host when its operator turns it on, local never. + */ +export interface CatalogCopyRebuildHost { + readonly executor: Executor; + /** The host's own store of retained version source, without any cache in front of it. */ + readonly blobs: BlobStorage; + readonly catalogCopyRebuild?: { + /** + * Called after a copy was rebuilt. Its new version leaves the app's webhook sources pending; + * Cloud wakes their reconciliation here, and polling recovers a missed wake. + */ + readonly rebuilt?: (app: App) => Effect.Effect; + /** Which copies apply may change. Reports ignore it and cover every copy. */ + readonly scope: CatalogCopyRebuildScope; + /** + * The most compiler builds (check builds and deploys) one run of the step starts. It is asked + * before each build: a run stops before a copy, or after a copy's check with `rebuilding` + * recorded, and the next run resumes it. Only a host whose runs have a deadline paces (Cloud), + * and e2e runs. + */ + readonly pace?: number; + /** + * The pass from which an app still `failed` or `conflict` is recorded `gave-up`, and one still + * `rebuilding` is recorded `unfinished`, so an outage that never ends completes the stage. + */ + readonly passes: number; + }; +} + +/** + * Read a stage's scope (see {@link CatalogCopyRebuildScope}). Its run is named by a digest of the + * scope's tokens, sorted and without repeats, so the same scope resumes the same stage. + */ +export const catalogCopyRebuildScope = (text: string) => + Effect.gen(function* () { + const tokens = [...new Set(text.split(/[\s,]+/u).filter((token) => token !== ""))].toSorted(); + const owners = new Set(); + const apps = new Set(); + let all = false; + let max: number | undefined; + for (const token of tokens) { + const [kind, value = "", ...rest] = token.split(":"); + if (token === "all") all = true; + else if (kind === "organization" && value !== "" && rest.length === 0) owners.add(token); + else if (kind === "app" && value !== "" && rest.length === 0) apps.add(value); + else if (kind === "max" && /^\d+$/u.test(value) && rest.length === 0 && max === undefined) + max = Number(value); + else return yield* new CatalogCopyRebuildScopeInvalid({ token }); + } + // A maximum alone names no copies; say `all max:` for any `n` copies. + if (max !== undefined && !all && owners.size === 0 && apps.size === 0) + return yield* new CatalogCopyRebuildScopeInvalid({ token: `max:${max}` }); + const digest = yield* Effect.promise(() => + crypto.subtle.digest("SHA-256", new TextEncoder().encode(tokens.join(" "))), + ); + const hex = Array.from(new Uint8Array(digest).slice(0, 8), (byte) => + byte.toString(16).padStart(2, "0"), + ).join(""); + const scope: CatalogCopyRebuildScope = { + run: `apply:scope-${hex}`, + all, + owners, + apps, + max, + }; + return scope; + }); + +const inScope = (scope: CatalogCopyRebuildScope, app: App) => + scope.all || scope.owners.has(app.owner) || scope.apps.has(app.id); + +/** + * The in-progress outcome apply records once an app's check build passed, before its first write + * to the app. + */ +const rebuilding = "rebuilding" satisfies CatalogCopyRebuildOutcome; +/** `rebuilding` past the host's retry bound; the next stage still finishes it. */ +const unfinished = "unfinished" satisfies CatalogCopyRebuildOutcome; + +/** The compiler builds one run of the step has started, which its pace counts. */ +interface Compiler { + builds: number; + /** The most builds one run starts; unset, no bound. */ + readonly pace: number | undefined; +} + +/** Whether the run's pace lets it start another compiler build. */ +const admitted = (compiler: Compiler) => + compiler.pace === undefined || compiler.builds < compiler.pace; + +/** The reviewed targets, imported when a pass lists its items, so they stay out of startup. */ +const reviewedTargets = Effect.tryPromise({ + try: () => import("./catalog-copy-snapshots.ts"), + catch: (cause) => cause, +}).pipe(Effect.map((module) => module.catalogCopyTargets)); + +const Busy = Schema.Array(Schema.Struct({ busy: Schema.Union([Schema.Boolean, Schema.Number]) })); + +/** + * Whether the app has background work a new version would reconcile: schedules, webhook + * subscriptions, workflow runs or profiles. Read-only. + */ +const backgroundWork = (app: App) => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const rows = yield* sql`select ( + exists (select 1 from executor_schedules where app = ${app.id}) + or exists (select 1 from executor_webhooks where app = ${app.id}) + or exists (select 1 from executor_workflow_runs where app = ${app.id}) + or exists (select 1 from executor_installations where app = ${app.id}) + ) as busy`.pipe(Effect.flatMap(Schema.decodeUnknownEffect(Busy))); + const busy = rows[0]?.busy; + return busy === true || busy === 1; + }); + +/** + * Whether a copy's origin is an install from an official app feed: a package in the catalog's + * scope, recorded with the feed's own `apps/.json` source document as its reference, as every + * feed install has since the feed shipped. A copy of another app records `app:` and the + * parent's display name, which anyone can set, so it is not one. + */ +const catalogInstall = (origin: AppCopyOrigin | null) => { + if (origin === null || !origin.name.startsWith(catalogPackageScope)) return false; + const reference = URL.parse(origin.reference); + return ( + reference !== null && + (reference.protocol === "https:" || reference.protocol === "http:") && + reference.search === "" && + reference.hash === "" && + /\/apps\/[^/]+\.json$/u.test(reference.pathname) + ); +}; + +/** JSON with object keys sorted, so equal values compare equal whatever their key order. */ +const canonical = (value: unknown): string => + JSON.stringify(value, (_key, item: unknown) => + item !== null && typeof item === "object" && !Array.isArray(item) + ? Object.fromEntries( + Object.entries(item as Record).toSorted(([left], [right]) => + left < right ? -1 : left > right ? 1 : 0, + ), + ) + : item, + ); + +/** + * Whether two versions declare the same requirements: each account requirement's name, scope, + * cardinality and provider ID (which hashes the whole provider definition but its hosts and setup + * help), and the same SQL, document store and events. Capabilities name what the framework + * supports (`toolIndex`, `sharedDefinitions`, ...), so they differ between releases by design and + * are not compared; neither are icons or an account check's presence, which change no fit. + */ +export const sameRequirements = (running: AppRequirements, rebuilt: AppRequirements) => { + const accounts = (requirements: AppRequirements) => + Object.fromEntries( + Object.entries(requirements.accounts).map(([name, requirement]) => [ + name, + { + scope: requirement.scope, + provider: requirement.provider, + cardinality: requirement.cardinality, + }, + ]), + ); + const rest = (requirements: AppRequirements) => ({ + sql: requirements.sql ?? false, + database: requirements.database ?? null, + // Builds before protocol 11 declare no events; an empty record declares none either. + events: + requirements.events === undefined || Object.keys(requirements.events).length === 0 + ? null + : requirements.events, + }); + return ( + canonical(accounts(running)) === canonical(accounts(rebuilt)) && + canonical(rest(running)) === canonical(rest(rebuilt)) + ); +}; + +/** + * Whether a build failure says nothing about the source: the build could not install a + * dependency, such as `apps` itself from an npm registry it cannot reach. Another pass retries it, + * as it does a build the host's compiler or runner did not answer (`BuildUnanswered`). + */ +const unreachable = (error: VersionBuildFailed) => error.stage === "dependencies"; + +/** + * The build of one upgraded source, by its digest. A pass builds each reviewed target once however + * many copies hold it. A build that failed for a reason outside the source is not kept, so the + * next copy, and the next pass, tries again. + */ +type Built = + | { readonly kind: "built"; readonly requirements: AppRequirements } + | { readonly kind: "build-failed" }; + +type Target = { readonly owner: App["owner"]; readonly app: App["id"] }; + +/** A retained version with its requirements and files, read past any cache. */ +const retained = (host: CatalogCopyRebuildHost, target: Target, version: VersionId) => + Effect.gen(function* () { + const row = yield* host.executor.apps.version({ ...target, version }); + const files = yield* readVersionSource(host.blobs, row.id); + return { id: row.id, requirements: row.requirements, files }; + }); + +/** The app's versions, oldest first. The first holds the files the install copied. */ +const oldestFirst = (host: CatalogCopyRebuildHost, target: Target) => + host.executor.apps + .versions(target) + .pipe( + Effect.map((versions) => + versions.toSorted( + (left, right) => + left.createdAt.getTime() - right.createdAt.getTime() || + (left.id < right.id ? -1 : left.id > right.id ? 1 : 0), + ), + ), + ); + +const rebuildApp = ( + host: CatalogCopyRebuildHost, + listed: App, + mode: DataStepMode, + progress: DataStepItemProgress, + targets: ReadonlySet, + builds: Map, + compiler: Compiler, +) => { + // An earlier apply, of this stage or an earlier one, recorded that it was changing this app + // and stopped before its outcome. It is finished whatever this stage's scope. + const resuming = + mode === "apply" && (progress.previous === rebuilding || progress.previous === unfinished); + return Effect.gen(function* () { + const target = { owner: listed.owner, app: listed.id }; + if (mode === "apply" && !resuming) { + const scope = host.catalogCopyRebuild?.scope; + if (scope === undefined || !inScope(scope, listed)) return "out-of-scope" as const; + if ( + scope.max !== undefined && + (yield* progress.count(catalogCopyRebuildChanged)) >= scope.max + ) + return "out-of-scope" as const; + } + const app = yield* host.executor.apps.get(target); + if (app.activeVersion === null) return "undeployed" as const; + if (!catalogInstall(app.copiedFrom)) return "not-catalog" as const; + if (resuming) { + const resumed = yield* resume(host, app, target); + if (resumed !== "restart") return resumed; + } + const running = yield* retained(host, target, app.activeVersion); + // The running files' own package is the identity the reviewed digest below covers. + const pkg = declaredPackage(running.files); + if (pkg === undefined || pkg !== app.copiedFrom?.name) return "not-catalog" as const; + if (catalogCopyHeldPackages.includes(pkg)) return "held-tool-names" as const; + const from = declaredRelease(running.files); + if (from === undefined) return "unmapped" as const; + const order = compareReleases(from, catalogCopyRebuildTargetRelease); + if (order === undefined) return "unmapped" as const; + if (order >= 0) return "current" as const; + + // Untouched: the running source is the app's first version's, the install's files. + const first = (yield* oldestFirst(host, target))[0]; + if (first === undefined) return "conflict" as const; + const installed = first.id === running.id ? running : yield* retained(host, target, first.id); + if (!sourceFilesEqual(installed.files, running.files)) return "edited" as const; + + // Only the reviewed upgrade of a published catalog snapshot is ever deployed. + // An unmapped install is logged by its package, release and digest only (catalog content, no + // identity), so its snapshot can be reviewed and added to the targets by a later step. + const next = upgradedFiles(running.files, catalogCopyRebuildTargetRelease); + if (next === undefined) { + yield* Effect.log("Catalog copy has no recognized upgrade", { package: pkg, from }); + return "unmapped" as const; + } + const digest = yield* sourceDigest(next); + if (!targets.has(digest)) { + yield* Effect.log("Catalog copy has no reviewed target", { package: pkg, from, digest }); + return "unmapped" as const; + } + + // And `main` holds only the install: a repository not created yet starts from the install's + // files, and one created has only its first commit. History is read, never the working tree. + if (app.repository !== null && (yield* host.executor.apps.history(target)).length !== 1) + return "edited" as const; + + if (yield* backgroundWork(app)) return "background-work" as const; + const addsTools = catalogCopyToolsAddedPackages.includes(pkg); + + // An app finished from its record passed its check build before the record was made (below), + // so it is not built again: a pace of one build per run then still deploys it. The deploy's + // own requirements check (`finish`) still guards it. + if (!resuming) { + // The build keeps nothing; it says whether the upgrade builds and what it declares. + const cached = builds.get(digest); + if (cached === undefined) { + if (!admitted(compiler)) return dataStepPaused; + compiler.builds += 1; + } + const built: Built | undefined = + cached ?? + (yield* host.executor.apps.build({ owner: app.owner, name: app.name, files: next }).pipe( + Effect.map((result): Built => ({ kind: "built", requirements: result.requirements })), + Effect.catchTags({ + VersionBuildFailed: (error) => + unreachable(error) + ? Effect.logWarning("Catalog copy check build could not install a dependency", { + app: listed.id, + message: error.message, + }).pipe(Effect.as(undefined)) + : Effect.succeed({ kind: "build-failed" }), + BuildMemoryExceeded: () => Effect.succeed({ kind: "build-failed" }), + BuildUnanswered: () => + Effect.logWarning( + "Catalog copy check build had no answer from the compiler or runner", + { + app: listed.id, + }, + ).pipe(Effect.as(undefined)), + }), + Effect.catch((error) => + Effect.logWarning("Catalog copy check build failed", listed.id, error).pipe( + Effect.as(undefined), + ), + ), + )); + if (built === undefined) return "failed" as const; + builds.set(digest, built); + if (built.kind === "build-failed") return "build-failed" as const; + if (!sameRequirements(running.requirements, built.requirements)) + return "requirements-changed" as const; + if (mode === "report") + return addsTools ? ("rebuild-adds-tools" as const) : ("rebuild" as const); + // The check passed. Recorded now, a run whose pace stops the app before its deploy, or one + // that stops part way, leaves the app for the next pass to finish from here. + yield* progress.record(rebuilding); + } + + // Apply. The deploy is a build the pace counts; a run with none left stops here, before the + // app's working tree is read, and the next run deploys it. + if (!admitted(compiler)) return dataStepPaused; + // Main is read now (this may create the repository from the install's files). + const workspace = yield* host.executor.apps.workspace(target); + if (!sourceFilesEqual(workspace.files, running.files)) return "edited" as const; + // Background work may have started since the check above; the build took a while. + if (yield* backgroundWork(app)) return "background-work" as const; + compiler.builds += 1; + yield* Effect.log("Catalog copy rebuild started", { + app: listed.id, + replaced: running.id, + from, + to: catalogCopyRebuildTargetRelease, + }); + // Only over the version checked above, with nothing activated meanwhile; otherwise nothing + // is recorded and the app is someone else's again (`conflict`). + return yield* Effect.gen(function* () { + const deployed = yield* host.executor.apps + .deployReplacing({ ...target, files: next, expectedVersion: running.id }) + .pipe( + Effect.catchTags({ + VersionBuildFailed: (error) => + Effect.logWarning("Catalog copy does not build on the target release", { + app: listed.id, + message: error.message, + }).pipe( + Effect.as(unreachable(error) ? ("failed" as const) : ("build-failed" as const)), + ), + // Nothing was activated; the next pass builds it again (and checks it again first, + // unless it is being finished from its record). + BuildUnanswered: () => + Effect.logWarning("Catalog copy build had no answer from the compiler or runner", { + app: listed.id, + }).pipe(Effect.as("failed" as const)), + }), + ); + if (typeof deployed === "string") return deployed; + if (deployed.app.activeVersion !== deployed.version.id) return "conflict" as const; + return yield* finish(host, deployed.app, { + replaced: running, + version: { id: deployed.version.id, requirements: deployed.app.requirements }, + installed: installed.files, + next, + from, + addsTools, + }); + }).pipe(keepIntent(listed)); + }).pipe( + Effect.catchTag("AppNotFound", () => Effect.succeed("removed" as const)), + Effect.tap((outcome) => Effect.annotateCurrentSpan("apps.catalog_rebuild.outcome", outcome)), + // One unavailable repository, store or build service must not stop the rest; a later pass + // retries it. + Effect.catch((error) => + Effect.logWarning("Catalog copy rebuild failed", listed.id, error).pipe( + Effect.as("failed" as const), + ), + ), + // A failure, even reading the app, says nothing about how far the earlier rebuild got. Its + // record stands until an outcome shows what the app runs, so the next pass of any stage + // finishes it rather than reading the new version as `current` or leaving it `out-of-scope`. + Effect.map((outcome): CatalogCopyRebuildOutcome | typeof dataStepPaused => + resuming && outcome === "failed" ? rebuilding : outcome, + ), + Effect.withSpan("apps.catalog_rebuild.app", { + attributes: { "app.id": listed.id, "apps.catalog_rebuild.mode": mode }, + }), + ); +}; + +/** + * After the deploy, any failure leaves the app part way: the outcome stays `rebuilding`, so the + * next pass finishes it. A concurrent activation is someone else's choice and is left alone. + */ +const keepIntent = + (listed: App) => + ( + effect: Effect.Effect, + ): Effect.Effect => + effect.pipe( + Effect.catch((error): Effect.Effect<"removed" | "conflict" | typeof rebuilding> => + error._tag === "AppNotFound" + ? Effect.succeed("removed" as const) + : error._tag === "AppVersionChanged" + ? Effect.succeed("conflict" as const) + : Effect.logWarning( + "Catalog copy rebuild stopped part way; the next pass finishes it", + { app: listed.id, error }, + ).pipe(Effect.as(rebuilding)), + ), + ); + +/** + * Finish a rebuild whose version is active: compare its requirements with the replaced version's + * and activate the replaced one again if they differ, or record what now runs on `main`. + */ +const finish = ( + host: CatalogCopyRebuildHost, + app: App, + rebuild: { + readonly replaced: { readonly id: VersionId; readonly requirements: AppRequirements }; + readonly version: { readonly id: VersionId; readonly requirements: AppRequirements }; + readonly installed: SourceFiles; + readonly next: SourceFiles; + readonly from: string; + readonly addsTools: boolean; + }, +) => + Effect.gen(function* () { + const target = { owner: app.owner, app: app.id }; + const ids = { app: app.id, replaced: rebuild.replaced.id, version: rebuild.version.id }; + // A deploy activates its version at once. If it declares other requirements after all, the + // replaced version is activated again before anything else reads the app's accounts, guarded + // by this step's own version. + if (!sameRequirements(rebuild.replaced.requirements, rebuild.version.requirements)) { + yield* host.executor.apps.activate({ + ...target, + version: rebuild.replaced.id, + expectedVersion: rebuild.version.id, + }); + yield* Effect.logWarning( + "Catalog copy rebuild declared other requirements; rolled back", + ids, + ); + return "rolled-back" as const; + } + // The IDs an operator needs to undo this app: activate `replaced` with `expectedVersion` + // set to `version`. + yield* Effect.log("Catalog copy rebuilt", { + ...ids, + from: rebuild.from, + to: catalogCopyRebuildTargetRelease, + }); + if (host.catalogCopyRebuild?.rebuilt !== undefined) yield* host.catalogCopyRebuild.rebuilt(app); + // Main gets what now runs, on the revision just read, if it still holds the install's files. + // Other files on main are someone's work since and are kept. + const outcome = rebuild.addsTools ? ("rebuilt-adds-tools" as const) : ("rebuilt" as const); + const main = yield* host.executor.apps.workspace(target); + if (sourceFilesEqual(main.files, rebuild.next)) return outcome; + if (!sourceFilesEqual(main.files, rebuild.installed)) { + yield* Effect.logWarning("Catalog copy main holds other work; kept", ids); + return outcome; + } + yield* host.executor.apps + .commit({ + ...target, + expected: main.revision.commit, + files: rebuild.next, + message: catalogCopyRebuildMessage(rebuild.from, catalogCopyRebuildTargetRelease), + }) + .pipe( + Effect.catchTag("SourceError", (error) => + error.reason !== "conflict" + ? Effect.fail(error) + : // A conflict means main moved, unless it did not: then the write itself failed. + host.executor.apps + .workspace(target) + .pipe( + Effect.flatMap((now) => + now.revision.commit === main.revision.commit + ? Effect.fail(error) + : Effect.logWarning( + "Catalog copy main changed during its rebuild; kept", + ids, + ), + ), + ), + ), + ); + return outcome; + }); + +/** + * Finish an app an earlier apply recorded it was rebuilding. If the app runs the install's files, + * the rebuild never activated or its rollback finished, and it is handled from the start + * (`restart`). If it runs the upgrade of the install's files, the rebuild activated: finish it + * against the newest earlier version that holds the install's files, the one it replaced. Any + * other files are someone's deploy since; the app is theirs. + */ +const resume = (host: CatalogCopyRebuildHost, app: App, target: Target) => + Effect.gen(function* () { + if (app.activeVersion === null) return "undeployed" as const; + const versions = yield* oldestFirst(host, target); + const first = versions[0]; + if (first === undefined) return "conflict" as const; + const installed = yield* retained(host, target, first.id); + const active = yield* retained(host, target, app.activeVersion); + const from = declaredRelease(installed.files); + const next = upgradedFiles(installed.files, catalogCopyRebuildTargetRelease); + if (from === undefined || next === undefined) return "edited" as const; + if (sourceFilesEqual(active.files, installed.files)) { + // `deployReplacing` records a version only when it activates it. A retained version with + // the upgraded files means the rebuild ran and the install's files were put back since, + // by the step's own rollback or by someone's undo: that choice stands. + for (const version of versions.toReversed()) { + if (version.id === active.id) continue; + if (sourceFilesEqual((yield* retained(host, target, version.id)).files, next)) { + yield* Effect.logWarning("Catalog copy rebuild was undone before it finished; left", { + app: app.id, + version: version.id, + }); + return "rolled-back" as const; + } + } + return "restart" as const; + } + if (!sourceFilesEqual(active.files, next)) return "edited" as const; + const activeAt = versions.find((version) => version.id === active.id)?.createdAt.getTime(); + let replaced: Effect.Success> | undefined; + for (const version of versions.toReversed()) { + if (activeAt === undefined || version.createdAt.getTime() >= activeAt) continue; + const candidate = yield* retained(host, target, version.id); + if (sourceFilesEqual(candidate.files, installed.files)) { + replaced = candidate; + break; + } + } + if (replaced === undefined) return "edited" as const; + yield* Effect.log("Catalog copy rebuild resumed", { + app: app.id, + replaced: replaced.id, + version: active.id, + }); + const pkg = declaredPackage(installed.files); + return yield* finish(host, app, { + replaced, + version: active, + installed: installed.files, + next, + from, + addsTools: pkg !== undefined && catalogCopyToolsAddedPackages.includes(pkg), + }); + }).pipe(keepIntent(app)); + +/** + * The step over every catalog copy on this host. Each app is safe to handle again: a rebuilt app + * reads as `current`, an app part way through is finished from its `rebuilding` record, and the + * commit names the revision it was based on. + */ +export const catalogCopyRebuildStep = ( + host: CatalogCopyRebuildHost, + name: string, +): DataStep => { + const builds = new Map(); + const settings = host.catalogCopyRebuild; + const pace = settings?.pace; + const compiler: Compiler = { builds: 0, pace }; + return { + name, + retry: ["conflict", "failed", rebuilding], + expected: ["conflict"], + ...(settings === undefined + ? {} + : { + applyRun: settings.scope.run, + exhausted: { + passes: settings.passes, + outcomes: { failed: "gave-up", conflict: "gave-up", [rebuilding]: unfinished }, + }, + }), + ...(pace === undefined ? {} : { more: Effect.sync(() => admitted(compiler)) }), + items: Effect.gen(function* () { + const apps = yield* host.executor.apps.list({}); + const targets = yield* reviewedTargets; + return apps + .filter((app) => app.copiedFrom?.name.startsWith(catalogPackageScope) === true) + .map((app) => ({ + id: app.id, + owner: app.owner, + run: (mode: DataStepMode, progress: DataStepItemProgress) => + rebuildApp(host, app, mode, progress, targets, builds, compiler), + })); + }), + }; +}; diff --git a/packages/app-management/src/implementation/catalog-copy-snapshots.ts b/packages/app-management/src/implementation/catalog-copy-snapshots.ts new file mode 100644 index 0000000000..dd28d2472d --- /dev/null +++ b/packages/app-management/src/implementation/catalog-copy-snapshots.ts @@ -0,0 +1,547 @@ +/** + * Generated by scripts/catalog-copy-snapshots.ts; do not edit. The reviewed targets of the + * catalog-copy rebuild: the digest (`sourceDigest`) of each published catalog package tree before + * 0.0.1-beta.140, upgraded by `upgradedFiles`. A copy whose upgraded files have + * another digest is not rebuilt. + * + * Catalog commits read: 43. Package trees: 8021. Listed: 7831, + * as 4239 distinct targets (trees that differ only in their pin share one). + * Packages whose own move to beta.100 (1fefdb42 to 97ba6d9d) was exactly the upgrade: + * 1796 of 1848; the older trees of the other packages are not listed. + */ +const packed = ` +--F3Il2MC4U -1P1Cr92XGY -2qL3IMns-U -4zkGmazIyo -5dIzxDblAY -6BqH2_DihM -6jX17GkQdE -8Mq-EAwzfI +-8fAhnmh5Ug -948Q0vm6Z8 -9xvFZehnt4 -A_XBjv-TDk -Ber4ygQvCc -CUsT2xUD-o -DjpDLoac5A -EQGR31-u8g +-EVdnSK2YLg -FmnFLMRcf8 -JRGI6Pptiw -JkC_KR8cbA -JzpdRR9rQY -K4F0p-Z4O0 -KxyHBiLHlM -Llg7gbu3dU +-Lt8_OMPDec -MWI1oGV2Jo -Mj4JMk5GT4 -Mp64ZNwM5Y -Ms4ek4_Dyo -NeJO_OxzpU -OESKa4cm2E -Orj3QOGiHg +-Pqlxlhx3lg -UW_c5rcSzQ -UmgGpRaUDY -VJBL9HCNQc -VeFo47vnEM -WTHi3gKb-k -XDETdl7wGY -YdRMhkpMGA +-_m99n_iKw0 -a-kKEENRS4 -c3rUtOqaCw -cWrBME6VQk -cfSEkhcpjI -dVVuF4RLIE -ebe7RHO-3Y -hD-UzsV6c4 +-hZWgD8oNsw -hp90Cd5Wk4 -iLSjaZJex4 -ic7TtVhn5w -jWwWJWdoxQ -kym5xH7Q20 -l00XFs6PL4 -l0XPJYGOjo +-lAmZgNgINc -llRH8KK18s -mbFnFrfcfU -nT6perM1oc -o7x_drtc3Q -qAjvFcS99c -roXcSjGxos -uEjagdsV7Y +-v50WndMTRc -vvxjwsJsQo -wHZ0DFs8yY -wa0zcwImbE -wz07bNdREg -xMxdf_8eOE -yExOi_ofRw 0-IBr3xsRRo +000D9ty1VpM 00_03-uT9j4 00kU-5eJnH0 00y1YVLdqzE 03IWB1mGYSM 0454NVQWz94 06dAnG6g_oE 07IimNwlK7Q +07R45mXGaSA 07lEdmMSYH8 086hwvhn16k 08Nm0_6Phvo 09DfZHF__n8 0AapXCJniJ0 0BI8nTAaA_U 0BL7d5kp_gA +0BR0_Ca4fik 0BSg06xsneA 0DDMgOvrD2k 0F_X6JDgv0o 0GC_5Hsa498 0IC3Vhl12GI 0IEdDKUfSaE 0IVdW3t1_m0 +0IpdIK-DLSY 0J2qL9W-Qgc 0LAVVI114Sg 0LnEr-Zj0LE 0N5W_z9xKgA 0PYg_C286W4 0Pe9UFB0TIw 0Q0uJShNvzU +0SvUmP7qjvA 0SvuwK_xkPc 0TbLXQvIC6g 0TvqyOQjfQo 0UBBulkc0RU 0UTO7Ckk62Y 0UqGgOXOO8Y 0WgwdQsYdX4 +0Wrig2bPZSI 0Wy2bwL1DUE 0XLCTZReTEA 0Xs1rTGSZQ0 0YY7T_0Y8LQ 0YiSB8Pkjfg 0ZopRpFcs3s 0_EUJgX7AsE +0_N40cC_G1Y 0_x0ZMDPZcU 0aacAZj55AE 0bDNw0_GfW4 0cGsAvcvFtg 0cKgsSGbuII 0cvFb6yDI3k 0dC-xnneALQ +0eJ98CenKaU 0eMOeT-nKtU 0fBCQecgKok 0gib7CryqNw 0hKoXeHw5B8 0jhdJIvCvY0 0kFIflsEZPw 0kpsbke6-eI +0l1OeHU6lT8 0l3McIt12Tc 0lD78myTFvY 0lqSMe39A3Q 0m9IAb-tBQA 0mMtrVjSThU 0mo5QBJrF2U 0nGQVTE-h5w +0nfkXwp9O9Y 0pzh3Zs9Tz0 0qfTzHGlEbA 0r7fYmRM4ig 0s0oY3C_hIw 0s83CAHshVw 0sU7n8IhFdY 0uWf-XkE19M +0vgIqD6ViBU 0wBY5whTdHA 0wBpBECnaqo 0yz4B8lk-CA 1-NSZdNPuI0 1-RiGwaJk0A 1-nUtBYg68U 10Tc9mKKheg +10joNCTyoDk 11B1L3Q80Og 11K7JlyPyPk 12diYwQweeo 14CtT4gfs1s 14PRGq8c7jw 15PteSuyHf4 17I_ItzHbYc +17xikdvlSUM 18sZoytBKls 1A5lrbPQrfg 1CDSlVEGCJw 1DV9zd1KDPA 1E6cTPDvQsI 1ENClg144Wk 1GnKXJ2eN0g +1HfpabuNoGc 1IbXWa3fX-E 1KE63i_8L60 1KVmIxkA-Fk 1KanJsBCzqM 1MsB0ikkvJc 1OjhwnQx7UQ 1Pdro7flp1o +1QpLGmyIHrM 1RJL8da2IhQ 1T3vnldWG7A 1Tlh8yCrsmA 1Uwd_dT0D34 1VemV0Zlx2o 1W1WIo5yfl8 1WMoZ-hAw3s +1WmjL4QTN3c 1Xdp77p5RSM 1YlNGgz3NQE 1ZZWeACM7EA 1cg9VIoGn10 1d18uu6TUCw 1e5XQCYiPIw 1h5kXZn6DfU +1hvxyIeQPHc 1iI_xr7fz6M 1ipdZH-UZE8 1j52loBfEZc 1kasZiAhPfI 1ktRWUW-hRk 1mabHiKufIk 1nOe0D6hzs0 +1nYnptP_SZQ 1pH4PGhQ7fY 1pl8vkcQ7-Q 1qA7IKJ64XU 1qCZ9CmxxXE 1r6E47wrEYs 1t4biep0A3s 1tgH8Nr_uS0 +1uHJl7hZpPQ 1uW2KqIbHRU 1w1pqRIOo4Y 1woNOeXKm24 1x6LXi8XC5Q 1xCyKWZS-Qs 1xVeAcKGAJ4 1xY3YjPGRqI +1xaVQLTmo_s 1z801-_gJek 2-A0xanTJqU 20VfHW5o6_0 21HrWODrYH4 21QbapQ-Kos 22so899Nsu4 23X4UOndneU +23a8V7nBtDY 23jlLdi28gc 24gsbJnEiAw 25BrXOnSuV4 26LVHic5zaw 28_DQskIQIA 2Bpo0ydWpcs 2C-1uA88Yzc +2Cm_Qk7SO8g 2EVdx0j2HBQ 2ExGyN_hgJE 2FofhpDJ83I 2GF9HSQ0U8k 2GOasM1PgTM 2GiIJQeLbTs 2HJ2swbhAYc +2IZQ_TjwmFo 2JefBpad7bc 2JprkmyzCdY 2Kbn0wXuHGE 2LEOlLCWo74 2MsgQ-qPbGE 2NAjT7U8GUg 2PRiU_7AlhA +2SIzVFaEDqQ 2SnSSbbbT-0 2UDFciiCpHA 2VX65Np5eYU 2WAxjr_pShM 2Xio0y2byck 2YDPpTpAVa4 2Z2Ry8sr6N8 +2_1_ciNTNMY 2_nwfwzAJ20 2af-HYGmuCk 2bAz2t4iKW4 2bQVRFD5OOk 2cyr1HKGAdE 2d1Uxph5GbE 2eKkgf8yw7A +2f3QrEEu96I 2gDNyI-0m1M 2gZiZvN4iTE 2i0vH15wgUo 2j4EbYSLIYk 2jCCh9TvCS8 2jF0oTRlkUg 2k3g6TVBGpU +2kDjBGAwjCs 2keR91W7988 2kuMz3-1-40 2nRaxSZYMco 2nxCq6cAZsc 2oEyVAnFZlg 2oIK7QGcors 2rHwN3lBt_s +2rjRgMtQw6E 2rp0CcwKiuA 2rtlZXtPKmo 2seCN92EXjQ 2tov15ZOWtg 2uymthzq9DA 2xQ8qcHSPYA 2xhadNMpAfQ +2xt2SW8ABek 2ylMyUK-9uo 3-WqbQ9CyrQ 3-jERH2GFaE 3-jSYch_Pxk 30AMiG53l8o 33Wvp_whLP4 34IKEdG2bTs +34eacIkhptY 3AaWr29TU-E 3Ae3r7BzXMU 3Ao0EUn14gA 3BCbfpBMoi0 3C1un12T6UY 3C6ErMC_UX8 3C_WOGrEhhE +3DqovoOGobs 3Et1KFqRltU 3Eya_M_-TIg 3Fb5Tl-tw8E 3GV45BKI2tY 3GbBFqg9wOw 3J33k2zJvv0 3JsPRIQZdUE +3K_xxdB1FHg 3KurKWjzMSo 3LU8POw5Lao 3M-cPg5LeLA 3M2gq0BybKU 3NvD-QQiDdk 3O8G8q-Li3o 3OHBfMwibfo +3OxFkUij6sk 3PWx6rH2Ntw 3Qr3GkqE7Us 3TSrTyzO7Zw 3TVkoTwVqxM 3TabUiKeGZg 3TnnhW4BeYs 3V1EArfnNiI +3Vi6b4libzo 3Xta7l3A0N8 3YPzFuVDPZA 3_evZZ3RqNg 3beOnyD0VKg 3c8FMd4bcxo 3cVlmRFNr5A 3eD6dkf7Qfk +3g8FjJt61SA 3guNP6Q5FoE 3gwVxxi7gvw 3i7UI6WndeQ 3iZLyRTDQAs 3izS4ce7Yzk 3kUVEJB8t14 3lUqrOU2R_M +3lnj7XHVnpw 3lz07sefHHA 3m9Olj63mjE 3mELk2zEFds 3n4EAeahZVI 3nUcrEt0EEI 3ntt5rNW89s 3oeoTElNoR0 +3oxNSu-pgxk 3p31nn-h6J0 3qT4h4-cPWQ 3quqSpw1_pA 3r1O1ktbqks 3rCH0Fi0LTA 3rMA98FDjwk 3rZU8PIH-Jw +3rfasawbjUU 3sR-GntptHU 3u2C-EPPT2k 3uRKfdW7sPU 3vXfAt1vAfY 3vqAmX6DIaM 3vyDa8FmvEQ 3wJIad3dDHc +3wrRvbzKIXA 3xOeCBhiV9Q 3xkbygrAte4 3xmAniwoq0s 3yjw3h6XFIA 3zpzC81COgU 402ju6vO3Gc 40N-fVu8eqs +40TTgiGVjms 40XgiGPTkOQ 421JaIiL-4E 42MDi7qxFxY 42Sm0TtjrL4 42qYv_I7CwI 43EGp9RhzHA 45RYPbBsiu8 +475HPknkbrA 48Opl9AotMA 48WDTu7gdRU 48s3MAABv9I 494t1qPbkpw 4A8ugws2cr0 4C5aqTPp6vo 4DLB6tR9UxM +4DQdbTh2KzI 4E11_KHgBuo 4IF7T0RRtIU 4IkwSbTRLv0 4Io62D_kb_I 4IrtKZhrXM0 4JsUL7U1q2I 4KXW2ivNz0s +4KepmsV1kGc 4LFOhQA7Miw 4MISHNgoHmo 4MO0j8E7RQo 4OfQn99Hup8 4PBWlSY7MxI 4Q6tt_jsu2A 4RG1LSKGSRA +4SNs7ihmrTs 4VOD9-CoyxE 4W2PRMZABq0 4WTEtNEnWV8 4X-YRImOUkI 4ebuh3zQE5k 4eiRPYpDpD8 4em1gBIa86E +4hOhDc-jQbE 4jps86lOr8U 4k1VpufwSrk 4nHIa-dqV-E 4o6AiM5b02k 4oIw_ioNa_4 4oeDKg8I0Uo 4p1aqHvOerM +4r6D62mIKj0 4re3nVtEikw 4uRdq0XmV1c 4w5rFAeaVxo 4wEZvgvuCXo 4wrT6LjMznc 4xFKzzM23M8 4xurpIvhgz4 +4yKvE5g3xhE 4zrb5j5c49Y 50byzyr3cYY 50rGtrgij2Y 52VltIV9s-g 52nzq-HItf0 534A5niEdmg 54hFFOAfsk0 +55Psce7LHfY 55qVoP3Djxo 564m6rwgc4I 56sPAFdG0hE 59LdkelYut8 5AARs0NePM8 5AY_MF6t_oQ 5Acu8nOh0yM +5DLIetWrud4 5DOdpK5mbQw 5DopeAsjdxg 5ExwTc1hNog 5G6-A4H6S6E 5HnlN-lWEjM 5JI4p87F6Y4 5M0es7s-zqc +5MZk5SlnMyE 5NqK2Z5nVd4 5PIVr8d70Ns 5Q-dVw_OQhI 5QtOcLw_EfI 5RfoWOFmGZM 5Ro2XYm51Zo 5Sw4CTcYQU8 +5T7mb_QYJKk 5Xy6ZCKEXQA 5YIWcBgOXVo 5Yw_iSDOWng 5ZEqV_zr3oQ 5ZFogtQAkbc 5__2He5lZH4 5a_lPvGxj4U +5acfsI9Ie1g 5alTuGoC-Qo 5bXZK9fjf6I 5bw7KWVos5U 5dOAyP_i_Hs 5dglvSE5Buw 5fk6gWnVLoA 5gBf44T5Z7M +5gYxZPAGAQk 5gyAltYcSUo 5hYJKKu6flY 5i1luXfPTys 5iySp5E_2B8 5knnvGuxbDg 5l4i4vgIBMY 5l_rwcg1gos +5lmkV6nKpQU 5msVzcN7cdI 5oXxRQ8aKl0 5oeGipzjkKU 5ptZ3Ht_CdQ 5sLypj3DkCE 5sOuhA69e0Y 5vO_ZyQYdLI +5w7RQ8G5M4o 5xfLEprq4kI 5yuX-QK4HkU 5zj5heBjJKY 6-s6px0M2YY 611YtaQulC4 61OMQymNgfo 63eK9DCgjzI +63zIH4Dgg-0 64WNmuyE4-I 65M3boWgxc0 66RNbegjO94 66uVvJr7Ews 69Yj2oiTzQI 69ZogRKxalA 6A2e5NRRL00 +6AQiv3UHAa4 6BNy3VwYiPM 6C0kd_kRRZ8 6C2IQd4U7rU 6CnpomGlUxo 6DLQuplniyA 6DOHNhgTuo4 6DruW1HmIIs +6DwaVQw2vZ8 6G4q24bq7Bw 6IE9Jtr5ItA 6K1zA2d45UA 6KpGv5VLCwQ 6Ks4uBk_gU8 6L6Io1FlYcg 6LV2v4cYVns +6MCe6H3UzuY 6NHFoQXSjHY 6NgH-dNPKQ0 6OF9l3WkjH4 6Oqhmw2eNWE 6Or1K5OuexM 6OsejVsfzTM 6P3MZI3LxQQ +6PswcP6ImFw 6RGi0zHsb0A 6RbUe3jfow4 6RqmvzuWWj0 6S49509kO4U 6TNFoxhbWz8 6USJOdrbDzs 6Vg6DJe1l0A +6W8W2BNEYLc 6Wwd8f1dDpM 6XPr6D_b7IY 6YTrg1OcifM 6YaIrCSzUEg 6YuzU5cN_NQ 6bNyDtTmXYA 6bXbyzfJ4e8 +6bjV1PWSkNg 6c6AX7jZ2q4 6cho5GMsAMU 6ds6Ht9ux-M 6efXHKiDVoI 6f0FkdkLduU 6fjUWcMmgtM 6fqIP1Bku9w +6gAknyAxBJ0 6lHPz9zad1s 6mfC4Kl84Uc 6oihL6FUTCg 6ouo3m38Vec 6pcf0Kf9wJA 6qaYl1i31JE 6tr1Rl0ww4w +6uLJNIsYFew 6vpr9mtauTM 6xbSS0mBLe4 7-rQrZwae-M 7-t6mh8zX-o 70q5X5KN3gg 74vQBiYc4I0 76ws4YSdQWo +770R8gr9m8Y 78JppfoYNGs 78jnSAaiAeY 793XkdvRA4g 79EyedhVNG4 7Ag98V1vktA 7CzzwlS-Exs 7ELEazCOgRE +7FRwPF7Gu1o 7GDWSFPQLRY 7H1CBYwI230 7I9MyuEFklg 7LYe6RFTxYY 7Lbm4zBPfP4 7MHh4wWyEj0 7MO2N5uVTWU +7Mw3REt_shs 7NDBsblrvqU 7NGfwdI8RRA 7NKk6pvgXDE 7Njj9Av63NQ 7NxWiLufQWw 7PAb_f_p8Ms 7RnfVir8oKY +7SAWcKUR04Y 7SDJadChvrg 7TI8C5Dy3OY 7TXmHYvFNtE 7UYUzERsMKE 7WTK3Gy1DKs 7WdZHA7ZuW0 7WlOCX1Ef6w +7YFkmWC6tfQ 7amNGm9epA8 7bt4lNIDGSA 7c55qQztxHA 7cj2geQtY3g 7dbGSIxgdok 7eT3UIPq5QU 7eXcNVmp0No +7f3WUhDWSb4 7g6mFNqgzWw 7hJF52EKBPU 7l0MxNCMTwk 7m2RU_AGjoo 7mYul10O5qo 7mt5_Q5i0Is 7n477nwfhDA +7nwMSNUf5Kw 7oBDWVt4KgQ 7or2FDrvcmQ 7p-zwNHMknE 7pgeIo1FeLg 7poHwkP3viA 7sJDVrrWolk 7swSRMKSXho +7tmmYoiyNcI 7tyE6DoOT9E 7uvdJU1MRZM 7v_PY5Wy5FI 7vdFpiLBahQ 8-7wwL-ziVI 8-loC9_eBjs 81CVCGJrT-8 +81WjpMttBZE 81w8GOaenBg 83dkHNbBC7A 83oNlg9Dc_k 84N090FucoM 86rysXbXXeY 87ZgNsbpUNU 88roOKyF8gg +89j29ZV8udw 8CZc4tcONNA 8DOmv6jh0vU 8E_5VRUF0hk 8Eo95ZdAgKk 8Getr6BCwgs 8J0Qk0SXpRY 8KU83FY-BVw +8MIPQn9xaGo 8MSVoDsgM04 8Np75uUMUZY 8O5RL78xAhs 8OLMDbPIr2M 8OfOB53QE4Q 8PGYy0xunZ4 8PTD7IhyXpw +8Pr1Ui-VpXE 8R2Mnb4XQbA 8RybMCUZII8 8TBWFwYzn3k 8Ta5BxWqoZM 8Tye75cnZZA 8UYCUgTRT6g 8VE1f0UBCQA +8Vt_F3CNXig 8XdwELQTk9U 8_6QzsdiPvA 8d6oAbpf65M 8dvVpdj6uDM 8flJwbIP_UE 8gJNXJQij2A 8h6z308kk8o +8hgwXFKbhcE 8jMwIzjw1f0 8kGFVFacz6M 8mzseNUh7-8 8o3HHymRORI 8p57XmTTxng 8pzIa3Ljp_g 8qlZZbfykCc +8r-7B4I0v08 8rnNY6oHfXY 8tVmgRpqPK4 8tl6FJXcVpQ 8uJ7Bl4o9k8 8uP3corjqmk 8uTCB0hKeic 8wCjYVKoZ84 +8xVCxAR6RCo 8x_tZIhf5fg 8yLNNWTXRe4 8yRmL01BWvM 8ylchwRee6I 8yljZZ1c9Qo 8ymOdd3k9RI 8zFJloclEFU +8zG9bO4hOCk 8zu10dHlssg 9-Ryc2cj1c0 9-mu4-1AymA 91iSslizW_s 91qhlEJpaMw 92nOPC1c9pU 94rKz2SLEA0 +97mCxPMWRdY 98SlU2DCw3E 994t7A8WeZE 9AjKMXhjp4A 9E1AL2gBMUQ 9E1wxkxfS0E 9EiaEiAGa2Q 9Fc2zfIjJ1U +9GaFAB3oIvU 9GqXOYlOSMc 9HPBWg-xat0 9HPDF10jsFg 9HhA4BsbLvI 9HlQLWm7Los 9Hv3Hy4rFmE 9K4ikvbRyIQ +9L00YFoNYn4 9MjPVjwynMo 9O0071NRIFI 9O2qHW6C70s 9O9bVepQmXM 9SF78mL6PUA 9SbQqUb6OSw 9T6BPRbmLVY +9TYJUKUkMAA 9UiO6-RGmzk 9VJRiiBBHt8 9VTAE3qKCi8 9VeQkjev7aw 9WzrKz9dVZo 9XixjjVpGP8 9YPAM3KuUH0 +9Yl31gVLp6Y 9ZrAM9IdUt0 9_3oTHBbEuM 9aC0wers8L4 9atJguMNbEQ 9av5cOe1VUA 9d9Ee2VDrzY 9fxPwE6KsGw +9hcVYG-u7Sk 9htkzfvqGcY 9iIG6ZPQ0cE 9jRycx6zVyM 9kQw5wKLG9M 9kS9tyI9G1s 9lZH8boMyHo 9mZdClxcn0A +9miTjOuCUG4 9nDfoo6SoEE 9n_djdI5RqE 9o0Hrs5ypy8 9qGc_hGEpN4 9quX7pNO-w4 9r1Q83Xvs5w 9tQQ9nsdGD8 +9tWLvafKl5E 9uQD_JoiFgg 9ugRdvN2Psk 9wUHcmkmkVY 9xx5uBc05_w 9y3paTN6xK4 9yFhypiFZKY 9zp3dkC2yTo +A0Ve18x6QH4 A2WEGHnxOHs A2YuZiaHXXY A2ucNsVHgTo A3o_3rldtKA A64mvBv84Zo A7UGhmEUXtg A91KiaSpGaA +AA6xlE92NnA AAoU9xkem0o ABO95-nEAwc ABtigb1LbJQ ADP_uMyJ-Lc ADxLXQzQHY0 AEBvpSDHwTs AFDTDAErcF0 +AGdwUXKRW3g AGsWRd7caNA AHkAdQ2pv9k AJzPJz8Ze10 AK-DKxVgc4U ALX5biC2b5w AM11oMU31OU AMKntWNInX0 +AMcwq56bGhE ANldYMhMCn0 APQbYVd5vdg AR1XvdApsLc AR98u3ZKqYc ARbX-_ze92U ASeb2tO8oZU AUToWInuTDU +AVGZXm-MigI AXZJSP5M15s AXqgabcBt28 AY7t-EOw3xg A__Ruh7q8pI A_r7QrPlJHI Aa16-5Maerc AavAR4c7NLI +AbFaThTsQTg Ac7LcHjbFxI AdESsHVdAIk AeS88Y1_zeE AgnJ_ahODbk AgnxI0ZKy4c AhJPJ_mxGjY AhLeZ63h2vI +AjINaarcxZo AjZPIolg_wM AkG4aRxZ0b0 AlWxeJUVJ38 AnwCBxIkgsg AoHY9GmhxaU ApNRavO_bvI AqMeXXdzxaE +ArdsQvzhIOc AsyIFQ6I1DM AtLuF75Tgmc AtpT_H-MZE4 AuB4C78Ek9Y Auhv56rBVME Aul3KCDz87c AvEYsBeTWtE +AxfIavvHmtM AzRJtiMhibg AzTX3Hdo3qw B-QIrq2z0h0 B07zfL3LaEg B0RIWcAbq8A B1Oa8zwmOtQ B1Tumm_DHzs +B1zCTBNlKaU B2Stm8Y0veg B2_88IkV29Y B4F9vdcuaSQ B4d770vjpOI B4wcUG00lmk B4zsDLHDkMo B62glGg1xFY +B84xLLNfZNk B8vqo1e0mag B9K7pAt_aPI BAakoxW8B9Q BClpmua6M8w BDHx3eE4b4s BEBtDrefNxI BE_MX-DycUA +BErOHrsFkj0 BFmpHCPddyU BG0mvLZP3CY BG8RM6uqOcM BGck6tMHre8 BINRaLByd5E BIlTSOx-NPw BJ8NjmtRsVQ +BJC7GXv1CiQ BJne2efGe1U BKVu51xnZx4 BLN5QhX8CD4 BLVprN1peRE BOawtElxJXo BR9YgZ2sTPI BS5Jv9S2JqM +BSH4D4L15rE BSgQyeyl8Ug BSpqwX5YYHg BU4ABeePv8U BUZ5vXTjU5k BUtWwwNcDCI BUtwtdjEAeY BVDm_yxaV0o +BVWYHTQ-EL8 BZL10IEbX7c BZde1FEv-mc B_8k4ssfIfM BcQeX6ygZOM BcXDRH1JYJc BcZxTVyQCmQ BcqCPw2vic4 +BfxE0Q9VIsE BhZGTXWXNw4 BiW80KSaT4I BjWQJSUdz34 Bk4KQ7l-IZ0 BkNc9d_0LAY BkNsuZ6BToc BnPdNxrrYHY +BovBS8u5fsk BpjCQQphNO4 Btj1CSMYZww BuVKxkURbN8 Bv2p47dBknA BwmzedbZUms Bwq8Ok0xtDo By9Idw85zfY +BydCJnJMysU Bz0GfRHnKOU C0G3G_OZL7U C0VAkA4KyOk C18Z4DAoxzU C1s-A7knViI C3qvCe6YoGQ C4RTy_0llpg +C4yagTqx3Zg C5LSiHosZ3I C5hcMQh-Juk C5ojkJS2BeU C6aICxVjbm4 C6vEU5kW3wE C9E9V5tcKfw C9IP44yhEVs +C9oNlGE5IVU C9tQtaPtD_4 CAdvQ2eyKvI CBEafc3jT28 CC4mUXg8zZg CEIrRazLBdI CEfCKRmj3Qw CF7NkWY-mp0 +CG6XkIgjSE0 CHw0BTImTxU CIA1Mcbb_qQ CJORB21Y9bU CL38jP9D-uA CLbu6KCUAKA CM09dffrBCE CNH0lih51nk +CNYkr_x6BLM CPbH8Ie7yXE CRTugEmEOQY CTkyFAppb3I CVGgYixoSrM CVc54AiYfY4 CW92KT3a-xc CXGc7OwVaa8 +CXN-asJZQ7c CYzOJoBHm84 CZJccBUq-_Q C_eG2hpEQ1w C_jaDS_IkaY CaJFsocsgz0 CbbMD9WCvS4 CcHfG9IVPfI +CcnxekIeCpo Cd1oEUS4PP0 Cdkw-60dKv4 CfLcksYS_9c CflbVKyqrDs CgijGOUOxhg CiGAYjPc3W8 CiyznpfRa4Y +CjMn0f4R69Y CjS-q2ZjKZo CmgYBYWRC10 CnIFa9P5VV4 CnT-nqPHX2k CnupoQLXgJg CpnRmHwWrG4 CqFMotThGnE +CqoegAn8WPk Cqri7tDgDwk CrHyN884aEs Cs85fr2ETQ0 CuZyif0onS4 CvZHaIdlW2M CwxlnD5FkAQ CxFmogENFaw +CxLF6vPECH4 CzrQ_RNrgqU D0Q3A7snH48 D1yOEOpwsKU D1yd8L2jWrU D2FGU4oDZO8 D2PU6GwEypw D4C8GpUIXYE +D7AKdeSTwfw D94tLKKW2s0 DDNBdDmLhIo DEAI-UTj3gI DF0BiEWtQ7w DFAQJGhNJN4 DFMgI9rAo40 DFgdiGTtRYs +DFitxq1LzHk DFym3VbzPDs DG0DzVZDsxg DGHT53B8NfA DGaDeP8m4j4 DHzwZxEEnBs DIOJc5P20eo DIOezgPco3Q +DIhYYcrBQ8A DJXRVCUMPGs DKds5CH5j6c DLV66ByxCLo DMRpFNi6NH0 DMxkDrStvKk DNLzW6XfraI DNSYo4AH-_g +DOdWJtcCE6A DQEhkoVOccM DQLWjiIgUd4 DRe9bXA_hWs DVt57jtM8Tc DYY-UKYbQ4k DZztPqtXor8 D_Y265DChLM +Da0U5lrlH0o DaqpoNerqEk DaxTFZD5Y50 DbEJIKKpjVw DbTRsLJzb7g DdD_1Xrd8gs DdUPP_CZGtA De-XhZhOEJ8 +DeZEX04Ae-c Df61mjyf1Cs Df9JfAcW-ik DfvHYoG7kig Dg4lyCETGSE Dg8upLIcVTo DhjOtnEQcVM Dk_Y5ZxEgrg +Dlfj-mN2x7Q DmGvD-WHZTg DnaG3ayqo_o DncEmgNqZhI Dnzfz8-gLgw DpFeN0rZkOQ DqQeUGdJXyg DtboEMKXWXc +DufMQKxV4ts DvGPmFSoPyA DvawMVbL-B0 DyLZhamn5f0 DzyrOdZdVCg E0A9HQM6wjQ E0ecGP7nmZU E1DwZJMypGA +E1mxAHnk494 E2tGl4KwoYg E46XaXw8L4A E6H7L2dcU1k E6I-VdMaw5E E6QlukKkpAc E8-NJs-Xtu4 E9q6k9z6U3M +ED7mgxKPUuk EEbEbfq_jQk EFjnY4Jbaqc EGT4YEFn3tA EHWx-fWlWug EHZwt7auT8g EJFhmixiHQA ELKlNECn-yA +ENCAu33SXSE EO7edRP2ywc EOHszryhwTQ EPh7LZfcgEw EUUqSQA-Yqg EW5BaTf2uY4 E_-agFuNk7c E_2xb6LIqxQ +EaX3VR4Ihxw EaY1PPcpX9A Ec5WCwdq4IY EfcdMoiVfWg EgGSPuSgEeI Eh_pXU5AATM EiDil4VsmAM EiLdxzVo68Y +EiXRvZOWv3c Eitj9_wy0uQ EjAqhIj6tdk EjU48l7-Dd0 EkBb5E2jeGo EkaJ7vRiSmE EksVBAdCN_U ElAKQbwD2mk +ElEZovvAUWY EmJHUTCXDBo EqJXAkYUKa4 EqyuP75yBsI ErFcXY3XLos ErR2zuskRkU Esb9KWVll_Y EscFz3NVaAg +Ets3j7DhTk8 EuQZ7AAwCOE EvKmUbDBD5c EvTIig99PYU EwLkvH9CNfE ExDldQF2eDA Exbo5UedrOI ExhyculxiPM +Ez6-INRpobA EzqG53rUOyw F-fc2VP2to4 F-wiv2SNDeI F0njWjnzAHA F2FHYO0ydn8 F3yUGjY4HsU F6Sm7PJmKfo +F8XsegsBrGc F9-LrrcBQlw F9erG20xpEY FA6Do9guWKc FAJ97XS462E FCKvexJvQTU FCog1dRbCjw FD65LbfGpkM +FFgSVEcBz88 FHBs0Myl3DA FIMgnDadPA8 FJurpUpa_iY FKSKgilBr5k FNEm06PCBg0 FNcMUbuJi9o FO5eVKQUrdY +FOgrnazBleU FPHl35lA6yY FQ11yoGLKHU FQKsDBj3qSY FQ_CtjOB8EY FQfCgRPCAbE FR9kL1BlFHg FRsF4QZQuw8 +FSSL-qiUu9Q FT73a1d_PD4 FTLYXZy9zGg FTdg9Czfkjc FUAavtZ6SaU FUNU5nA_s9M FWposPPGc6E FWxMjehL5Y8 +FYkPCqF2fOI FZmEGxtpyKg F_2BC2iV1do FaAltxQnfQE FaR0DVYyaw4 FaVH9nyFkVI Fb8oGlQULtQ FcgZkbeG8BA +Fd1I6GcYSR8 FeR8F3tAqWk FfMUo5W_P-A FggikIzB64o Fh4DMoZQDks FhHuulbmqpA Fhnev163ivY Fj6sonqrcqI +FkCKcZS1Za4 FlETMjHsAM4 FluJHJ6x79Q FngaVfmrkY8 Fo6LMyEgia0 FswkmxfCnhc FubV31Xgz0s FuufP6vGyqU +Fv5dH43QMgE FvutLHBzrzI FwopjqGBXV8 FxFN23CJDDI FxwGNPgB2wE G-F1PTsgj_s G1EcnaX_qJs G1OgTJPnGjc +G39u85K2s-8 G3bXEyXqlbU G46Dt_3xOIo G4ODAqM9yIk G69XKCtSRDI G6UR5iZwSpg G6_MW25ccuU G6lXFcT73VA +G7eDIRjgu6Q G8YwZ_74EbY GA0Dq0IOc3g GEJK4EYFD2k GEdbyReeF3Y GFk_GAtk5vg GGBx58SSV-k GHVlJyMcWVw +GIupZ2XTLYc GJ98G6hCa4w GJOEvUzkUNA GJlxMssWV5A GKL2lLTlMF4 GKMPQL3J06U GLqSkRgA37s GNHDz5kJYU4 +GNUJKRWGWHw GPpKvwxYSp4 GQ1hpOexlfQ GQ487rcoZBY GR3a6kT2O_4 GSwIZsa1QKE GTTBTQd3iq0 GTn-NHj7Vso +GUPZLhi8Dio GUnvR6J1MAQ GWdm1z3jthI GXvaql-2x-A GYIjfYYbT4k GZm1Sq7ZQ2k GahcJNggd7s GcHAxBgJCJM +Gd1-X8v-7EE GdYepO7hQpQ GeZYq428z_E GfHZwn2Vc1Y GgIbGNiCiWc Gh4qntBmyLI Ghwt4x0hoW4 Gj6QLQ2fGHw +GjJYg7LaypE Gj_eSYix9Sw GkuaSLf_BJ8 Gmg0Z_-lYeg GnMDVBFNUdc GnNKEMFFY3Y GohL3RzjK68 GoinyYUJXrg +Gomawq08vxY GrELjEzE2to GrNwDvHGejU GrfY-4FfYVM Grp03gMLSiM GrpF66cyQng GtOrxmLomGE GtZzoAjclHs +Gt_IYku7y3o GtmKsqUcS80 Gu3MxfyiT3s Gu594tmNSXo GvFrBYHPLBk GvdydguwSFc GwE_5QcZfGc GxCDdWRFB7k +GxN44DCe_4Q GyFcJ4vPefw GycWSAgCRcM GzdCswy0T58 H-Aj-ScCseI H09d0zLmaz8 H0Jl0lY0WxA H129ja0dzvE +H1URrnEiNDc H1gHfeRXkc8 H3m0oO3d9ow H47Bhv3Ykqk H4bBkNK2k2c H5DIGFrcbe4 H6VwVmeAYho H6jSY2bRgk4 +H785P_9LXW4 H7ajf2jPe_w H9ioKnkhZC4 H9jz0pIPc5Q HAF_TgdsoFE HAJzXpzQqGk HCtMaL_xiAI HE94B_ISwkc +HFMRZoF0Nx4 HFdM2FgG9ws HFqtVHR2eRo HFyp9KJeP74 HG25afbSsFA HGNwYnlSBPc HGb27e3Wv0Q HHjBzc6Zbac +HMXH8bNHMLM HN4Lh9RvLpU HOM8gx_tUaM HPYE_24dt_s HQdp2_FQokU HRCFWZH--F8 HS3oSlDPcvQ HV3vlIrtdgU +HVLoOScUOBs HVMnw-qD6qU HXIrHfzW8kU HYdn5GkYS4s HZmvYVgWmn4 Hb5SWIo91VM HbW4E2Cc71U HbgSH8Ng0dk +HbqJ4wVCHvc HhOnuPAPCIA HiAMJuE2oSY HjLZZD9i-Yw HjrSq_5gPUU Hkvh8k7gUbM HlCGDwcE0-o HlWobd4MFQs +HltsfNMRHPw HpMyefZhO9g HqEqIqcnYcg HqIJsRO1qi8 HqlTL0HxaIk HsXn6SwoQHo HvBhmaVQ0f4 HvNGJaIA6r4 +HwPPjiRz-QY HxOGRijKZXs Hxnk_sVtNzc HxpuSHevrQY HyFeV-LPeHM HyjuWUxLOxY I-L3W0S04u8 I-PSYEsQYlE +I12TsRf8l6s I14PmhXXf2A I1j2LNJtnPg I1nfWVu1VrU I2A8_01Lf7g I3gG6Q6aZHE I4uj9hPScoY I5Y7BKVPGJ4 +I6i1M0oAB3I I78t_aJJ8AM I8IrJhC6gGA IBZdKbDushM IDzlssGPQIg IE1gCwS9_Ok IElP4Xxus5c IFGFJBqHyOU +IHIIQbUagIE IHuRJhRnViE IINkZLI50-c IJv_AxdfMzA IKmsjBsZrqI IKw9lXq-osw ILdGxCTETSE IMqfIhBRoqk +IN_00Kxaz_g IO6RV58_Ti4 IQ-QnA9volM IR-IsQmK5Po IVE19bpG0dk IXvelHKGH6w IXwANHTFbzQ IY0Kxr0Y-EM +IYZKTlVIPcE Iag9-rVP2Rg IaxSWHgGJqQ Iblzi7weyvc Ic7NrHzkvcg IcDADtDiehY IeNKKMb7LBA IeqCrevK8ag +IftKe7Q2uiM IgLQyoE9_kY IgnZGjb3GNo IlOz6sMH-K4 Il_bHsQBUtE InRzDR-AlYs InW62jdjPPU IoX3_-ipIS8 +IojgAgtcQrY Ir28BXa_wiE IrMD2nxPoMs IrekWgq4VEE IrffO3nr2ME IuG4A9FCeuM IvTMeUZhGRc Iv_cqpzahp8 +IwK6uWqUyLo IwSk-1PiLqw IwVRHElTzmY IxirZWKGgZ4 Ixlf5i7VIHk Iy59VaKmXs0 J01ict18ts0 J0dCEF4hdsI +J3Yl3rsOQ0Y J4YPyNnPorI J57eaC4J8hU J6hbxXZNchg J973ImKqfxo J9LZglgSLBA JAuBUwa91jI JB5wsy0fobs +JBH8iIVSYM0 JBK6opFGIzo JChAvaqpIoY JE6fpV8chQo JEhguq1cOHs JJ2BuD_5c24 JLeFdcoYVdA JMOGzogn0yA +JNavUJQHKn0 JNoRxerTraQ JNro5m_TFbg JNvANLboMTo JOeihcHTwS0 JQKOyqzqChQ JRBbhVp3QlQ JXTC68yPt0I +JZ0wbQGamqg J_d1vcrb-5w Ja85eiVq5Uo Ja86L0CeNps Jb5q9K3MRPA JbDlTHM7AvE JcApKUKl45A JfdIanqkYl8 +Jfq9k2cNVlc JgYmrP4i7T4 Jh6c02KeDsw JkcrZsTX0rg JkvjCH100rk JlcngdxG8aM JmFt_43D-0k JmQwWLBwrO0 +JnQzvns2754 JnwhIimKTYE Jpqwq3pTU-0 JqeRo2OYPR4 JrJr-lL2huE Jrmt-mTv1WY Js1oDDu2dvU Jsq618mmStQ +JtO7bG23IrI JvWlJigjaRQ Jzmnslb22QQ K-8zoVSCvas K-zy0aLxreA K1QgA-ZMxCI K2LLqDx1A20 K3qgSxZ_vJE +K8yI95FZBeQ KA0XepVQ0co KAfe4pkYDAo KC-p3mUqm74 KCQnWG65RIg KCpafnsSjlU KFW9Ood4Omc KHIGKMkGD90 +KJrS3KGdGzc KLS8YL_d2Qk KLuV6irDbGw KM5R-9k5X6A KPPXaDd_NTg KQ_itAjKE1A KTqhPCYVR-I KTzwYWMuUCI +KUodcsGERzE KVx79bw9cBE KWt8wHbmttA KXPYYrBs7dg KYluvNv5R18 K_RK3fW2eTI KbIbKibcGRM KchodNKQ4z0 +KczkDw_2NXU KdTmoNi1GcE KepwkF6qYO8 KhL2S-vPbiQ KieOD6w7BLU KirzRjD9Kh4 Kk28fIMOiRc KkISIrGa1Hw +KklK0Bh7Khg KlY-vyjyRkI KnmNbJFwBUo Kny6-g-H-VQ Ko2BN8iZ3_4 KoRckc6OTFY KogsBcpztpY KqNb1IVtcYY +KqSIP5Qp8K4 Kq_NOgFJybM KqcuPoW8Z7g KuhR46YTwUw KvZSsoouIkE KvmKX7NfKRY Kvpt73Oal8g KwzzfneMUSk +KyOpOQcZCY4 KyUXFFa6gN0 KymrjHZ_mlc L-iiMduJJuY L02b7zWJsu4 L0v4uqL0LBk L352VL7mCxo L5I-X1ko5go +LBDflMBWh6U LCpG0wOOQLQ LE1NWz3p3Hk LF5ZK2-24is LGMo8Qk6xfo LGW_Te2xGQY LHmibSjHBE4 LHu3c7c2esY +LHvr87IF-g8 LHzv7L7ye9I LKD30dm6Sxk LKHKq0_uVTw LKp5hChpMmY LKu0tPVub4A LMJ2QUFDVBY LO20X0EcFU0 +LO3dCoxkYFk LODguTKNXnI LORh9CTZ5N8 LOjhsHdUHm0 LP-Ic9kvNjE LUfpuvluOwU LUr6jelf3QU LVJD8FA9KR8 +LVlZt1c3CyE LWeT3NDzUWY LXWIIkEjt7w LZHyxiF3IYQ LZOvGXy8F60 LZTFEC2qXEM L_BNjYs0YGs La-qP88_Bcc +LbMjXySUcWI Lbo4rcM0Fuc LcwtRHoQYQ8 LesC0awv8LM LgInlsTqmCA LgMbusDGxOo LgR7PtjKyvo Lgz2y5P9fy0 +LhidNJ0fxTo LiPv71VUyEY LjEgrxBupxE LjIKH5zSWa8 LjRaE76m3KA LkCuZCGO3ZU LkecbSIX4gg LlFrrpY2_jA +LllnqIwhkmY LnDiTdYfIOA Lpa9HbNS4h8 LpcN39q1ra0 LqbvpbRIwZQ Lr-PXytZ66s LsOBV9Bhftc Lsf74-S7fXE +Lt80uZb6Qt4 Ltcxg-AHdsQ LuVwXvFtNe0 Lv1ULzD0X1M LwPUq2cUbPg Lwm_CY_A8_0 Lx9GudUDK20 LxyjwQw8M5s +LyZlMDEq528 Lz2kmm-XL_c M-vU8PvigAc M0VhYtjkWjw M32suowk0Ps M3wrbxCo96E M4gcgcNbvrc M5GXb9ouSW8 +M8PjVXgRqvs M9wbXfRmmtU MAGypS-PJ8g MBpHBXc0nw0 ME5REdjR-4I MGX7sI-7PGI MH6a132997c MICo654dMZU +MIJwOqa9xXQ MIMPuxd44PE MISsZyivzls MJUX_SJh3p0 MK1bmvSqdUQ ML34vqIzM6Y MM7vsA4D_IA MNFx-6jiGsU +MNdeR51rJ8s MOpKBGTydHM MOxH7vvIeP8 MPC_O99KTmk MQNH1MTA3H4 MQvC0z5jK_A MR1jJ419rcI MRBFsmtsAwQ +MRI6y4cSZFU MRmSjOzohMQ MSJer6a1CM4 MSMDfct_5H4 MTN8wmAdNZU MVH8DBvKL8E MXZ9pu6mgzI MXzVqL6ywRg +MZL752Sswlg M_Y5Cby3w3A M_qGQfxRTW0 MbylHdGOZQg MdfxGqjfSBw MeXf-zPYGoE MhAAmwOXNR0 MiQMcQclXP8 +MiyDLrJOa0o MjFG7fIeqF8 MjbdXYzTpKg Ml2Mlv9Zc3s MlB0NNWqhSE MmdKcc51MM8 MmnHu6zLaTU Mn2YbwsB1sY +MnKiScs5few MotqWynZ5x4 MqhKxGjP7Ns MrBfFGh0Wpw Mss69ACTnkk MtsM8zl_Qxk MwZOfJbRvj4 Mwbtn_5HlE8 +Mz0ZoMLPgPE MzCyx5Zu4NE N-D7MkkJZwg N-mGq5uf55E N0G_RdsFkUs N0YPfgbkl9k N2VemL6mHmk N3_bvUWLAdQ +N3mDMUm-qko N3vsHoxYGJc N6GUy8B05Ik N7mm38pzsdc NAWCRTiMxHk NBWuswfw6Zc NCLOHi9jZjQ NCPitOPf6Ho +NCvDQ2omREU NG6_Nt0OYro NK4_pCSdXq4 NLS5HjUZvXo NMn22Xrl3jg NNFBAemAaX0 NNwula9Axyc NOrzbEvUDEU +NPZS9o4dInY NQueKubcUzY NS3cY8SKghE NSXcYCKSCCA NU4YxGg90q4 NW75M-lrSks NWCV17CX44w NXI5NCW067w +NYEh7sFR4tY NZCxwWSMTzc N_gk04XJvDc NbF5WFasNhQ Nbd6yM64w1o NdjfKpfjzB4 NeqctO9kSw0 NgETCRB-E0E +NgUOpIWD9xc NgdUGQK0r3Q NhktnOB3MW8 NkNZmxnV0jM Nkiw6lGDsrA NnRkwp3nQEY NnXDVqWPka4 NnoLLYTPE8g +NoBxw7Nb-pQ NpLKw-CgVnc NpTTzj3QUlI NptNzwX_9cc NqF1DaSRDjI NqnKzJTu5aI NsWC1FRCdyM Nt8gpYzhVlU +NtlwperiPu0 NtmdmSwKF1w NvkhviupfII Nw26St-TFYc NxS6Vkjr0Ps Ny2K-9OUPkI NzVTiL_E9Ck Nz_iFDC0qYE +O0ajfEkm8oU O0t_N2t4Hcs O1Y_jBnaLGU O2IixBAOD3U O3m6yPFmago O4ipQjW9K7c O5mab-4moxQ O5zax19gtdc +O71BS24dzNE O7zmS4VhsnM O8R8n6WcoPY O9DU-XI5jek O9NqdXOeDMc OCFKHM9-nXU OCxahTnh0mw ODremYYy3U8 +OEKC0IgNi7k OFnthv5r7Z0 OG2II0s1254 OHRGSl4sxAQ OIqgu_kNWMQ OJetQauKZqs OKMG0L3uI6I OLEbBi9iox8 +ONJccMfpv8k ONsiGZSKO_I OQ99XgGc-jE OQaKwpDeQmQ OQuL561X97M ORQ40dWDj6g OS0-63mf5H0 OSLvmd-fu3w +OT5odVvtZAo OWT7Zlvsq2I OXCBxZdXaVU OYV2zckwtWk Ob7otVA1GBg ObHQvNpduKs OcIvNWDHrmw OfWJ5jdgJr4 +Ohz_hdRXBYI Oik603zmPGA OjWRkMZWRJs OkPEHTrdQ9E OlCm7CPLBko On4XPI5Iaos OnDAohWiyL8 OoffoVZD8kU +OpDTXkw0G9k Oq5HPW6kOvs OqE3T82Om4s OqNuBNkEpUw OqaRSGheqRA OqgeM1L3Kjk OrLCCXSxvCc OrTiVhhP95I +OsfA-O8vl8E Ouu2ZmY78Wk Ovqbwjcn2Yc OyFg5xfqrPI OyiDm11MFhE OzG_qaNoC7g P--aavRWzP4 P-A5YH7jnmo +P-C5_mf2QLE P2cm-DfLd8E P2hDGe2W_dM P35JglXFdzM P3uCMlHx5tw P4DO0LJoK3c P4dr80X_IW0 P62hgpA5W6o +P6m-OnbzotE P7bvQFQXD4I P7mJ8fJe_xo P9KYR9wUav0 PB4TQ3RoJsk PBM6mwt2iz0 PBg5reXoa3g PCB5Cc3E1Tc +PEnKrZSLEek PErAkf39cfc PF5AN9P_rmU PGAiKm0TgZQ PJHDSsoMSkE PJUWxcF0yBo PJkf80q3vnQ PKCGA6_zP9s +PKIUsf8F-RA PKt4N3oKax8 PLMNSowlv7s PLOZRcq7GqE PMLL-b2I7RA PNF99W7QWsw POZiTb6YmTw PQ_Z5CiP--M +PShV18upRiY PUYGiSWdTio PZ3jhWuHzec PZDN6BuDVXU PZXvGLBBwZ8 P_Eg2yzoNU4 PaNBh3Z5VPg Pe8r9ntVweY +PeWv36SQ1o4 PetWP1eBlLk PfAqFTXLTf0 PftXB8awiKU Pg70_sIziyg PiGVhaP8cEk PjD8yIqy-Ag Pk4koNv8HEE +PnEyORgg38o PnpLPKyzpvA Pob_yTnY1Pg Ppt9waINmgc PqIrtEdxUCI PqsIsIAFCOM PsHFVmjjvQs PtRQdlgkmgU +PtdqZkS1A-A Ptsemhef27w Punv8Wh4M_4 Pw5AF5hurUs Pxb9MTweoiU PyIYnNov76Y Pyo6eeMG9OU Pz1fVVx-_qQ +Q-oZUptFbIE Q2jDta1Png0 Q4zBay-VvxI Q5pko8G1zt4 Q77KuRCVFCs Q79SGxJlK_I Q7g6Zgw_QJk QAoBZ6Fn6dI +QCLhdAl_W9U QD5DnNOV5R4 QDWHO5G6lnU QFCD3NTlnTE QGR7notgigg QGUQ8_AZt1k QGYaFjuBsAU QIo8g-1tzyU +QJD88tQfGg8 QJWcC2TLKQQ QKm62t7ReEI QKuapTNsAtw QL4Tl_qINDc QNlIuhXJw04 QP9IrdRIf3k QPG8z6qMGJM +QPuqd-ywFT4 QPy2vuBkwk8 QQOnDE1qzbI QQf0Zt_XZec QRNKRH1nJZc QRbBzgf1uKA QSYD9i0xI2E QV5dR3x_FcY +QVG-NgtGO8E QVP6nzZ1se8 QW-3CHR9Uuo QZLk_LXrmYc Q_URW5wSBrw Q_oCjKzftjM QbCukpssDCA QbpjKaHqut8 +Qc6goEAAWoE QccP7oAZHVI QdgJSp7bpwE QdsmZd0XK2Q QeeqlIVYwPA QepCSGjoD7g Qg3niPl8DJ0 QiraznZO7us +Qn-y8TgbN3A Qnm4D-hA4DM QnpnYGOHUrw Qoh5kbcvzTc QpfIIIk689s Qs-lGeNt1uE QsJ-jezkfic Qst15scCAXQ +Qw3DDazf73s Qyrx8OEb0pg QyuOLXlmfJY QzmhGPZFoLE R-QLr_40rSY R0JIhHoQnC4 R0PyQHNcZ4E R0fBoHezWdQ +R1z7LpW6y3I R2nNCp22oMs R31S9jUIHUU R3r6297a64k R3zAFTlZHAI R4iRoFyMlzQ R4tZCE23zoc R5Dj5OewprU +R5PfT5GTg-I R5k1nHRK2SI R7vkPI1VJzw RBAlrByVdxI RCDCAJrBexc RCLI5q1FHn4 RCwMq8Jw3d0 RFYORA3fmu0 +RITL6_Y6jrk RKBQBezBYR0 RMiEPa1-fNM RNWWVbhvfd8 RP2FsDpmA2I RPQnjR7lJ9c RRHTG9RnE0U RUHVjf6YFUQ +RUmeUlyVchE RWDQcuZ2iIU RX6OZE2j80U RX7mpCy33BE RYUqj4-zMrc R_sTQ3d244Y RbPrHqFKub8 RemFXBfANcg +Rfv1AtNbb9M RgBpkJR0UPM RgPKbEYYbVQ Rh494V2IO2E RiHGJUM9zfc Rl6go6zj6xI RlgRtAr3rzU RmMXXdnhehM +RnOl1CKhBvg RnpLJDue7eU RpGes0rdB44 RpbufuGRuRU Rpbx9jMeU7o Rrmy_LUNWRE Rs8362UR83M Rsgn95sU2XU +RsnZniMAhc4 RsyLIrYA574 RvffM8wxiFs RwGUf2D-aVc RwbclPxb31c RyVYh1dlP2U RzIQ9KpgKoE RzcslIbMjHU +RznkochzqVM Rzw9BVSdoLU S-KYBUiy3vk S-hxVgpjQXs S3FKCwCze4E S3uTb-D4e7o S6I576hfWK8 S6gVaJ8j1Ss +S7ESqqvFjNk S7WQB4DbMIo S7ejf5A-e-Y S8b5yUxBpCQ S9MgaSsoZzU SDVvkqApL0M SEHtW7HNlE8 SFISosYNV-8 +SFrP6f9oyyA SGoeS4WCRH8 SHFJ4vbzUE0 SJNfT8ni0_w SKKr1rDn6VU SKik0wAe74g SKqdbvxYc88 SQve6cAWKyg +SRErHHWVfyw SU5yt4fQF04 SU91vOJSO9o SUR4tH2IekU SUeIMWkYPfU SX0y3sCK6H0 SXQHYGhc5eQ SXtVW-lWfRk +SYkmGKi9ddI SZuz0iFpldI S_qKCkHdTOI Sa-0DzhuKJU SaEUGAFixJQ SasytzU1qHc Sc3d4zR3LWc Sck23c3BUf0 +SfUX_vDFMhk Sg0NV5Xxkvc Sg30FFz_-tc Si2sYubztqM Si3ZgSxKJxg SiHfYr3VWuk SimtyUzoZmM Sjh0NYwmO8g +SkR15AUyZ18 Skui-ABKVhk SlNSiyl57RY SmBhyKFSPX0 SnaZChl82Xo So8u94Mr7Mg SokUS4VE2y4 SplKjBeqYJM +SppbNdBTIGE SqZ7XAZBe1k Srqz3v0jNh8 St7hGfavguI SuHj18Hlnnw SupgReJMuq8 SuuvnJCfc6o Svz06gJqljE +SxGuyaDvFEs T-SB72TOnR4 T-sizXKoDPw T0x0kHXeuBA T0y799-A5-8 T1AEsair1ss T1gVMP5POK8 T3U3SwgORvY +T4wVldbX-W0 TATdrOITAio TAy1mzAOiGs TCFMUU96e9A TCG3jUUI8g8 TCms_vlDALY TCyCzf8rbfQ TDBOxkiLUWw +TEf_hbA6KF8 TIuBevkqHks TJLYszNzG5I TK6cWJDRKSM TKre2-JrHtg TL47RD6l7vg TLfonnbVgPk TM0E44d2hIE +TMAKibXx1wo TMrm3Ks5tIA TMxbx-8vbV8 TNw9uUlGl3I TO0cyN3AvJc TOJnvtxMjZ0 TQw9x4XcNvQ TQwE_Cb3Y-Q +TTeA3VfAtJg TU11suL22z4 TUq0YxuDHBY TVFooddk-f8 TVfq5XUsE7M TWfYQwIsNxI TX-oMWZ-n2w TXECKMLGnZw +TYgynaN8X_8 T_1DZZ9Y8VE Ta3vtZ9GOVs TaBgm21_M-A Tb-peiQpceg TbPKswkaHDk TcGxU0lB2_M TeQoO30W8cY +Tf1qqwUS-wk TgbHZWk-xZc Tgtos9s8Y3s ThlKVoao3hk TjoGBD7LA_8 Tk8TvxNXsyM TmKpeyHVEgg TmOXEwNVGkI +TnNERj0YQtA TnSC5aOhmn8 ToDHAkCePjc ToJHp6-HSqg ToRE2eB7t4o Tozse8LWtSI TqLmHJEfXUk Tr1gDa7aYfc +Tre4ulgZM-Y Tsa2kskVBLI Tum-i8HdDe4 Tw2uK9pUL3g TwYeGIsrHk8 TxmAZt0SiR8 TyaGmrNGGNU TzVdYq1DuvY +Tzpt1auqOOg U-jfInTOzK0 U1cBXOQJzGM U48rFOuHmO0 U4BhbYAPHGc U55bCSD8YvU U59f27yNzkU U6-CkGAIQ0Y +U6d5gun3UGc U7C28HexJvU U7Kv1-qRizY U7RHUkJ5Pj0 U8o1XwUCrGg U9GbI8dY-40 U9Mi4GuRtrQ UB8tWKqj97Y +UBkFz40EgWE UCtA08qsfpc UEHd-E1oMPg UEat7O0SseA UF-N7W3Y5TY UGDOeGwSvNg UGS2EPSSvv4 UGaTHGLLMI4 +UHj23wqXs10 UJzvZUPXmw4 UKUiJF8nv2s ULId_ApY_OQ ULOzHJzuW0c UM6fbI2X3HQ UMDAsqLSIOU UMVvMP0TvLs +UOFNvtJl2PE UOgOyVdUUjA UUAo9ftGYpk UUrO8PIvmOY UVeQm-9W5OE UWBTjrgNtHc UWxDGZ-HUsY UX6tBAqa9Ik +UXcQ_6JabCg UXqgqvlfNfY UZ7jM9NH75A UZThEtzxwSk Ua6JnG22lFY Uaa2hNvXu6I UapbVuDenB4 Uauw1nO8TJw +UbsB3x1WlgM Ubsclj1uuPQ Uc1brWyXSwk UdFFe1aIQwQ UdUYEedvLyQ UdrznrRQdqI UePbcqIGlLs UgdbQ6CJdOU +UglK3UIa_jg UlNji89CEfA UmTZQjhSQ8U Unp4W2Dds7U Uq0lHaIVEMc UqnENPV8Uv4 UrDS_7IV9lM UrvslNLquTM +UsP3qedYnt8 UtPP2ptuMNI UumKyvt7Rug Uuw2wAdejXM UvsxdTl5y-I Uw5rSRk4bns UylAyOdF7ZY UyrUJ-De4Ek +V1BtEWuH1H4 V1Hwe35xYEM V2U9jR4a_Xs V5NOIUTKE2U V66uS5Duw6A V6IN4B12vUM V6dZQGYa0Ck V7v6N6dHVqE +V9GGe7h7eoA V9SYmGDrDlU VC6BWcnbxZo VExtv4scv6o VFpLga5g3eo VG1vY51YMIs VGBRhnH57tM VLEfZ7OSL6E +VLbDIebNQ1U VM9KaB6fPFI VOpZhTHb1qc VPkZreWkD5w VPnyTZxh91s VRULwjNheeE VSaPbdI711Q VSwGeZkwhzA +VUK8zRkUg-g VUd6cfE2pVQ VWePKQXA8as VX3PNxyu11k VXqrHRzOa_M VYCqKy0b4W4 VYCvRRtHvGo VYLlGam_VyQ +V_4RSPuo7AE Vbmf83goPN4 Vd3jfIrN2d8 VeX-ubfK7f0 VfDxF0HXcLA VfM4g-_la7Q Vge6wdeiTNI VgytrorDDlg +VjJj9kvbrfo VkBmH0wNgQ4 Vky-4LBcmRQ VmtnJLadszc VphzCoNITiE VppXsL_PIjw VqglIVGqb8w VskInnqE5hI +Vvr9i_qfoq0 VyTErh4fhoI VyWrZSPP-Ng Vyjz26BBzCk VzL_7C8dHyE VzwIFq19aiM W0ZSBAcCn7g W2lDGPeqMeg +W7KZGQdQKYw W7TP6tEEoxw W8u_OMAtqBs W98EvS4Gh60 W9XEDZHzfIc WA4rmju_C7E WAEItM5ZmKY WDvuOkWLTgw +WDxr13cy18I WEXtKONgggQ WEvmlhihzVY WFKtab9HZZk WGOZGhigvG0 WGtnPwyNORo WJ2sawTR9mo WKspHQKJiXE +WLTYMgAhNS0 WMHjeE8Hsmo WQBGyrwMMok WSXxJ6Ec0VQ WSwXzuX8t9M WTjXME_vun4 WUOXs2oFQWk WWu6sZQdBoE +Wc4bMV1ccOk WcybsvGiXkw WfHKUkdkOXs Wfm-Ovuhs6Q Wky0RzxyBRg WltioYznjFY WmNRDR96MBI WoLf71bW83k +WpoctaflADM Wq-5JfGGNZ0 Wq9tnu2VZIw WqxaLXVNVG4 WrJms--7E4s WrrgWZkrVkk WsToHZAX7Yg WtBMfXvTY0M +WtKLGPSmqwE Wth3Qt7OTGA WwgleCSX6Ns WwjZCsFVnps Wx5pf5SXeZs WyZ3IjxS1E8 X0U9PpBsbZQ X1HX0koxrTE +X1HcCmCW854 X223orlOjYw X3U437Ztza0 X4TESW5ig0Y X4TcpXj2GYI X5DTkMgrWHw X5iNk45MdZg X7sy6JZHHvo +X96A2LivpWI XB6DS0C8D64 XBRuvkseyaY XBUyBKRuuaE XDuJ1ca6esU XEh9_uVz5LM XFLBmJBV-CE XFRcoonEUEQ +XHgCuuxDwO0 XK3vAnSJwJE XKjZ_XNcwRM XKkZ1thTElw XL2fF9M5xhM XLO5oAuNCHk XMmcgbCgVVU XN2X106ZdKc +XOPLhk0dBqI XPHiySXbKYc XPovHlVzLg0 XQu7BKhqlQ0 XRUHKIQD7Nw XSf0SfmbKuQ XT0JL00LpB8 XUTEyA907jI +XZ4UwsTxg-4 XZGrKxbSsTw Xc8hEe9afcY Xe5hIhl_ZcI Xg7j3P5DZ4M XgPKcgIr3ts Xix-ABSn4Js XjOLb0Pdd_o +XlGjFSTvrDo XmB_CsWSbK0 XmJ9aC8Ud5U XnZN9KZq5cI Xo8FbDos9Nc XoNo0pap_NI Xor1SPzyuzI XpCF-AoaEL8 +Xq0qLYASERk Xq5ps9wvMlI XqOxki3IT6s XrmcWrx-rC0 Xsi-Qz_xXSA Xspo40rvG4Y XtHay0wx33s XusxWGy9_as +XwP7EXRbQsA Xy7u-nHdEfE XzDsQU7lub4 Y0cQSl3dN2A Y3lPBxBztFY Y4tOufNFKsw Y6BNGsVSiYk Y6MwU16wyy4 +Y8SvuZhmpGA Y8pWwQjaIGs Y9JmgPQdtV8 YAjM-SrS_70 YBir4uRBViE YDpKJ0wz8I8 YEIRF61q85s YEJrszNkXHQ +YEijMHuZ-H0 YFLsAg5Dr1Q YFNKrjX6CRU YG-uI8iw26w YGvc0VcglJA YHjK2oO8wd0 YJiBRJkMzdY YK5EATzY05k +YLiKzMIdp5U YN7VNk6VzB8 YNEjv5nbVVE YOPzPjsx_1I YOW4wnpwNZw YRYp1pvZnC0 YSsGuacrfVA YULVSyX0ipU +YWt37tws74U YX0fc5uw3S4 YYOepoNoBW0 YY_6_OwbDwg YYdbxiLDcGc YYhXp5AqlQ8 YYtI6MVlh5o YZ0ZlnBx6Uo +YZbAzvcugG4 Y_32AXwjYzk Ya66QvaiX40 Yapl_BKcZZk YbDHdb6Yw6E YbTjNvEH2nQ Ybm9n8czFXg YciCD0ww188 +YcnRyK2NMrI YdbyE2osqRs YdoclF1x-dI YeBBkOmSDmk YfIW2Nh_PBg YgDE1XJU740 Yhj5m0j7I2g Yi0ZLNeVJQw +YibbtE292K8 Ym8eyVPRR0A Ymo_nkgCxjM YoZcYGcpHV0 YpfslPYjmhk YqpH-q_9230 YrMh6lVQsQI Yrllsharpe0 +YuXRQMbOEyo Yv5WYL1s80E YvfnxR4-9bg YviFEuEez1o Yxaf89Qhy0s YxzRLC0FxGk YzaqJle7hwk Z-BhEIzJpRU +Z-jvkYdvnFM Z17AcrbyYck Z1t5UQISPvY Z4fxrf4tyUQ Z5xRsNr3i6c Z6_OFewKDVA Z7X41wCDRKs Z7xTdcCzgdU +Z85RXWff2Xk Z9AfNqaW81g Z9poH94pjJk ZAfwEjNVn2I ZBVJNqIQJoM ZDML3Mcyz3c ZF3xgydqawA ZJ3vUOoWGF4 +ZJ4twV-L9hg ZJ7Kvc_B7Qs ZJDOKao6Q8I ZL9UrJmvQ7o ZMw8ap87U10 ZOYqVCQv1A0 ZOZw9rTZqEs ZOqKQdIgZTg +ZPO1mS3AE5k ZPjfRN9S3uU ZRUvKWjgluk ZS6g2WRGHJg ZTQAdSIKrg0 ZTcvJ5J35yU ZTg-htmRH0o ZUuzulmW3EQ +ZWvqitO3a9s ZXMFfj1o9xM ZXoexSNtilc ZZG1XmxrenU ZarV6r9li_s Zc4smZXukss ZcY4_gmUXCg Zdnn1UUfKXs +Zgt1Thj1n8Y ZhHx5zTUwTk ZhZFlXF2tIQ ZhqizRYqfWo ZhwVQpBc7Xs ZiNUCg9gP8E ZjFaHUcFAxQ ZjeuaJkou1E +Zl87AzQyB1s ZmwYv52gptE ZoSYisIc-so Zp2AWr3XR6c ZqTPVwzRx7s ZquRjTf04BA ZrA6SwRvz48 Zs-nBw5q1VY +ZtibRcLwGOw ZuzWtVtFga0 Zx07uAkcG74 ZxrNS0gmWv0 ZzECHuQsDms ZzG2m2fycOE _-19Fhmk99I _0Y-iVOoWS0 +_0hNiSsPPcc _1IMd8PuldM _2PbOQIgOps _3-4j6a2mkk _4meK63ZYn0 _56oHoIKPAc _6beA_wd-5Y _6tWfXpYi0s +_7NGtbR3F1Y _7Vq_hvdw8g _A3W3VH3CJ4 _AOPTF7Kksc _B-_Uqer9Cw _CLr3bAi9Bo _DKP8_fWbII _EV7umuShFk +_F3lDMKqyXU _FXpHM2vBcw _GEPDajhsUU _GhHp3EUR40 _IXseIvfdlI _Jr2Rbuga4U _K-c2-Oj1Kw _K2o1yJUMuE +_LvrMltvARI _M4FJPNth8Q _MJ5Yw_mrOI _MwILCND2c4 _NLksZG5BcA _NiMulME9Ik _OLi2JaVR_0 _OzLDk4efMo +_OzYSNAyveA _PbHkzoaB64 _PdASyJ8qPk _QFDTd_mI38 _S2WldBIqAs _SC2PNPVKuk _SsuMM-APzI _UeZCt6pLxs +_VTrGEKD6M0 _VrrSJtE1hU _XCXbyriWDM _YSzBPK-eF8 _Z1_nsw6qzw _ZoWpmnvKX0 __mvXmRaujQ _a3d8eesh1Q +_bOeMWByiH4 _e6pkIK00lg _elaD9gfQOk _go6IloQj8E _iHMhXEC88U _ibAwQaKGDE _lNIozzTH0E _mlCKRwyFl8 +_my9aUyp0UY _oeq2YlHR9E _omxfGlUXM8 _p552JDeRvA _q3RHUI3KnM _tS3uGzeUEk _tV8F9yGpmo _u9c4z7Q6Mo +_v1txzHIIm8 _v2zMZW7yDI _wiFZz5GJLQ _xEI8cBaWXA _xzdTUfBXUk _z3R1DOaWi8 _zbmOSLkgW8 a-Cx7tTFSpA +a-GEFqTJgqI a-OR2LaciGs a2waNsHsCes a3RMKFHC7Gc a46RBqVeESQ a4fANGXXUPU a5XfRbQFdSI a5mb8_vXWc0 +a6ssH9bs8hE a8xhHMo-Jjk a9ylTi6YYhU aAoyTDTt-jw aBh1cBaFJtg aCjeFyJZdDw aDByVPZmrSg aDX9uHPu880 +aFAdRsueM9E aFopIUov5IQ aFqy-njRPTs aGSdSP1FISI aH7QVmwUT5Y aHLJGVqyOpY aHZazeA6Sx0 aHxnAS65Oxg +aJQ2q23ecwY aM59s9rLH8U aMjoSYM1RXM aMln24b5zX8 aN3AlroD2RI aNQ96tAXUWE aO2NEUEVVqk aONeGS3yD0I +aOqm_D9E1DQ aPixNw7Asuw aQZWJwzYawQ aRMyrv9edDM aRkKTZqoyy0 aSRgJrTN7nw aSz6Gt6kNd4 aU1e2g7jmEg +aVJ_6ujkzkY aWGea1zN32A aWWZ5vkylfI aX8cW4PBeDw aXPJ97We_yg aYd2g10ouCQ a_5DnG5djpg a_f0pH_2sLU +aaoF9_DzDzk acQfjRF_Cio acd3h5OmFus ad0YD3i4U-s ae68GhUMYNE aeiAB87pd20 afouYSvFXLs ah57r2pXRbo +ahjIRX9sr0Y ai4AlAxxkX4 aipyB5uDF3Q aivH5lVh4QE ajhrF8TRv3c ak9N1kdVyxc alEGViRga74 alEOgLl-BJI +antE_svco6k apX4MVbdIa8 apmu7xV2IQw aqXq0MlWXhY ar6QkkjlJZM as4cq5eAp6I asbtjv8Zlo4 aseoNwbKyuo +atORbBWXoUc atRtmAM6DNA athJ5MxsCQ8 aurutrlgDqs av6YaBfHUzs awWIyzPnCzI axC-_uHf704 axqicK7q23M +ayQuuDOZ-fI aypcVRg-Mno b-UxgO2mipg b-yaRpESlbk b13OoCp1niE b1v1i8Ma_DE b27RnygiDUQ b2rVfIVSDxY +b3F2t3XZpZ8 b3Whg68bITw b3iD-vv3rU4 b8bhPG9Z3dQ b8wiTX8stHQ b9I0pqJTLjE bBw5gcJ13hM bCEcwMXDUNc +bE77lNLCalg bE_rCUJvVi8 bF2IHoNkUz0 bFH4aJijZiM bIBPz1GcFcw bJi58PfWSAk bLwy-Aoq1DA bMsZtleEytI +bNNtCy9tFPo bOfOgrYUCsI bOwdzUQluPs bPP4Z3zI0A8 bQ236-w1bBQ bR5_rthqc64 bSTzEY2ltk4 bSdPnghWrmk +bTLS54ZSyUE bURErTIEtdo bVq2p-oiScM bW0zger1ybk bW8oOXOBGCI bWDBq8MS52w bXUtYalXejc bZRajf-5XWg +bayuhwEYKdY bcNwABsd1Sc bcRc2G-cTa4 bePPpmIWwwA beS2TMEVnUA bfW-0I6X5uY bgCz92VT39U bhNyrTD9xYw +bhmNp84_SWQ biZ9zD0Wmdo bixSwj-J44s bj1QRP1QCrs bj7TAny84XU bjmYNROQwPw bk-boWOuzPQ bkSfMv4Ujhc +bksiZh57HAU bmRgHyHpq8w bnh11QOlu7s bqFGMEN-E2A bqjv2rmV2gk buV1LpU9RGA buj36BoYy6E bvBDgOEOrSI +bvxWk4XPP4s bwKFRegYMlE bw_YbSlcD9g c0EeojVOjdI c3InXribwSo c5RcrCS8zbA c5_eIWqmbuE c68VwUzsQ7U +c69UJ7ZRO4o c8LOWVAf6pE c9Q6qMKMsj8 cAmw-ULl4pk cBncu5qHrCI cCJ7H-1lcwA cDn3xMwxHWo cEt3XhuWUFE +cH7oDLRhgLQ cHBeblYPD2k cH_6IIecc44 cHdSwKqXERs cIuovhoYh0s cJHNk7jcLlM cKjt1M6lENc cKle2sEOjls +cLrfd27srAQ cPclKSfeBaA cPfBILgViwk cPswO53Hogg cQSGRz0jh9M cQXulANwyP4 cQYaCNuCzJs cRAaiOSkFwA +cRK4LWuhzkk cSMBm8CLFag cSMlLTbzETc cUbCJaKUs3g cWn37p45VRM cXWjtd6cUoc cXYqwkFJkWE cY4gQS25hg8 +cYvRgImL8D0 cZxEI8aM25A c_BWDry_KCU c_OTIJyNwuo c_PzHQk6hmM c_XG_oC7Pkw ca2zBZAFiHk cbM1J-an9cg +cbjpVsz_Kvg cd743BpzRIg cdZP2jU5J9I cduymCCGW7M cekFqaUGTME cgBD2s1B-oo cggZBf2H8gE chZMPQWoLuE +chyr1dD4pl4 ciUtHJCl8kw clViiMMfvL0 cn7HVYjZ_os cnLSbKhEQ4s coCSgIkdJCc cqKVp4bsa1g cqg2taiAm-k +cskh2vBPv18 csrpqbsdFfo ctTVlIr6PNs cu4718QOtng cunpQ-QM2oM cwBskf4WYis cwWLL-CPSJU cw_9IftAFiY +cwa4g8NF4DM cxoFTDxfmtg cy6BRwNZL8U d0BYgxmk76k d2Kqsg0Vsuw d3BpxntQ914 d4Ijmn9hZuk d4fCbI9hw90 +d570cpRenm0 d5JXkn2WiYM d61JVBs2WZs d6ZsdvzFtlE d6fs-pHd_BI d782sMA4_Og d79LMnJsEHw d8WFrXsZMIA +d8ZFUthkdeM d9KSvDn_Onc dCYQX3xx8LI dEAckz9TqgE dEagZADEAhE dEzmKDvp9Qo dGMnalByqeA dGYraaIHu5w +dI1eo55bExA dII_dHmPVAw dIt_EFqbViM dL0IMGt7eXc dLboBrSikdw dM1-qrNA4-k dM8-7T6VcW8 dN8hU-CQML0 +dNHlIO532XA dOqccVFUcjI dP5POm7Fn8s dQkp1SA8J_g dQpf_ArW6bs dSNLPJVT66Y dUImrEAJoCA dVaruxqHVHw +dVj9pY74dhU dX34iPMudJU dYFWu8Pjtms dYFwVvC6QVQ daQE_iDzLD4 daZgiYsBRLo da_Dc1owIcc dbp-aajKSOY +ddZBZR5p3nc ddakT2BBUsk deEjBMqI3UY deGv6ijitNg dfGlaKNhws0 dfh7tWSkduA dftqc9AW3NU dg-K87VPRnI +dhBfzzr7vAg dhKCdPO9lC4 dhPIcTH4-68 dhqMVcLsQ0w diLdyZcDzUo dk5hK841PDg dkX-FmSX5qc dkkZoFwsOYw +dlX43d9fsV4 dm7w3NvxC7o dobzTbZ2yHs dqERLJNTHSg drf6V2WJPDc drmBkPGsAwA dtLh2LsKPD4 dtRMPUOBPlE +dx-fGfh2S2k dxGNmfbwkmc dxIbp11dLGw dxXu7wijGBE dye2W5HVgm4 dzkHrDY5vr8 dzlUZt8zHrU dzv5MU6t_ZE +dzyVSnGrDuw e-J1DMRdoAM e-h973k5Gkk e0De5wKNOc0 e0sus6hT_fU e1rtJ-wRAMU e4avexj8ZQ4 e5LDbthbQUQ +e6AgkzlGkMY e6fpwgpW4dk e80HmqXwBxk e9ourzND7PI eAhl6LRLBRs eCk5LKzReaA eD-QTkPYUjA eDDurX2Gis0 +eFWiw-myGvo eIrc3vsG3cg eKDtyhXhFJg eLUm8ABY36c eLb4BdZTOpk eMMnqxbaUTs eNDD8ZDgHm0 eNS-JR9xPdw +eQBTVcPcfCo eRfW0vBg3yI eSPoELT9CMc eVH8h-TtLV0 eXZSW0j4w0c eY63g8hA7mg eZLt2w_HZNM eZRZjrl_0RM +e_-LaOhPUDc ebRWjsqWekg ebXMOSzeP54 eceUC2-L6nE efMoNgq1KqQ egSacc6KBrQ egrPK6N0uTg ehEMRfl4Bjk +eiJZpXBG4vM ekiTbwudJy0 ekl5Lq8kFzU el8Q3RJsSpk elytljqdmP0 emxwCK5h_Js en0c_jywXw4 eok7rGXoiaI +epjUf-ZVu0E ery5VC3vF20 esRQxbymTp4 esS1_VXDen4 esZtO3a4dfI eukCKjSl090 evKfeiToCf8 evtb1q-YVpE +ewCwDSWb1G0 ewKH411ymlI ewbcT_7bRVs f0dUbrMtP_s f1AsNbFHDGQ f25SQPFYbDA f2bLQ9MsO-E f4YQNKFHaw8 +f63UKsOsmWg f8lwLUjq1kg fAC_fpkSQMw fAm-Cp22zww fAvWID7pCDI fCc4r6WNDP0 fDKhJg8twXc fEIRMHInESI +fFQnq-rfACk fJ4tDmYEdWk fKmVYqGuRc4 fMAOvdOBVLY fMXGcVb1rlA fOf8ig6tQDk fOqfpo6D5Ao fPkTcrbmrG8 +fQK7z6G1XDI fQUbhF8fcs4 fSZfvbY3IQI fTbGTdUn3ec fZP3DgxYrMY fZwbKDoGsuU f_IlduwFp3Q f_JspC2Y2Jc +f_eiG_hmH40 f_nzCHQXuyQ faPkDYPTzYw faiC9LwAQcY fbyrm2GHIiI fdmWUgefNSw feVHFKDZfjg ffF338mr1ZY +fiiLSxsyRJI fkqzodTv-jY fkuc6IuG7oU flow98FGJ1c fmhniBe7bug fn0AERr8hqM fnYIKSXdi6I foEK2h5j6G8 +foGbYKrLVHk foQqwNBrp10 fqgVKGmeZRs fqww_wT86_8 frE6ee-AwMQ frocPx3Ftd0 fst2HNPlpwk ftQZN1RW15A +ftbHRBlm9mc fuh1XdGfJzY fuu71ANsvxs fvnMCA78Z1k fw_umFkHFBs fx2FAobBTD0 fzrSsmsYEBI g-L4WvKcDHc +g-uVYA2eLEs g1UU_KLkNTc g1do0atN5RU g56cFsQbykU g5ctP8RFUlQ g65MGASr9ZU g8E9xPXT_2I gA-mlWR9q0I +gAnPVvBhQ88 gCUJ9Lrn3pg gCgly2DlQYE gCzVxaVRP_o gD9x2xk_Ip4 gEqdIjX9dUY gEw9UgqczXE gF5kNWtZt6o +gHtwA_H1U-I gJjD4LBE7w0 gK25sc_Vzy8 gLz3F5_IQxE gOLjdTwBwko gPeBLSdjOFg gQ-nyvA7Ank gQ03uI9vXtg +gQBvST4nN2s gQUury6r1QA gQ_FtVfEPXU gQgHjXAEhL4 gQyKYvAT8pE gRe-w8i18k8 gRlke_Rin4c gSKmSHjWTd0 +gTUUKKx_KsM gVuIRPZMaCU gW9AQMMZbV0 gYHOKKOEUWo g_BgjswHHKU gb3Wn5AwuCE gf5kfwxwXko ggaSNbm8KD4 +ghB6gdut2Vw ghwQz9_4XBY giuUzRDoPIw gjQfQkWaRRY gjXuVQPpubk gjl4uiZS228 gkANmf7P7wY gluf3odEaXQ +gmsLXeFQvPg gp0vIK4o8KY gpYRSWaiMmQ gtkxi5Rs8k4 gucQBeO13-c gvwfQTwEnBU gw-_ru6Olak gwhHrW-tnlg +gwnoVHesi7M gxCJN4ZSOUc h-BbrWPH9zk h-qWsEmy2jw h0Fnebnn63o h1mM6RuQRf0 h1xfqSMJzGA h45Lo2G0G2U +h4BrD6_0X84 h6Js2ATIK7s h6aW70ZLo0w h7Llf_2QnbE h8X5AmfOKDk hC-V65_YbL4 hCejiOLpMRI hETIpNoFtQs +hFhp1qMfm7E hGeJDgqolYs hIMoGqz_NII hIoWOoppUwU hJUvWpk_KAg hJb7QHRVOPU hJy2MgqR2J4 hKCDLqGEzbM +hKDDamAVm9o hKx8B9HnsPA hL60tR5DITU hLDsrbRNxeQ hLX7y3xF4nw hLvgJ6GF8Vw hMAlKK4gkjE hMVEr_Yysj8 +hNhwf5LJ_yo hOa_lIY4lq8 hQTpFCQzmJY hQlCjmOTcn4 hSvJOERlGIs hT0Up0LKOI4 hUbiaybjA-0 hVoe9rqqX5U +hXSMWULQRds hY1xmk9-gdA hYyw24DiElY h_00i2BExRw he7oAgkk7Dc heSGaaVz2MQ hehbrnyfhh0 hesYqZ9kWuA +hfnsrI9_RLI hiCrjg6q1uo hiXjw_2uS7E hihcvBHt8o8 hipWglWwwXc hkCyKCY9bmA hn1-CATEAsE hn5-WgbzOWA +hnS-O2v4jCk hnuLUQgOb08 htJ3OwtqyBw huKHIjXVZck huPcgi30vOA hv6lpAoSBrc hxVrNGOlAdo hyauZ8G4Qtc +hzXbTOUb8_4 i-A4wtWXbAI i-ZPJRliMao i08hvND6FLs i09juCPwecg i0Cuq5JAs-A i0dWG9j3EPo i0pGV1umm44 +i1i7BZCFjbA i2Xv0ZIUlo0 i2wnulY_-fU i38pNh_vxvM i3KO0ymuJoU i41_5H8Fmoo i5UK1_N__o8 i5wePFFP1_U +i7ewmLybQVc i80DT6nVQ4E i8FtlkhYL7I i8rb_9PFR7w i8uc-ircxow iA1KKoNbJSs iAAEqLol6Sw iAO0P-qWLQc +iBZ_xNQ_r5A iDOCBhWCi8M iGBmaD4Hupg iH-yiVWpRxQ iHrNxsB-0eM iIXBeyX8RRw iJLMG2AavTY iKCHYI4H_9I +iMqLDAgky1I iSSx8CrfN_o iSkOKXjXjbY iSsFnN37_zI iSy9bjML4Uw iTrc8nJ5cc4 iVJvT_2XmYs iXm3J9qZcNI +iYKaOsP23s4 iZLvFjBI42A icWWoYbo5LM icpmxHOue_I ihk5V9ivOcc ihohTLi3NYc ijWB_-cZPmM ikvhMnRFXxg +imrKdtDuehI inDZ5OVFRt8 inkAZozybHA ip-ZRWukNDk ipQK9RUTWrI ipSa03Z_hgQ ip_WooUvulE ispECJjWg88 +istWGlVYtxI itJIXtzXgw8 itT2rF41EN8 itXGV3k7YiM iuGm4HFFc6Q ixxRncEKEEg ixznW-1LxlQ j-DspX5PtOU +j-vKYUesrOM j0-9afxs-nY j0h6juXHx0s j0lpBsmm0Uc j13W6wR5MUE j13xhCTHYtU j16LvF1wcgg j1pP7p8CN_k +j2US7dbwV_4 j2pSMpvaYRU j4zamV8unCY j8G87XrMPuY j9riiTqWEBc jE48rrQRScc jEmqwITnlio jFECBP2buGc +jGhO6badFRQ jGvQc_GenkM jHcNEJJTtzg jJAmcf8IjyA jJQl8KM63XA jKofq9bMT5o jM12Ut4UU9M jMD_4vUJRgM +jQ6f1HnG-kI jS7bNz3Fu2Q jSgTvANSa8Q jVTFKTzTQ9U jVwhEsVnwPQ jWHh0F_djNI jY4hYaYBrDs jajyc2DtdeM +jbAK5WibyIQ jc_KCmubuJk jcn90xELnOc jhTmWtFbo0c jiFtdYhOiJ8 jiq4ndGpQbc jju2ZXWdVoQ jkRzSW3GLcA +jmqiE6MAvVc jnQR7Y07pe4 jnjdE59HjcY joNwQVjHdYo jodJ4Kx0lys jokD9EqsscA jqfGzQ6zFIc jtdBo_6SbL4 +judKOiiV8M0 juzIjFSuxVU jvfKt9e0Od0 jvfimbMJtt4 jvs5cRFvjyc jw0GYWWc-NY jwbfV4nnuuY jz0-dnXboHw +jzrARusWDIA k0e-XwF7bPI k2dyLzzbJvE k38eHyQQc3A k3Gql3naZKU k4FXiKbuC4Y k4vXobU7Avk k5HG87yc8wY +k6AgHMZFj4U k7cu3gOt1vg k8XCwHUUVbc k8XhTwT1YwU k9amzAqZkJs kA1WqTN0HbU kDKP56GEIDY kE97bcY1wWM +kEp1UedNZz4 kF3zkTarI6s kFPLJRMHGlM kFZQIzuFQqk kGKdOIcHAWA kJalVlNgjE0 kJyLvpmuXvM kK7KCcEZtNY +kMcUYQERWZo kMpSyeCLG8c kPS5JgNmRmw kR6ZkYbVwzg kRcyAt0GwYs kUIk0ga6NIg kUjpjE-nyCw kUvavr-HFRo +kVc4rvcsbXA kVw-9qqFqc8 kW3uSQR4dT8 kW_aesplxro kYYEJG2qzNg kaGKvOlLJMc kbx__jpC6S0 kc2r3upYr70 +kcVeCz4vdDU kcwAhVWfmT8 kdBqOW6mwK4 kdUHHNYjTW0 kdpOpfLtxkI kg6QW0uYEFc kgBf_gashl4 kgwPLt7CvwE +kiGEOFq1W6s kicFRjjK1Qc kjNtZcOSKcQ klQvlN4t_QI klTaei4PxGU kmk4fUSNVvo kodX-lW6FOU kpMx466mggs +kpPGzsfPW0I kpyuQ1uy_bM krg4qBL2PqE kriM097qwq4 ktxGKOYsHEg kx0N-uMqkM8 kxNThY2_b3E kxjq7O_BS1c +kyNRV55WbuA l-NRriQrnP0 l1eCgZIaL4A l28gTqa-IdA l28kI95-X9g l2QYu_nEAlk l5iTspd7P_M l74ZiAVdCng +l7ow3qWedX0 l92JSoaNReU lBDhmPOYzOA lCjBY7NtHqM lDiVPWJsBoA lE37HlwvZ6o lEAT58mdMG8 lEicAJv49y0 +lHWWnrtPQ8Q lIS-hXk1ZQs lKbQu5GSZec lNFm1d6MMm8 lNKlgUP0A1w lNv0Xmg3NyY lOnZIHhNyCU lPEwHT3Vw6M +lPOD3z7aXic lSN4XyohdMs lThk5cCURe4 lUGtjkiDATM lUUwOjxD6fc lVzPUJQsq-c lWqA7mdgRZA lX61xiXIZTw +lXW-NOht7jY lY2il186i9A lYtexW03xoE lZ8I7cyaf8M lZdrqRn6Ibg lbap0hnpqcs lf1h-McIZZc lg6WlBDlpOY +lguYZ5LaUD4 lhY2_46vIWk lizrEhuH1Xo lkL7oEAU00U llfFcdK8xNY llp_t6VwBvY lnTUVxI9s34 loa8nPCcRy4 +lpJsvubNfIY lphikLshfPc lpva7-eg0x8 lqtohzyKUE8 ltnIz_AW28o luJZVvY1nZM luTFihBR3dk lubluswh-bg +lwilLKcSnc4 lyYuEPUI23E m-TaP9dRyw8 m0uITrGFO7Q m14uKyw1c0Q m2whLDOjyJs m4GyrkKGiQI m6EKlazLeYM +m6Q-7ct_n60 m8hZjMS5DtI m91nDIbWHvc m9R5Q4DCwNQ mA8oQCBEQ_I mAuSqa2mxPA mBO0NGHPKlA mBaw-VS_L3o +mCqKGmYDLm8 mDHho_YtDCw mDdU52pIXwA mDlyhJKd81M mEXyt6yrHkc mEhNag0pZ9U mFVg1Woho_I mIYlSwdrSuU +mLTOIB51DM8 mLjGhDHoDKk mMAJUq-GtkE mMHit4fNnvA mMRrGMag9DI mMnkaKylaB8 mMvgBIVA5FU mNLvSEeMdyM +mQeEQJ6-O3o mROKDNSJ-A8 mSjQqeaFVeY mSmHEWSPB-I mTOVOgzfLYc mUc-SDzIO8g mWCL6r_75o0 mXtQf4Uvjq4 +mYxzGRd_lcI mZ27dJROA40 maLEaE6AOTQ mas3dd1Rmy4 mbhYLoDk2Tc md2_0sbq8PY meXWiw0Oa6A mgTFd3WPN9Y +mghFJm_5RqE mgm-5Qg3kas mgpclrI1rlM mgx4IwBrjp8 mh5akkhkUhI mhrx_Il08iQ mjd4zir80nQ mjocLNkUWgM +mjz-grVIkWk ml4r0xOlYhg mmJvdOnhKVg mmTIhNi6khQ mmYltg-r324 mnvPXjKfZws moaXrVW725o moijHEsvnYc +mqNbHLSM5lk mqRjHYdj0tM mqipiYGk9I4 mrG7T2rjLLs mrOUZDhrUb8 mrjCZ1sYG3k mtXWcIrFlw4 mtsO_Cyq_ZU +mvG2zpqRSlw mvhy2cqKp2M mxQaNIq3ksg mxYDjoXyPgk mxzfYftIHGA myUPrygECs0 mycBdy0RWtY mz-dq_3pQqA +mzyeAAF9tSA n-DmuATGhTM n-hknvfRf_I n2GAFmERdsE n3D53PS58yA n3FHwFk1i5o n4XDqOZhABU n5JUz0g5354 +n7YvbeKEPu4 n9-J6qKZbjQ n9RUttHbHhA n9nya_vCoGw n9w2x43iUBU n9xGULWQcEY nDbOZyCPIYg nEvgqOkyBDQ +nFLrKPQacJg nGrlD5RbKhQ nJdvvsUexLY nKeWuAijLQA nODhMDMnPho nOLDierdAQ8 nQAo9BdFFWY nSB9sTMegWI +nSOt982eYTE nSbHWHHsOxQ nV0qgkW9bGU nV3_KVYomOo nVHlmn0ZBO0 nXOTTWlgWiY nXOx_boZwkI nYaanQMpXqU +n_-fnIkR5uY nb294kKj3zc nbGOEm50kfw nceFrhDQX5s ndOVxj_LtQM nfO6V2khNMk nfyjjdGLhdQ ngVGe6-x678 +ngkQ7IdLP6Y nlQkOijD9dw nlSBrouZcUU nlyJgMQaGtQ nmw8FJSlSik noNRXpyh8GE noQbvDj1Hmo noUyxbyULQQ +np2yIKT2rGI npbmdk1N5jk nqOI9Ehd8qg nqX_p747f5Q nsPcvVug5HA ntIyZwU3XZ4 nwR9bIbFdTI ny4cDtnkKaY +ny5V32Lw_i8 nyngRxw0mCI nyvcm-E1fh8 nzjXI5vPQbI o-lEguH62Ys o03k-36Y-oY o1ZGlUFya0Q o2-btENtVB0 +o2On5UFlTYg o2TO8MXHrn0 o2nqDxDPfP4 o4ulYG_vIMY o59GRxwg4oU o5WGvj7tYFI oA4mdRzFkuA oAUYXaogYiQ +oArkwhHEmLY oBLHBrXhcz0 oCemiRCJFy0 oCfDQI59Ajg oHMkPlhZABw oIMWrftlyYk oJRbV9u46ag oJTDNwNmsBk +oJjIotGNsXc oJkCh1Q1nsU oKKzLDqqOOI oKYluIBAbeQ oLd4JzT2AsQ oNMaYZod7o8 oOREuGBW7Uc oPq0IKiaKNU +oQ_kq7TK_MM oQaC1qjnfLI oQaU0Z-PVYc oRsflVgLuCI oUQzNNE4t7c oV00CEzAnww oVLm9PSue7M oXFI59m7P8A +oYo7zmrUW2w oZN5NJs_nSI oZdY2Tlv1aE oZexjPJ2-No oZi-o61QVV4 o_2Ich9hgFc oa5ZUnJbROI oauJmENhCR8 +obsY7Nkd_IU oceDHNq0Rq8 ocke2xEA_xU odrzAsiDbc0 oeyXrgIf28c ofCaAlBObEY ogdYjckg73o oi8eJPgq3Is +ojuET65voLs okdc1wrBkC8 ol02Cw3eCZc onzUUGlfT6s oo5agobakJI orxaxGY0L9M os3yNDis5d4 ot7PpoDtowc +ouav6O6siCc oud9CDbMy6I ovAyEbeOdJk ovCZdwVahuo owRq9ZQM_Hw owSzetHsFdk owre9II7OVA ox0up7UzIfc +oz72pFVJ29Q p-X8r6CnWAg p0GWGqMuYZo p1W5f0CdgSI p2HDyugL4Yw p2KWqPxd_ew p2wwxGGmF-I p2ylBWoCMKg +p3I2AJC_ra0 p4BbNzwUqGk p4ofuI-w5i0 p6XNU0AwdcQ p7TSQt1eXDg p7xSy1QPx5c p8FK0w-a6Ms p8_teENoTg0 +p9-v2-DxvrQ pA9p11x1AEs pAET7aJgPRA pAKkCjvP8wI pBsmuOCKwsU pDHpLRVvUQk pDV2gffK400 pEPH3dEofRo +pEZYqFGw0ag pH3y_JV1KIE pI7lvnE0qQ8 pI9e_qZTly4 pIC8T6DHUjw pJ1QHRL770I pKMB-uWah9w pPqhz9PEFIM +pQex19Pj7Ko pRTRJlxy0EE pSEqFnanxu8 pSXF1E6FRWk pSoaFh5NiGM pSrpdwbM3NU pTSRhSD-M8M pUxqtVLjk58 +pUz2AcTl-CA pWFzN2LkYi0 pZQ_LlTEOk0 pZg4YVa54mI padTcgLowhE pag75BB5RUI pc3sHLan71w pe8d0RKfuEA +peJjnk_lf74 peK-zL7VSDE pgFOpYtjgOY pgqOhBopjRU pgwcOmCBin4 ph00PAtmB30 pi7SV6AP0G4 pjK6HtrRSSE +plbl-7YwDbE plw0ugfnug0 pm_8KJGnRqw pqfLT-6TWek prknx0IIZ3k psR2qMBLEUU pt895iu1FkA ptSx_0JcvZ8 +ptT8ehb6S6M ptj6kFZskMo puenwNeeZqc pvKscsuZPfI pvvvVwxm7R4 pwYfZI0rCM4 pxNZFJ4kxhw pxTejdu-_j8 +pyODV3Z8DOw pzGF0pqvjLk pzJOmJc755c pzekJZtnMeE q0wnZeJXVhI q2_a7rMHtko q31N5hsSj2A q3J64rZgbys +q3NTiAsb8JY q3P8bCrfX-Y q4AuAJymA4o q4PDwJuqE_w q6HqqO3l2N8 q6ooQzaoGyk q8ArwWzCFzU q8B7MmrQJ54 +q8qd-ZkzF0s q9yvTUJkWB8 qAAL7RyysAw qAE8zNDP_1w qAqZiP0395E qCt4aQk-Cxk qF7cODTAnFw qGNP55mNhIM +qHznDLDQGpg qIktSDGclnw qKDoy0z6y2w qKoqa6hs_V8 qKp5CgEa-Nc qNqguJX7ObA qOI4GoJaQhU qPblYC2AiKQ +qQupfSJMXVc qS4LsiWaRW0 qV6trb6jxns qVG-pJ6H8Ns qVH9ytPYE4c qYK1LPOS5rs qYLfTOQbNlQ qZJftmZ_Zzc +qaynmzzqSHQ qbA6oePeQXk qbzjOLMnq4I qeAHPpABLq4 qeeVmvKOEDI qemOjVv21yg qfpmKEsWtiY qhPVqHY7uWk +qiVowHApgPc qirKP6XNpPM qiydeUtuzGg qlKSnYDXot8 qmVHY4aHE78 qmoukYj874g qnESF8aHhQg qp1H7FTb368 +qpIx8u7bk0Q qpUFrYyEX4Y qr2K8Bkt8xw qrRci1eQlxI qrl7bnxMTdQ qsbGoOJrVsc qtk6nHmUZ-k quuIEg9Lueg +qwVsK653DKM qzE4e4CoUe0 qzlnVA78Ycc r2cexbetiGI r3mkQ2y-bKk r7CZDLGvP0Y r7FKV0G4TL8 r9RgAVTcer0 +rBkMfg_CTrc rBq5uMztEmo rC90tg2reI4 rCfrXaLG7Cg rCsSYGHOAUc rFateitzhhQ rFzFCWTMfVc rG_y4hKnnX8 +rH1EY7dzaFU rHYzL48q43E rJqQd8SNQe8 rN5iEcJIVlo rOfW0q8IXAo rOx8_F2u-IQ rRfWbRU3W8I rSveWcaNa38 +rTjjuk5p1fA rWdlMOoMYwc rX6qRgDo69w rXC07I2o53M rXr8QeyLreI rYO7CLwW67U r_871WcBevI raZxtFPp54w +rc_twysJCjI rchHEFDeCKo rdrnowCfCEM rexmjYfxqeU rfCKVUZ6btQ rg4r-Hz-50g rj6Dtes-hjQ rjrTpXzLgDU +rkek29QDKZw rl-yRbrYTIY rlOok8qvgP8 rm5O8Dx14zQ rq-PW_6GFGc rq9lOw0GO3I rr_amkER1yU rsA1ODwJ93k +rsGjuMLgXyA rsMruK64zeg rtCP4gnWKlY ruJ8sUn7cqY ruwMJD9trsk rv4K32M7qmQ rvp_7zb1LyQ rwxKgklJsIQ +rxHJSbvszfo s0AcHp19u9Q s0cFNZEh9r0 s0iQ3jStzx4 s0q83eLzmto s1-zW9RGPWE s1CkGf986O8 s2ORU7vy1ac +s4bo843WSgc s540SOqbMiM s5BcRv8ygeE s69USIxuzB4 s7KNLzzrTyM s7PrJyCQ5F4 s9_QQ_gV9Ds s9pXSFGtSno +sA67tbJ_s2U sAKjwyWsntQ sC9ARC8yM6Y sCgsM8t5LK8 sCzR3AULYgI sD-phJs_sPE sGCDUM8q5Y4 sGSbEFsGqe8 +sGt8Ea_vIYs sJ46e6O_a64 sK-4SQeb1fY sKHqmVqZkpg sKjeLxSZg_c sLTVma5RzE4 sMvI6vRMhFo sNiN14U5jdI +sO254eYJkn0 sPAg3Jspgvg sPlg6eI0gnI sQJOY0TF2j8 sV5MDCoO4oY sWR_rXg-sig sWronHpy6RU sWsG8XduA_k +sXKHmYJcoyU sXnmwGJvlFo sY666K1ZMCQ sYrXERV0X-c sYtPAYKabxE sYtfIv5fO50 sYxeg8EIwEk sZLOpjMDhcM +sZmNw2zjMZg s_KbezM_FO8 s_p73HZi5B0 sbBy9yWYQok sdc_w8RpIOw sddnafyou9g sgSpdtfY_Ok sgbIYzm6IFs +sgl5nXvOJIQ shOIW7Shz-s skUHhKU_3eo skab4V_TEEM skpL835-rno sm1RmHHEOoY smdxXU4UQ2A snlxW0ksNNA +sny37LRcnro soNLqFxJzP8 soNg5phAK3o soR_eE201tM sqP6dLPUdiA sqwWZU11G90 sr5_6YA9fI4 stK8z2nUgbE +suF346qnY24 suWTAY68Pjw svp_-4Fr-Rc swPXblo9x48 sww4Ror0cVU sxqxcYr7BqQ t-CHyT8WlZk t-XlvDfPVBA +t-b0ZjifgSw t0YlrOkn2JQ t3OTr-d7Pd0 t4kufQsYD6M t4tTJRoOFtw t55XnuglFzw t5mQEwExZPE t5tV5dELGYA +t61WzYr4OwA t6ExI2Q5XHY t7eOCHBVL0A t941OlI5Goo tAAS4OuxH8Q tC-Op_k-OYk tCrVo09jaGU tD8cxxXFwfw +tDLBp4Oz9Lw tFH_2fKSAZ0 tGgPf4uSIpE tHLYvR4Zuok tHYznyL33To tI1pp7Xeuho tIwbNT78Txs tJjwC7tes8E +tJqz4kpTJPA tNCocn4cKAw tPI00t-SsvE tQPRZXVsZqI tQqxZ3GGht4 tRe8oR9ufAY tT1qR2FfvTg tU8T4_16avc +tUN9sJZ8qcM tVgF0VzrrkA tWOHUcrRL00 tZWzSAZEHic t_yoSTlLGkE tb6TYc7dftY tcZPrNEgWQU tfHjD5fLVJI +tfsf5ib4vOc thwxmJcP1h4 ti1SMjBO3Uo tqtkBGXN0AA tt50nwZLaKQ tt82fEyc9us ttJedcAzdM4 tuZOi0l1uRE +tvi4AF_dkQM ty9Ua1msG0M tymyVOMhhy0 tzWirkcWALM u-78bG7G4w4 u-Gz7U6Tzec u0nfn1UcnVs u1lIu9eewa0 +u1rbWYcxYpY u2-bMihcXfY u2T1xzYqNk0 u2zPAFN6O-0 u3tiu_UoIZg u4kyKgnXFR8 u5IbpuYzK0c u5gV7VJKCqE +u5hL0ZNEKNU u6huoEKQtng u7xMTskkHbo u8SN6BAo7ww u8cXoX1-FmA u8rIVUS_ieU u95es4ommto u9jLDeqCfjI +uAfqqOaIWFE uB1drixWfpI uBRc2sDcWdc uCF8F2G1qzk uCT_liol_kE uDBFgzV_zBQ uDOJ_LdvVO4 uDfyVFerWFU +uDls0yM9idA uELjz5U6P4E uFv3ZDkCRQY uGR13605s3g uHJf56h2p-Q uHey2Y13K9Y uIGXzHZYhek uIrH5bTLdL4 +uJQ9-NhSt6c uM7QWpqsHNE uOdogLIC7aI uPNS0YTuUNE uQHyRdXWm3M uQI-jNPnPnU uRzFd9c7wlU uSv9nRNCgBk +uT9EG-jkFlI uTkfMClM-NQ uU5opNkKBGE uURjIFWLLVo uUlqr0DZKnE uVktqfH8pnM uWOMB3U_zMk uWn9t_Tiblk +uX5L8TWZFSQ uYO9POF2KJQ uYtcYVyNDBo uZ68B9eYw48 u_O3r4kokCU uagwe4t41rE udLUMwAW46I udbAByLld1g +ueKI64306YU ueNNzic_s3E uil9gkB7Or8 ujo_tlE79_E ukWLCWUxL1c umfq16eUTUA un9UI4MmfRc uoSCLX_wIns +uoa-At5ICT8 uokeYClgVJI upFTaLzyoXo uqj2TKa4Zy4 urYhO-o-PSA usAAJ1Gf5OU usIHxiWFUIo utN7QlG6pHo +utR1BI7pTyk uuu0KRaz8Jk uvbZVk5g6Ro uwK7jK5DS1s uxcyAapeoP8 uynucbfqcPQ uz2Ugsc2N5Y uzX_opsSfxc +uzipe1V8fl4 v-3JBT2wVMI v-emGMRxvOE v0TCL0Tay70 v182p1Hwtrw v3Y78H6EUlw v4HOBpYbAFk v5PGft1gLIc +v7B2Nt_74po v8V2ZR3vfzQ v9t-n5p7B6s vATDatGWAMM vAkJheVvdhg vCStvn05D_s vCcEvmy5pn0 vClk_3bRRP8 +vD0PUZ8MJAY vD61UzCxyOc vGNYsExmlAI vHZBMPxlnXg vICz_Lj0MXY vLQirAv4KKQ vMKo_dmcHhE vOAMDlj2578 +vOyTpuohqVQ vQ90aw3kmXk vQjI8I-RU00 vRfIYysaFGo vT6xch4TPfQ vTqe-YU7nTI vUStlzMuUxI vUq0ekC_8fg +vVRNcagSFQI vXHOnohDlCs vY1DGJAfeKI vYMVO1vBv_I vaF_q1N9mlE va_IKd1lJQA vav9TEi1FQk vbE4gwxT2Po +vbO4Ux_53KU veFGYf5gH9Q vfXSqbwUS0E vfaPqXFTCxg vhIel1047Fg vhNPg_0LYIc vjnpwtt3w7k vlrln8A44fI +vmupAfb3WrM vnOcNufsYTc vo769iJB7Sw vo9LO1Dx9ZE vpGm5c209-s vqZh3Rldux8 vqh-Fub5Hbk vs2cqznrmD0 +vtV-ZtRddKM vuHmrIUJkGM vus48Fuk5J0 vwEqg1uRg3w vwYcbsmBiYw vyHAyDQZNIo w025oPy5iAw w04rMcnyfaM +w0mCxu8Qq6E w2eYkd9z_rs w3x15MP_u6o w5-st2XTbLw w5SD79MATRg w6EqBTs3Umw w6HEKmlsv8U w7WJ0UXzFa4 +wA7dxd3m1nM wADIDX5HIUA wAWj1wboaXY wAYtxYNXu2o wB7LGR7cxjc wBTZGsm0cas wCSHQBpP8Tw wCVhoUEeklc +wCoXM8l-R5w wEFjedcflL0 wGVVsDaoCAc wGnfE849rKA wHVKZvQj-5U wHtVa0ta7HQ wI71qD6kE7E wJpzFW_snKk +wKmoVIyIpyw wM_gjRdERqw wPuTt9o2IL4 wRkZiFaAObc wWe5SGHFAeE wY72vgsCDas wYs9RIpzU1I w_y9Ettc5Yk +wa3SXf7eY6g waIwxZQfMFE waQqE7_BFUw wcE77Hcan4A wcIgXUhvx5g wdYO75EUVtQ weJ53x_ZFi0 wfIKEhABC-s +wgrJx0pARzA whIGuuPo30g whK-KPov488 whbT8uVlIFo wiaLrxyQfOo wiwZhXmntVA wnMZhCHbD5k woTfbkpTul4 +wozvv6RaIHU wqS74__HWXQ wqTP8rjkFpM wtd9SDtcSXQ wuYO3hJkDiA ww6ZOzo3j00 wx8PiuLhfek wxXGyzYB714 +wxx_D6r2_VE wy4znd1-g7o x0IBCZPLu64 x0mzqnPs65Q x1hAVeeufBk x3HFXGvdtDs x4C8aDhFieg x5SzqBWfH1k +x6M_vUEJQrs x78yKemJEU4 x7CGKe_L81E x7mwVrLYuaE x7oALXcSbuY x8TQFENzDME x8u8SSWOVxs x9_A2W9Uq6Y +xArP8nQoKz8 xBg4wi8eyFA xC423PuD4vo xCYkLfUF3VE xCcAMsjldAk xD1JEPYXgLs xFRISqTEWEA xF_Zbsx4Hds +xGb1qWkijHM xI33C8wlyJY xJOkrkU4HQY xKDoLpfKCQU xLhoIt26rIY xNX20hl1tTc xPcLWW2QrS0 xQ8mqOMd1gQ +xQRelHFQkcc xQ_Zed1---I xS50WVIpBW8 xTIpb8fTfAc xU6P9qn6OUs xXzktJ5vJ0I xZ7IEFi_QFI xZmvGB25J20 +x_R18mqlCi4 xb1U7a17d7Q xbpG0NLyFJw xcqrmvtLwfE xdBYaniyfak xfmSnKxVKLY xgAIQIhU8hI xia6RTzbpmY +xjxNyhQl5ec xl_WtGDQyDA xo5l8psu43s xoVge4jgNF0 xqRkx-hqW70 xqURjQp5F7E xrMjarAO_DE xrlpdXo61sk +xuEqCvcv0EE xvMulZC-qL0 xwIPSF8Mi_Y xwe7-uYulrQ xwsEjcP0fTU xxuz4h9Eti8 xyBWjx37zCs xyFtEtz3I0w +xylxRg5eLlk xzmLLQ4cMQU y--px05UJGA y1XdnvNayVs y4ly8cCLWHc y4o5P7lo4cE y5YQ-1TJ1pA y64hH_UR_68 +y7FzG3QTSZI y9FJ_jilXVE y9mLbUMdWlw yASl-a56xUc yC0-lHMD884 yDBkoQfxPGY yE4N_gqkgbo yEdoXjK5eXw +yEnSy-ZJGzc yI3GhVVF20M yJNPvdzgQvI yJnLb4k3p9U yLWXm75X-gQ yNPyut5VBu4 yOfshbG3mzM yPjbAixVeEQ +yRVAXiNXHmo yRck2buaoJI yRmQ6Sb4KZk yRn1qWennBc yU5R8JBYq2g yXnz79XvVpY yZ6eu7BeO74 y_qHn0Nei3o +yaDyakhky-M yahTrI2egWs ybDB0a7Svp8 ybsrdopSSOk ycNpoy6T7ro ycfz8VVlNZk yd-iHxWF-P8 yhfnPTFihgk +ylhEEPRjeDQ ymNSzcBls4E ymUvPXuy5bQ yniyDXHeQ-0 yoRfzHcqivw yqvGmZyv6KE yqzMFj8l0sQ ytIbTRL45wI +yuVhxOpZgDA yue9EZJxBX4 yvQFLaseF8E yvlXcyMR_K4 yvt1nXSeong yvzlPu2GqGs yxRQX3X5FPw yyAX1yLoi4E +z-bA46S_r8M z0xUyzkCDa8 z10u7fctLBw z2AsXquVOAs z2taG4Z7sUk z35ykE7y6sU z4lqKCEjuL8 z4nr442dBi8 +z5Cq3-WGFL0 z5Q8ksp3-lk z6UF3uNBiXs z6Vc9DTH6eM z7iARI7Atb8 z8Rv1LO7IJA z9T61LXMrGQ zAPxj9yCJno +zB4Y4sKWhV0 zBU7rk2TMKE zC4mgfn5294 zCw5x5JLAJQ zEPSsQUadO0 zFssBe-TJoE zG6fPayrAVE zHX8kb5eNfo +zHhOKTnzXS8 zHilDaOOJDg zHz4k7E1OVA zIdhIefRCYM zJf_BhLBiqU zKARJvQkw4U zKHJawgp1Ug zKSwTIqcMjI +zN34h_Zdbts zNgACQUqTSs zO8-Jr-8bO0 zODvf0PpwxY zPRja3Zlj_U zPwDU6EUKWU zQcCljbBai8 zR3jou-kudU +zRdM81h3HSE zRfQ5Oq4dt0 zRqNnlvujrE zTCFqVYZ0h0 zUHumhBXkls zXci2q_NTVc z_ax8zTCk_g zaNgSbAurTE +zaRMpdmusNQ zbLcww6e_kQ zbgJpym-aP8 zdyslMhKXbQ zeSIEiwAaOg zecFtc1tTPo zf4XJgj11PI zf9VNWI92kg +zfUNH6u3Rhw zfbh6icnhis zgaF3-hSFOU zglhUbPZKMg zhaDy_L-Hb0 zis4hsxJJxc zkSjEFZJfjA zkavAFDUYaM +zkf8l79TKcw zkftEqQVo64 zkj0Vps2V_M zlDDDMsw-Cc zmytUjRSsuo znMY20dsSxI zpJRL7BqIJE zqBlY7eQmvI +zqofQrksSHo zrweUKeg7Ic zuyxibedW4M zvOTsKZV97Y zvTaXu97TGk zvyaUtT0DeA zxC2oUHWlQ4 +`; + +export const catalogCopyTargets: ReadonlySet = new Set( + packed.split(/\s+/u).filter((digest) => digest !== ""), +); diff --git a/packages/app-management/src/implementation/catalog-copy-upgrade.ts b/packages/app-management/src/implementation/catalog-copy-upgrade.ts new file mode 100644 index 0000000000..fd549a5956 --- /dev/null +++ b/packages/app-management/src/implementation/catalog-copy-upgrade.ts @@ -0,0 +1,483 @@ +/** + * The mechanical upgrade the catalog-copy rebuild applies to a copy's own files, and the digest + * that names a reviewed result. Nothing here reads the catalog or chooses newer source. + * + * - Every source: `dependencies.apps` in `package.json` becomes the target release, in place. + * - Sources on host protocol 12 or earlier (`apps` before `0.0.1-beta.90`): `index.ts` moves its + * account requirements under `user`, exactly as the catalog's own move to `0.0.1-beta.100` + * (executor-apps aea5787c) rewrote every package: + * `defineApp({ accounts: { x: p.many() }, … }, async ({ accounts, … }) => … accounts.x …)` + * becomes + * `defineApp({ user: { accounts: { x: p.many() } }, … }, async ({ user, … }) => … user?.accounts.x ?? [] …)`. + * + * The rewrite recognizes only that shape and returns `undefined` for anything else: another file + * that names `accounts` in code, a context read as `ctx.accounts`, a requirement that is not + * `.many()`, a use of the accounts other than as an argument or value, or a name `user` already in + * use. `scripts/catalog-copy-snapshots.ts` checks every published catalog snapshot against the + * TypeScript compiler and the official `app-user-accounts` codemod before its result is listed as a + * reviewed target; the step rebuilds only listed targets. + */ +import { Array as Arr, Effect, Option, Schema } from "effect"; +import { + isTextFile, + JsonObject, + sourceText, + type SourceFile, + type SourceFiles, +} from "@executor-js/sdk/core"; + +/** An exact semver version; ranges, tags and other specifiers are not releases. */ +const exactVersion = + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/u; + +/** Semver precedence: negative when `left` is older than `right`. Undefined for non-releases. */ +export const compareReleases = (left: string, right: string): number | undefined => { + const parse = (version: string) => { + const match = exactVersion.exec(version); + if (match === null) return undefined; + return { + core: [Number(match[1]), Number(match[2]), Number(match[3])], + pre: match[4] === undefined ? [] : match[4].split("."), + }; + }; + const a = parse(left); + const b = parse(right); + if (a === undefined || b === undefined) return undefined; + for (let index = 0; index < 3; index++) { + const difference = (a.core[index] ?? 0) - (b.core[index] ?? 0); + if (difference !== 0) return difference; + } + if (a.pre.length === 0 || b.pre.length === 0) return b.pre.length - a.pre.length; + const numeric = /^\d+$/u; + for (let index = 0; index < Math.min(a.pre.length, b.pre.length); index++) { + const x = a.pre[index] ?? ""; + const y = b.pre[index] ?? ""; + if (x === y) continue; + if (numeric.test(x) && numeric.test(y)) return Number(x) - Number(y); + if (numeric.test(x)) return -1; + if (numeric.test(y)) return 1; + return x < y ? -1 : 1; + } + return a.pre.length - b.pre.length; +}; + +/** The first release of host protocol 13, where requirements are nested by scope. */ +export const scopedRequirementsRelease = "0.0.1-beta.90"; + +const Manifest = Schema.fromJsonString(JsonObject); +const Dependencies = Schema.Record(Schema.String, Schema.Unknown); + +/** The exact `apps` release a source declares, if its manifest is JSON and declares one. */ +export const declaredRelease = (files: ReadonlyArray) => { + const content = sourceText(files, "package.json"); + if (content === undefined) return undefined; + const manifest = Schema.decodeUnknownOption(Manifest)(content); + if (Option.isNone(manifest)) return undefined; + const dependencies = Schema.decodeUnknownOption(Dependencies)(manifest.value.dependencies); + if (Option.isNone(dependencies)) return undefined; + const apps = dependencies.value.apps; + return typeof apps === "string" && exactVersion.test(apps) ? apps : undefined; +}; + +/** The package name a source's manifest declares, if its manifest is JSON and names one. */ +export const declaredPackage = (files: ReadonlyArray) => { + const content = sourceText(files, "package.json"); + if (content === undefined) return undefined; + const manifest = Schema.decodeUnknownOption(Manifest)(content); + if (Option.isNone(manifest)) return undefined; + const name = manifest.value.name; + return typeof name === "string" ? name : undefined; +}; + +/** + * `content` with the single `"apps": ""` declaration set to `to`, byte for byte otherwise. + * Undefined unless exactly one declaration matches and the result parses to the same manifest + * with only `dependencies.apps` changed. + */ +const repinnedManifest = (content: string, from: string, to: string) => { + const escaped = from.replaceAll(".", "\\.").replaceAll("+", "\\+"); + const declaration = new RegExp(`("apps"\\s*:\\s*)"${escaped}"`, "gu"); + if ((content.match(declaration)?.length ?? 0) !== 1) return undefined; + const replaced = content.replace(declaration, `$1${JSON.stringify(to)}`); + const before = Schema.decodeUnknownOption(Manifest)(content); + const after = Schema.decodeUnknownOption(Manifest)(replaced); + if (Option.isNone(before) || Option.isNone(after)) return undefined; + const dependencies = Schema.decodeUnknownOption(Dependencies)(before.value.dependencies); + if (Option.isNone(dependencies)) return undefined; + const expected = { ...before.value, dependencies: { ...dependencies.value, apps: to } }; + return JSON.stringify(after.value) === JSON.stringify(expected) ? replaced : undefined; +}; + +/** + * Blank out strings, template text, comments and regular expression literals, keeping offsets, + * so the rewrite only matches code. Template substitutions stay code. + */ +export const codeOnly = (text: string): string => { + // UTF-16 code units, so offsets match the text's own (an emoji is two). + const out = text.split(""); + const blank = (from: number, to: number) => { + for (let index = from; index < to; index++) if (out[index] !== "\n") out[index] = " "; + }; + // The kinds of brace open at each depth: `{` in code, or a template substitution's `${`. + const braces: Array<"code" | "template"> = []; + let index = 0; + // Whether a `/` here starts a regular expression rather than dividing. + let regexAllowed = true; + const templateFrom = (start: number) => { + // Reads template text from `start` (just after a backtick or a substitution's `}`) to its end + // or the next `${`, blanking the text. + let cursor = start; + while (cursor < text.length) { + const char = text[cursor]; + if (char === "\\") { + cursor += 2; + continue; + } + if (char === "`") { + blank(start, cursor); + return { end: cursor + 1, substitution: false }; + } + if (char === "$" && text[cursor + 1] === "{") { + blank(start, cursor); + return { end: cursor + 2, substitution: true }; + } + cursor++; + } + blank(start, cursor); + return { end: cursor, substitution: false }; + }; + while (index < text.length) { + const char = text[index]!; + const next = text[index + 1]; + if (char === "/" && next === "/") { + const end = text.indexOf("\n", index); + const stop = end === -1 ? text.length : end; + blank(index, stop); + index = stop; + continue; + } + if (char === "/" && next === "*") { + const end = text.indexOf("*/", index + 2); + const stop = end === -1 ? text.length : end + 2; + blank(index, stop); + index = stop; + continue; + } + if (char === '"' || char === "'") { + let cursor = index + 1; + while (cursor < text.length && text[cursor] !== char && text[cursor] !== "\n") + cursor += text[cursor] === "\\" ? 2 : 1; + blank(index + 1, cursor); + index = cursor + 1; + regexAllowed = false; + continue; + } + if (char === "`") { + const read = templateFrom(index + 1); + if (read.substitution) braces.push("template"); + index = read.end; + regexAllowed = !read.substitution ? false : true; + continue; + } + if (char === "/" && regexAllowed) { + let cursor = index + 1; + let inClass = false; + while (cursor < text.length && text[cursor] !== "\n") { + const current = text[cursor]; + if (current === "\\") { + cursor += 2; + continue; + } + if (current === "[") inClass = true; + else if (current === "]") inClass = false; + else if (current === "/" && !inClass) break; + cursor++; + } + blank(index + 1, cursor); + index = cursor + 1; + while (index < text.length && /[a-z]/u.test(text[index]!)) index++; + regexAllowed = false; + continue; + } + if (char === "{") { + braces.push("code"); + regexAllowed = true; + index++; + continue; + } + if (char === "}") { + const kind = braces.pop(); + if (kind === "template") { + const read = templateFrom(index + 1); + if (read.substitution) braces.push("template"); + index = read.end; + regexAllowed = !read.substitution ? false : true; + continue; + } + regexAllowed = false; + index++; + continue; + } + if (/[\s]/u.test(char)) { + index++; + continue; + } + if (/[A-Za-z0-9_$]/u.test(char)) { + let cursor = index; + while (cursor < text.length && /[A-Za-z0-9_$]/u.test(text[cursor]!)) cursor++; + const word = text.slice(index, cursor); + // After a keyword such as `return` an expression starts; after a name or number it does not. + regexAllowed = + /^(?:return|typeof|instanceof|in|of|new|delete|void|throw|case|do|else|yield|await)$/u.test( + word, + ); + index = cursor; + continue; + } + // Punctuation: a `/` after `)` or `]` divides; after any other operator it starts a regex. + regexAllowed = char !== ")" && char !== "]"; + index++; + } + return out.join(""); +}; + +/** The offset of the bracket that closes the one at `open` in code-only text, or undefined. */ +const closing = (code: string, open: number) => { + const pairs: Record = { "{": "}", "(": ")", "[": "]" }; + const stack: string[] = []; + for (let index = open; index < code.length; index++) { + const char = code[index]!; + if (char in pairs) stack.push(pairs[char]!); + else if (char === "}" || char === ")" || char === "]") { + if (stack.pop() !== char) return undefined; + if (stack.length === 0) return index; + } + } + return undefined; +}; + +const identifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/u; +const skipSpace = (code: string, from: number) => { + let index = from; + while (index < code.length && /\s/u.test(code[index]!)) index++; + return index; +}; +const previousNonSpace = (code: string, from: number) => { + let index = from - 1; + while (index >= 0 && /\s/u.test(code[index]!)) index--; + return index; +}; + +/** + * One change to `index.ts`: the declaration's new `user: { ` and ` }`, the factory's binding, or a + * read of one requirement. The kinds let the generator compare the codemod's own style. + */ +export type ScopedEdit = { + readonly kind: "declaration" | "binding" | "read"; + readonly start: number; + readonly end: number; + readonly text: string; +}; + +/** Offsets of each whole word `word` in code-only text. */ +const wordsAt = (code: string, word: string) => + [...code.matchAll(new RegExp(`(? match.index, + ); + +/** Whether every code use of `word` is a property (`x.word`) or an object key (`word:`). */ +const onlyProperties = (code: string, word = "accounts") => + wordsAt(code, word).every((at) => { + const previous = code[previousNonSpace(code, at)]; + const following = code[skipSpace(code, at + word.length)]; + return previous === "." || ((previous === "{" || previous === ",") && following === ":"); + }); + +/** `text` with `edits` applied. */ +export const applyEdits = (text: string, edits: ReadonlyArray) => { + let result = text; + for (const edit of edits.toSorted((left, right) => right.start - left.start)) + result = result.slice(0, edit.start) + edit.text + result.slice(edit.end); + return result; +}; + +/** + * `index.ts` with its account requirements moved under `user`, as described above, or undefined + * when the source is not exactly the catalog's shape. + */ +export const scopedIndex = (text: string): string | undefined => { + const edits = scopedIndexEdits(text); + return edits === undefined ? undefined : applyEdits(text, edits); +}; + +/** The edits {@link scopedIndex} makes, or undefined when the source is not the catalog's shape. */ +export const scopedIndexEdits = (text: string): ReadonlyArray | undefined => { + const code = codeOnly(text); + // `user` is the name the factory's context gains; a variable of that name could be captured. + if (!onlyProperties(code, "user")) return undefined; + const calls = [...code.matchAll(/(?(); + const names: string[] = []; + + // The requirement: `accounts: { … }` directly in defineApp's first argument. + const requirement = wordsAt(code, "accounts").filter((at) => at > objectOpen && at < objectClose); + if (requirement.length !== 1) return undefined; + const key = requirement[0]!; + const before = code[previousNonSpace(code, key)]; + if (before !== "{" && before !== ",") return undefined; + if (closing(code, objectOpen) !== objectClose) return undefined; + // Directly inside the object, not nested in a value. + { + let depth = 0; + for (let index = objectOpen + 1; index < key; index++) { + const char = code[index]!; + if (char === "{" || char === "(" || char === "[") depth++; + else if (char === "}" || char === ")" || char === "]") depth--; + } + if (depth !== 0) return undefined; + } + const colon = skipSpace(code, key + "accounts".length); + if (code[colon] !== ":") return undefined; + const valueOpen = skipSpace(code, colon + 1); + if (code[valueOpen] !== "{") return undefined; + const valueClose = closing(code, valueOpen); + if (valueClose === undefined) return undefined; + const entries = code.slice(valueOpen + 1, valueClose).trim(); + if (entries !== "") { + for (const entry of entries.split(",")) { + const trimmed = entry.trim(); + if (trimmed === "") continue; + const match = + /^([A-Za-z_$][A-Za-z0-9_$]*)\s*:\s*[A-Za-z_$][A-Za-z0-9_$]*\s*\.\s*many\s*\(\s*\)$/u.exec( + trimmed, + ); + if (match === null) return undefined; + names.push(match[1]!); + } + } + edits.push({ kind: "declaration", start: key, end: key, text: "user: { " }); + edits.push({ kind: "declaration", start: valueClose + 1, end: valueClose + 1, text: " }" }); + handled.add(key); + + // Code uses of `accounts` that are a property of something else (`client.accounts`, a router + // key `accounts:`) stay as written. Whether such a property is a context's, which the upgrade + // would have to rewrite, is checked offline against the codemod for every listed target. + for (const at of wordsAt(code, "accounts")) { + if (handled.has(at)) continue; + const previous = code[previousNonSpace(code, at)]; + const following = code[skipSpace(code, at + "accounts".length)]; + if (previous === "." || ((previous === "{" || previous === ",") && following === ":")) + handled.add(at); + } + + // The factory: defineApp's second argument, `async ({ …, accounts, … }) => …`, if it reads them. + const comma = skipSpace(code, objectClose + 1); + const accounts = wordsAt(code, "accounts").filter((at) => !handled.has(at)); + if (accounts.length > 0) { + if (code[comma] !== ",") return undefined; + let start = skipSpace(code, comma + 1); + if (code.startsWith("async", start) && !/[A-Za-z0-9_$]/u.test(code[start + 5] ?? "")) + start = skipSpace(code, start + 5); + if (code[start] !== "(") return undefined; + const bindingOpen = skipSpace(code, start + 1); + if (code[bindingOpen] !== "{") return undefined; + const bindingClose = closing(code, bindingOpen); + if (bindingClose === undefined) return undefined; + const binding = accounts.filter((at) => at > bindingOpen && at < bindingClose); + if (binding.length !== 1) return undefined; + if (wordsAt(code, "user").some((at) => at > bindingOpen && at < bindingClose)) return undefined; + const at = binding[0]!; + const previous = code[previousNonSpace(code, at)]; + const following = code[skipSpace(code, at + "accounts".length)]; + if ((previous !== "{" && previous !== ",") || (following !== "," && following !== "}")) + return undefined; + edits.push({ kind: "binding", start: at, end: at + "accounts".length, text: "user" }); + handled.add(at); + // Every other use reads one requirement as a value: `accounts.x` before `,` or `)`. + for (const use of accounts) { + if (handled.has(use)) continue; + if (use < bindingClose || use > callClose) return undefined; + if (/[A-Za-z0-9_$.]/u.test(code[use - 1] ?? "")) return undefined; + const dot = use + "accounts".length; + if (code[dot] !== ".") return undefined; + let end = dot + 1; + while (end < code.length && /[A-Za-z0-9_$]/u.test(code[end]!)) end++; + const name = code.slice(dot + 1, end); + if (!identifier.test(name) || !names.includes(name)) return undefined; + const after = code[skipSpace(code, end)]; + if (after !== "," && after !== ")") return undefined; + edits.push({ kind: "read", start: use, end, text: `user?.accounts.${name} ?? []` }); + handled.add(use); + } + } + if (wordsAt(code, "accounts").some((at) => !handled.has(at))) return undefined; + return edits; +}; + +/** + * The copy's files rebuilt on `to`, or undefined when its upgrade is not the mechanical one. Only + * `package.json`'s `apps` and, before protocol 13, `index.ts` change. No other file may name + * `accounts` in code before protocol 13. + */ +export const upgradedFiles = (files: SourceFiles, to: string): SourceFiles | undefined => { + const from = declaredRelease(files); + if (from === undefined) return undefined; + const manifest = repinnedManifest(sourceText(files, "package.json") ?? "", from, to); + if (manifest === undefined) return undefined; + const order = compareReleases(from, scopedRequirementsRelease); + if (order === undefined) return undefined; + let index: string | undefined; + if (order < 0) { + const current = sourceText(files, "index.ts"); + if (current === undefined) return undefined; + index = scopedIndex(current); + if (index === undefined) return undefined; + for (const file of files) { + if (file.path === "index.ts" || !/\.(?:[cm]?[jt]sx?)$/u.test(file.path)) continue; + if (!isTextFile(file) || !onlyProperties(codeOnly(file.content))) return undefined; + } + } + const scoped = index; + return Arr.map(files, (file): SourceFile => + file.path === "package.json" + ? { path: file.path, content: manifest } + : file.path === "index.ts" && scoped !== undefined + ? { path: file.path, content: scoped } + : file, + ); +}; + +/** What identifies one file's contents, as `sourceFilesEqual` compares them. */ +const fileIdentity = (file: SourceFile) => + "object" in file + ? `object:${file.object}` + : "encoding" in file + ? `base64:${file.content}` + : `text:${file.content}`; + +/** + * The first 64 bits of the SHA-256 of the files in path order, base64url. It names a reviewed + * target, not a secret: a copy whose upgraded files have another digest is not rebuilt. + */ +export const sourceDigest = (files: ReadonlyArray) => + Effect.promise(async () => { + const ordered = files + .map((file) => [file.path, fileIdentity(file)] as const) + .toSorted(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)); + const bytes = new TextEncoder().encode(JSON.stringify(ordered)); + const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)).slice(0, 8); + let binary = ""; + for (const byte of hash) binary += String.fromCharCode(byte); + return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); + }); diff --git a/packages/app-management/src/implementation/data-steps.ts b/packages/app-management/src/implementation/data-steps.ts index 42b30b0252..1e8cacb87a 100644 --- a/packages/app-management/src/implementation/data-steps.ts +++ b/packages/app-management/src/implementation/data-steps.ts @@ -1,18 +1,27 @@ /** * Run pending data steps in order against a SQL journal. A pass walks a step's items in ID order, * records each outcome and a cursor as it goes, so an interrupted pass resumes after the last - * recorded item. Items are handled one at a time and must be safe to handle again. When a pass + * recorded item. Items are handled one at a time and must be safe to handle again. Each item sees + * its latest outcome in the run (`previous`), and an apply may `record` an in-progress retry + * outcome before it writes, so an item a stopped pass left part way is finished. When a pass * ends with retry outcomes, the next run starts another pass over only those items; a step is * complete once a pass has none. Later steps wait for earlier ones, as schema migrations do. * * Background runs back off between retry passes: each retrying pass records when the next may * start, doubling with the pass number up to an hour. Startup runs retry at the next start. + * + * An operator holds a background run without a deploy by setting its `retry_at` in the future + * (`'infinity'` until released): no run claims it, a run that holds it stops before its next item, + * and a retrying pass that ends meanwhile never brings it forward. Startup runs, which hold the + * host exclusively, ignore it. */ import { Clock, Effect, Schema } from "effect"; import { SqlClient } from "effect/sql"; import { + DataStepProgressUnrecorded, DataStepUnavailable, dataStepLogPrefix, + dataStepPaused, type DataStep, type DataStepJournal, type DataStepMode, @@ -81,7 +90,10 @@ const Unclaimed = Schema.Array( Schema.Struct({ completed: Schema.Boolean, retryAt: Schema.NullOr(Schema.String) }), ); const Retry = Schema.Array(Schema.Struct({ retryAt: Schema.String })); +const Held = Schema.Array(Schema.Struct({ held: Schema.Boolean })); +const Count = Schema.Array(Schema.Struct({ count: Schema.Number })); const Items = Schema.Array(Schema.Struct({ item: Schema.String })); +const Outcomes = Schema.Array(Schema.Struct({ outcome: Schema.String })); const Counts = Schema.Array( Schema.Struct({ owner: Schema.String, outcome: Schema.String, count: Schema.Number }), ); @@ -95,13 +107,15 @@ export const runDataSteps = ( const sql = yield* SqlClient.SqlClient; const journal = sql(`${options.journal}_data_steps`); const outcomes = sql(`${options.journal}_data_step_items`); - const run = options.mode === "apply" ? "apply" : `report:${options.report}`; + const report = `report:${options.report}`; // Only the caller reads these; the journal, retries and logs do not depend on them. let attempted = 0; let failed = 0; const advance = (step: DataStep) => Effect.gen(function* () { + const applyRun = step.applyRun ?? "apply"; + const run = options.mode === "apply" ? applyRun : report; const completed = (candidate: string) => sql`select completed_at is not null as completed from ${journal} where name = ${step.name} and run = ${candidate}`.pipe( @@ -112,7 +126,7 @@ export const runDataSteps = ( if ( options.mode === "report" && step.reportsAfterApply !== true && - (yield* completed("apply")) + (yield* completed(applyRun)) ) return "complete" as const; yield* sql`insert into ${journal} (name, run, mode) @@ -156,18 +170,71 @@ export const runDataSteps = ( // Later passes revisit only the items the previous pass left to retry. const revisit = pass === 1 ? undefined : new Set((yield* retryItems).map((row) => row.item)); + // An operator's hold (a future `retry_at`) stops a background run before its next item. + const held = sql`select coalesce(retry_at > now(), false) as held from ${journal} + where name = ${step.name} and run = ${run}`.pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Held)), + Effect.map((rows) => rows[0]?.held === true), + ); + const exhausted = + step.exhausted !== undefined && pass >= step.exhausted.passes + ? step.exhausted.outcomes + : undefined; for (const item of items) { if (revisit !== undefined && !revisit.has(item.id)) continue; if (cursor !== null && item.id <= cursor) continue; - if ( - options.deadline !== undefined && - (yield* Clock.currentTimeMillis) >= options.deadline - ) { + const stop = + (options.deadline !== undefined && + (yield* Clock.currentTimeMillis) >= options.deadline) || + (step.more !== undefined && !(yield* step.more)) || + (!options.exclusive && (yield* held)); + if (stop) { + yield* release; + yield* Effect.annotateCurrentSpan("data_step.status", "pending"); + return "pending" as const; + } + // An apply run with no outcome for the item reads the step's latest earlier apply run + // that has one: a stage that stopped part way left it for the next stage to finish. + const previous = (yield* sql`select item.outcome from ${outcomes} item + join ${journal} run on run.name = item.name and run.run = item.run + where item.name = ${step.name} and item.item = ${item.id} + and (item.run = ${run} or (${options.mode === "apply"} and run.mode = 'apply')) + order by item.run = ${run} desc, run.started_at desc limit 1`.pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Outcomes)), + ))[0]?.outcome; + const record = (progress: string) => + options.mode !== "apply" || !step.retry.includes(progress) + ? Effect.die(`Data step ${step.name} recorded ${progress} outside an apply retry`) + : sql`insert into ${outcomes} (name, run, item, owner, outcome, pass) + values (${step.name}, ${run}, ${item.id}, ${item.owner}, ${progress}, ${pass}) + on conflict (name, run, item) do update set outcome = excluded.outcome, pass = excluded.pass`.pipe( + Effect.asVoid, + Effect.mapError(() => new DataStepProgressUnrecorded()), + ); + const count = (counted: ReadonlyArray) => + sql`select count(*)::integer as count from ${outcomes} + where name = ${step.name} and run = ${run} and ${sql.in("outcome", [...counted])}`.pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Count)), + Effect.map((rows) => rows[0]?.count ?? 0), + Effect.mapError(() => new DataStepUnavailable({ step: step.name })), + ); + const handled = yield* item.run(options.mode, { previous, record, count }); + // The step's pace stopped the item part way: nothing is recorded for it, and the next + // run handles it again from the cursor before it. + if (handled === dataStepPaused) { yield* release; yield* Effect.annotateCurrentSpan("data_step.status", "pending"); return "pending" as const; } - const outcome = yield* item.run(options.mode); + // A retry outcome past the step's last allowed pass is recorded as its bounded outcome. + const outcome = exhausted?.[handled] ?? handled; + if (outcome !== handled) + yield* Effect.logWarning("Data step item gave up retrying", { + step: step.name, + item: item.id, + pass, + outcome: handled, + }); yield* sql.withTransaction( Effect.gen(function* () { yield* sql`insert into ${outcomes} (name, run, item, owner, outcome, pass) @@ -198,7 +265,7 @@ export const runDataSteps = ( const retrying = counts.some((row) => step.retry.includes(row.outcome)); const retryAt = retrying ? (yield* sql`update ${journal} set pass = ${pass + 1}, cursor = null, lease_until = null, - retry_at = now() + make_interval(secs => ${retryDelaySeconds(pass)}) + retry_at = greatest(retry_at, now() + make_interval(secs => ${retryDelaySeconds(pass)})) where name = ${step.name} and run = ${run} returning to_json(retry_at) #>> '{}' as "retryAt"`.pipe( Effect.flatMap(Schema.decodeUnknownEffect(Retry)), diff --git a/packages/app-management/src/implementation/host-data-steps.ts b/packages/app-management/src/implementation/host-data-steps.ts index 5adf376d08..6d01e74ff0 100644 --- a/packages/app-management/src/implementation/host-data-steps.ts +++ b/packages/app-management/src/implementation/host-data-steps.ts @@ -1,5 +1,5 @@ /** The data steps every host runs, in order. Local, self-host and Cloud share this one list. */ -import { Clock, Config, Effect } from "effect"; +import { Clock, Config, Effect, Option } from "effect"; import type { DataStepJournal } from "../contracts/data-steps.ts"; import { runDataSteps } from "./data-steps.ts"; import { frameworkPinCatchUpRelease, frameworkPinRelease } from "../contracts/framework-pin.ts"; @@ -36,6 +36,12 @@ import { type UnremovableWebhooksHostServices, } from "./unremovable-webhooks.ts"; import { agentGrantModesStep, agentGrantModesStepName } from "./agent-grant-modes.ts"; +import { + catalogCopyRebuildScope, + catalogCopyRebuildStep, + type CatalogCopyRebuildHost, +} from "./catalog-copy-rebuild.ts"; +import { catalogCopyRebuildStepName } from "../contracts/catalog-copy-rebuild.ts"; import type { SqlClient } from "effect/sql"; import type { DataStep } from "../contracts/data-steps.ts"; @@ -48,16 +54,19 @@ export type DataStepHost = FrameworkPinHost & LocalOwnersHost & OAuthClientsByIssuerHost & ProfileAppCopiesHost & - UnremovableWebhooksHostServices; + UnremovableWebhooksHostServices & + CatalogCopyRebuildHost; /** * A step by its journal name. A `local` step is listed only by a host that passes local owners: - * local, whose journal requires them. Self-host and Cloud never list one. + * local, whose journal requires them. Self-host and Cloud never list one. A step with `listed` is + * listed only by a host it accepts. */ type ListedStep = | { readonly name: string; readonly step: (host: DataStepHost, name: string) => DataStep; + readonly listed?: (host: Pick) => boolean; } | { readonly name: string; @@ -105,12 +114,23 @@ const listedSteps: ReadonlyArray = [ // One-off: store on each MCP grant the approval mode its consent's resource named, now that the // grant record, not the URL, holds it. { name: agentGrantModesStepName, step: agentGrantModesStep }, + // One-off: rebuild untouched copies of official catalog apps from their own installed source on + // apps 0.0.1-beta.140, where the account merge fix is (E-042). Listed only by a host that passes + // `catalogCopyRebuild`: Cloud, and self-host when its operator turns it on + // (`EXECUTOR_CATALOG_COPY_REBUILD=on`). See notes/catalog-copy-rebuild.md. + { + name: catalogCopyRebuildStepName, + step: catalogCopyRebuildStep, + listed: (host) => host.catalogCopyRebuild !== undefined, + }, ]; export const hostDataSteps = (host: DataStepHost): ReadonlyArray> => listedSteps.flatMap((listed) => "step" in listed - ? [listed.step(host, listed.name)] + ? listed.listed === undefined || listed.listed(host) + ? [listed.step(host, listed.name)] + : [] : host.localOwners === undefined ? [] : [listed.local(host, host.localOwners)], @@ -120,15 +140,53 @@ export const hostDataSteps = (host: DataStepHost): ReadonlyArray) => +export const hostDataStepNames = (host: Pick) => listedSteps.flatMap((listed) => - "step" in listed || host.localOwners !== undefined ? [listed.name] : [], + "step" in listed + ? listed.listed === undefined || listed.listed(host) + ? [listed.name] + : [] + : host.localOwners !== undefined + ? [listed.name] + : [], ); /** * Local and self-host apply pending steps at startup. `report` holds them: each start then reports * what applying would do, writes nothing and records no step as applied. */ +/** + * Self-host lists the catalog-copy rebuild only when its operator sets `on`: it applies at + * startup, without the report Cloud reviews first. Local never lists it. With `on`, every copy is + * in scope unless `EXECUTOR_CATALOG_COPY_REBUILD_SCOPE` names a narrower one (see + * `CatalogCopyRebuildScope`); turning the step on is the operator's choice for the whole host. + * An app still failing after three starts is recorded `gave-up`, since each start waits for the + * step before it serves. + * + * Self-host is not paced. E2E runs only, `EXECUTOR_TEST_CATALOG_COPY_REBUILD_PACE` with + * `EXECUTOR_ENVIRONMENT=e2e` paces each start as Cloud paces each tick, so a scenario can see + * where a pace stops the step; the next start resumes it. + */ +export const startupCatalogCopyRebuild = Effect.gen(function* () { + const listed = yield* Config.Literals(["off", "on"], "EXECUTOR_CATALOG_COPY_REBUILD").pipe( + Config.withDefault("off" as const), + ); + if (listed === "off") return undefined; + const scope = yield* Config.String("EXECUTOR_CATALOG_COPY_REBUILD_SCOPE").pipe( + Config.withDefault("all"), + ); + const environment = yield* Config.String("EXECUTOR_ENVIRONMENT").pipe(Config.withDefault("")); + const pace = + environment === "e2e" + ? yield* Config.Int("EXECUTOR_TEST_CATALOG_COPY_REBUILD_PACE").pipe(Config.option) + : Option.none(); + return { + scope: yield* catalogCopyRebuildScope(scope), + passes: 3, + ...(Option.isSome(pace) ? { pace: pace.value } : {}), + }; +}); + export const startupDataStepMode = Config.Literals(["report", "apply"], "EXECUTOR_DATA_STEPS").pipe( Config.withDefault("apply" as const), ); diff --git a/packages/sdk/src/contracts/executor.ts b/packages/sdk/src/contracts/executor.ts index eb3f8151c7..1d7c6080b6 100644 --- a/packages/sdk/src/contracts/executor.ts +++ b/packages/sdk/src/contracts/executor.ts @@ -37,7 +37,12 @@ import type { ToolSearchUnavailable, } from "./tools.ts"; import type { AccountScope, App, AppRequirements } from "./apps.ts"; -import type { BuildMemoryExceeded, BuildUnanswered, VersionBuildFailed } from "./version.ts"; +import type { + AppVersionChanged, + BuildMemoryExceeded, + BuildUnanswered, + VersionBuildFailed, +} from "./version.ts"; import type { Account } from "./account.ts"; import type { AccountConnectionRefused, @@ -50,6 +55,7 @@ import type { ApprovalRequestId, OwnerId, StorageError, + VersionId, } from "./shared.ts"; import type { BlobStorage } from "./blobs.ts"; import type { MarkdownReader, MarkdownUnavailable } from "./markdown.ts"; @@ -458,11 +464,30 @@ export type Executor = Omit ReturnType; + /** + * Host-only: `deploy` files to an existing app only while `expectedVersion` is its active + * version and nothing activated since this deploy reserved its order. Both are checked under + * the app's lock when the deploy reserves its order and again when it activates; otherwise it + * fails with `AppVersionChanged` and records no version. For a host that replaces a version + * it has checked, so a concurrent deploy or activation is never overwritten or mistaken for + * its own. A build the host's compiler or runner did not answer is `BuildUnanswered`, as for + * `build`. + */ + readonly deployReplacing: (input: { + readonly owner: OwnerId; + readonly app: AppId; + readonly files: SourceFiles; + readonly expectedVersion: VersionId; + }) => Effect.Effect< + Effect.Success>, + Effect.Error> | AppVersionChanged | BuildUnanswered + >; /** * Host-only: compile source files as `deploy` would and return the requirements they declare, * writing nothing: no app, version or source is saved, and the build is neither retained nor * cached. For checks that must not create anything. Fails - * like `deploy`'s build, except that a compiler that did not answer is `BuildUnanswered`. + * like `deploy`'s build, except that a build the host's compiler or runner did not answer is + * `BuildUnanswered`. */ readonly build: (input: { readonly owner: OwnerId; @@ -519,6 +544,6 @@ export type PromiseExecutor = Promisify< | "apps" > & { readonly tools: Omit; - readonly apps: Omit; + readonly apps: Omit; } >; diff --git a/packages/sdk/src/contracts/runtime.ts b/packages/sdk/src/contracts/runtime.ts index 5f3a18dba5..02fa58fbc3 100644 --- a/packages/sdk/src/contracts/runtime.ts +++ b/packages/sdk/src/contracts/runtime.ts @@ -281,8 +281,10 @@ export class RuntimeBuildFailed extends Schema.TaggedError() message: Schema.optional(BuildMessage), location: Schema.optional(SourceLocation), /** - * The compiler did not answer in time: a host failure that says nothing about the source, and - * that building again may not repeat. + * The host's compiler or runner did not answer: the compiler did not reply in time, or a call + * to the compiler or to the runner that reads the build's requirements failed before it + * replied. A host failure that says nothing about the source, and that building again may not + * repeat. Set only where the host made the call, never from an error's text. */ unanswered: Schema.optional(Schema.Literal(true)), }, diff --git a/packages/sdk/src/contracts/version.ts b/packages/sdk/src/contracts/version.ts index 38f39de773..93d1b0e40f 100644 --- a/packages/sdk/src/contracts/version.ts +++ b/packages/sdk/src/contracts/version.ts @@ -146,8 +146,9 @@ export const BuildMemoryExceeded = UserFacingError.define({ export type BuildMemoryExceeded = typeof BuildMemoryExceeded.Type; /** - * Host-only: the compiler did not answer, so the source was not judged and building again may - * succeed. Only `apps.build` reports it; a deploy reports the same failure as `VersionBuildFailed`. + * Host-only: the host's compiler, or the runner that reads the build's requirements, did not + * answer, in time or at all, so the source was not judged and building again may succeed. Only `apps.build` and `apps.deployReplacing` report it; a deploy + * reports the same failure as `VersionBuildFailed`. */ export class BuildUnanswered extends Schema.TaggedError()("BuildUnanswered", { owner: OwnerId, diff --git a/packages/sdk/src/core.ts b/packages/sdk/src/core.ts index 3f77d095aa..b3d921425f 100644 --- a/packages/sdk/src/core.ts +++ b/packages/sdk/src/core.ts @@ -29,6 +29,8 @@ export { type AppRuntime, type ResolvedAppRuntime, } from "./implementation/runtime.ts"; +/** Host-only: a retained version's source read straight from the given store, past any cache. */ +export { readVersionSource } from "./implementation/version-source.ts"; export { executorDatabase } from "./implementation/storage-migrations.ts"; export { StorageMigrationFailed } from "./implementation/storage-migration-error.ts"; export { makeExecutorStorage, type ExecutorDatabase } from "./implementation/storage.ts"; diff --git a/packages/sdk/src/implementation/apps.ts b/packages/sdk/src/implementation/apps.ts index 18239d000f..712c45975d 100644 --- a/packages/sdk/src/implementation/apps.ts +++ b/packages/sdk/src/implementation/apps.ts @@ -283,14 +283,14 @@ export const makeApps = ( /** * Build source files and read the requirements they declare, as a deploy does before it writes * anything; no app, version or source is saved. A deploy's build is retained in the runtime's - * build store. A `check` writes nothing at all, and reports a compiler that did not answer with - * its own failure rather than as a failed build. + * build store; a check (`retain: false`) writes nothing at all. With `unanswered`, a build the + * host's compiler or runner did not answer fails with that rather than as a failed build. */ const buildSource = ( owner: OwnerId, name: string, suppliedFiles: unknown, - check?: { readonly unanswered: () => E }, + options?: { readonly retain?: false; readonly unanswered?: () => E }, ) => Effect.gen(function* () { const files = yield* Schema.decodeUnknownEffect(SourceFiles)(suppliedFiles).pipe( @@ -322,16 +322,16 @@ export const makeApps = ( .build({ files: codeFiles, public: split.public.map((file) => servedPath(file.path)), - ...(check === undefined ? {} : { retain: false }), + ...(options?.retain === false ? { retain: false } : {}), }) .pipe( Effect.mapError((error) => Schema.is(BuildMemoryExceeded)(error) ? error - : check !== undefined && + : options?.unanswered !== undefined && Schema.is(RuntimeBuildFailed)(error) && error.unanswered === true - ? check.unanswered() + ? options.unanswered() : Schema.is(RuntimeProtocolUnsupported)(error) ? new VersionBuildFailed({ owner, @@ -433,11 +433,23 @@ export const makeApps = ( * `stored` reads the bytes of stored public files that a copy names from another app; an * existing app's own stored files are read from its repository. */ - const deploy = ( + const deploy = ( input: DeployInput, copiedFrom: AppCopyOrigin | null = null, stored?: StoredBytes, reserved?: AppId, + replacing?: { + /** + * Checked under the app's lock when the deploy reserves its order (`activates` true) and + * when it records its version; a failure records nothing. + */ + readonly guard: ( + app: { readonly id: AppId; readonly activeVersion: VersionId | null }, + activates: boolean, + ) => Effect.Effect; + /** A build the compiler or runner did not answer fails with this, not as a failed build. */ + readonly unanswered: (name: string) => U; + }, ) => Effect.gen(function* () { // Reserve an order before building. Only successful promotions advance the other counter. @@ -447,6 +459,7 @@ export const makeApps = ( : yield* transaction(db, (tx) => Effect.gen(function* () { const current = yield* lockApp(tx, { app: input.app, owner: input.owner }); + if (replacing !== undefined) yield* replacing.guard(current, true); const deploySequence = current.deploySequence + 1; yield* query(() => tx.updateMany("apps", { @@ -476,7 +489,14 @@ export const makeApps = ( ? input.files : yield* sources.read({ code, commit: input.commit }); const { files, built, entries, requirements, codeFiles, split, invalidSource } = - yield* buildSource(input.owner, deployName, suppliedFiles); + yield* buildSource( + input.owner, + deployName, + suppliedFiles, + replacing === undefined + ? undefined + : { unanswered: () => replacing.unanswered(deployName) }, + ); // The app's database lives in its data facet, keyed by app ID, so a new app's ID is chosen // before its migrations run. A failed migration fails the deploy before anything activates. const appId = before?.id ?? reserved ?? AppId.make(`app_${yield* crypto.random.uuidV4()}`); @@ -583,6 +603,8 @@ export const makeApps = ( if (existing !== undefined) yield* droppedMigrations(tx, existing.code); const createdAt = new Date(yield* Clock.currentTimeMillis); const promote = existing === undefined || sequence > existing.activatedSequence; + if (replacing !== undefined && existing !== undefined) + yield* replacing.guard(existing, promote); for (const { provider } of entries) { // Apps sharing a provider ID can declare different hosts; the row keeps what they share. const definition = yield* Schema.decodeUnknownEffect(JsonObject)(provider.shared).pipe( @@ -710,8 +732,30 @@ export const makeApps = ( return { ...authoring, deploy: (input: DeployInput) => deploy(input), + // Records nothing unless it activates over the version the caller checked. + deployReplacing: (input: Parameters[0]) => + deploy( + { owner: input.owner, app: input.app, files: input.files }, + null, + undefined, + undefined, + { + guard: (app, activates) => + app.activeVersion === input.expectedVersion && activates + ? Effect.void + : Effect.fail( + new AppVersionChanged({ + app: app.id, + expected: input.expectedVersion, + current: app.activeVersion, + }), + ), + unanswered: (name) => new BuildUnanswered({ owner: input.owner, name }), + }, + ).pipe(Effect.withSpan("sdk.apps.deploy_replacing")), build: (input: Parameters[0]) => buildSource(input.owner, input.name, input.files, { + retain: false, unanswered: () => new BuildUnanswered({ owner: input.owner, name: input.name }), }).pipe( Effect.map(({ requirements }) => ({ requirements })), diff --git a/packages/sdk/src/implementation/create.ts b/packages/sdk/src/implementation/create.ts index b086a673fb..09d4c5f3b1 100644 --- a/packages/sdk/src/implementation/create.ts +++ b/packages/sdk/src/implementation/create.ts @@ -282,6 +282,14 @@ export const createExecutor = ( app.activeVersion === version.id ? activated(app.id) : Effect.void, ), ), + deployReplacing: (input) => + apps + .deployReplacing(input) + .pipe( + Effect.tap(({ app, version }) => + app.activeVersion === version.id ? activated(app.id) : Effect.void, + ), + ), activate: (input) => apps.activate(input).pipe(Effect.tap((app) => activated(app.id))), checkCredentials, }, diff --git a/packages/sdk/src/implementation/remote-app-runner.ts b/packages/sdk/src/implementation/remote-app-runner.ts index 3d16c9fc9d..58942aa37b 100644 --- a/packages/sdk/src/implementation/remote-app-runner.ts +++ b/packages/sdk/src/implementation/remote-app-runner.ts @@ -5,7 +5,7 @@ * return encoded `WorkflowRpcResult`s, and are rebuilt on the runner's side. The invocation names * its build, and the runner's Worker reads it from its own store. */ -import { Cause, Effect, Redacted, Schema } from "effect"; +import { Cause, Data, Effect, Redacted, Schema } from "effect"; import { withRemoteSpan } from "@executor-js/telemetry"; import { HostAccounts, @@ -356,32 +356,45 @@ export const serveAppRunner = ( * that revision: a runner deployed before that check ignores it, and would fill the revision's * cache with whichever document it read. */ +const replyResult = + (hostApi?: string) => + (reply: string): Effect.Effect => + Schema.decodeUnknownEffect(RemoteResult)(reply).pipe( + Effect.catch(() => Effect.fail(new RuntimeProtocolFailed({ reason: "invalid-reply" }))), + Effect.flatMap( + (reply): Effect.Effect => + reply.ok + ? hostApi === undefined || reply.hostApi === hostApi + ? Effect.succeed(reply.value) + : Effect.fail(new RuntimeProtocolFailed({ reason: "unsupported" })) + : reply.unsupported !== undefined + ? Effect.fail(reply.unsupported) + : Effect.fail( + new RuntimeProtocolFailed({ + ...(reply.reason === undefined ? {} : { reason: reply.reason }), + ...(reply.message === undefined ? {} : { message: reply.message }), + }), + ), + ), + ); + +/** The runner's reply, or the failure of a call it rejected; see `replyResult`. */ export const runnerResult = (effect: Effect.Effect, hostApi?: string) => effect.pipe( // A rejected RPC carries the platform's text, such as a size or memory limit, only here. Effect.catch(failedFrom(false, "runner")), - Effect.flatMap((reply) => - Schema.decodeUnknownEffect(RemoteResult)(reply).pipe( - Effect.catch(() => Effect.fail(new RuntimeProtocolFailed({ reason: "invalid-reply" }))), - ), - ), - Effect.flatMap( - (reply): Effect.Effect => - reply.ok - ? hostApi === undefined || reply.hostApi === hostApi - ? Effect.succeed(reply.value) - : Effect.fail(new RuntimeProtocolFailed({ reason: "unsupported" })) - : reply.unsupported !== undefined - ? Effect.fail(reply.unsupported) - : Effect.fail( - new RuntimeProtocolFailed({ - ...(reply.reason === undefined ? {} : { reason: reply.reason }), - ...(reply.message === undefined ? {} : { message: reply.message }), - }), - ), - ), + Effect.flatMap(replyResult(hostApi)), ); +/** + * A call to the runner that failed without a reply, such as a lost connection. The runner answers + * every call it handled, an app's failure included (`runnerReply`), so this says nothing about the + * app: its code may never have run. `failure` is the call's failure as `runnerResult` reports it. + */ +export class RunnerUnanswered extends Data.TaggedError("RunnerUnanswered")<{ + readonly failure: RuntimeProtocolFailed; +}> {} + /** The caller's side: the runner's operations over the runner Worker's service. */ export const remoteAppRunner = (remote: RemoteAppRunner>) => ({ invoke: (invocation: AppInvocation, capabilities: AppCapabilities) => @@ -409,7 +422,18 @@ export const remoteAppRunner = (remote: RemoteAppRunner encodeLoadedBuild(bundle), catch: () => new RuntimeProtocolFailed(), }).pipe( - Effect.flatMap((encoded) => runnerResult(remote.declare(encoded, headers))), + Effect.flatMap((encoded) => + remote.declare(encoded, headers).pipe( + // Told apart here, where the rejection is known to be the call's, never from its text. + Effect.catch((cause) => + failedFrom( + false, + "runner", + )(cause).pipe(Effect.mapError((failure) => new RunnerUnanswered({ failure }))), + ), + Effect.flatMap(replyResult()), + ), + ), Effect.withSpan("runtime.app.remote.declare"), ), }); diff --git a/packages/sdk/src/implementation/worker-source-map.ts b/packages/sdk/src/implementation/worker-source-map.ts index 711a2ec758..e13d0298ae 100644 --- a/packages/sdk/src/implementation/worker-source-map.ts +++ b/packages/sdk/src/implementation/worker-source-map.ts @@ -75,11 +75,13 @@ const stackPosition = /([\w./@-]+):(\d+):(\d+)/g; /** * The declaration failure of a build compiled with `sourceMap`. A Worker that fails while its * modules load reports stack positions in the bundle; each becomes the authored file and position - * it came from, and the first in a deployed source file is the location. + * it came from, and the first in a deployed source file is the location. `unanswered` marks a + * call to the runner that failed without a reply, which judged nothing. */ export const declarationFailed = ( cause: unknown, build: { readonly mainModule: string; readonly sourceMap: string; readonly files: SourceFiles }, + unanswered?: true, ) => { const described = describeBuildCause(cause); let map: TraceMap | undefined; @@ -103,5 +105,6 @@ export const declarationFailed = ( message: boundBuildMessage(message), ...(location === undefined ? {} : { location }), ...(Schema.is(DatabaseFieldReserved)(cause) ? { declaration: cause } : {}), + ...(unanswered === undefined ? {} : { unanswered }), }); }; diff --git a/packages/sdk/src/implementation/workerd-client.ts b/packages/sdk/src/implementation/workerd-client.ts index 2246cce337..793b0a67ea 100644 --- a/packages/sdk/src/implementation/workerd-client.ts +++ b/packages/sdk/src/implementation/workerd-client.ts @@ -1,6 +1,6 @@ /** Portable app protocol. Runtime adapters own processes, sockets and storage bindings. */ import { RpcTarget, type RpcStub } from "capnweb"; -import { Cause, Effect, Redacted, Schema, Stream } from "effect"; +import { Cause, Config, Effect, Option, Redacted, Schema, Stream } from "effect"; import { HttpServerRequest, HttpServerResponse } from "effect/http"; import { DeclaredRequirements, @@ -41,6 +41,20 @@ import { ownsDatabase } from "../contracts/apps.ts"; import type { EvaluatedCommand } from "@executor-js/app-data/evaluated"; import { evaluatedDeclarations } from "./evaluated-declarations.ts"; +/** + * E2E runs only, from `EXECUTOR_TEST_COMPILER_UNAVAILABLE` with `EXECUTOR_ENVIRONMENT=e2e`: calls + * to the compiler fail as a lost connection does, before the apps Worker sees them. `all` fails + * every build; `retained` only the builds a deploy keeps, so a check build still answers. An empty + * value, and any other run, has none. + */ +const compilerOutage = Effect.gen(function* () { + const environment = yield* Config.option(Config.String("EXECUTOR_ENVIRONMENT")); + if (Option.getOrUndefined(environment) !== "e2e") return undefined; + const configured = yield* Config.option(Config.String("EXECUTOR_TEST_COMPILER_UNAVAILABLE")); + return Option.isNone(configured) || configured.value === "" + ? undefined + : yield* Schema.decodeUnknownEffect(Schema.Literals(["all", "retained"]))(configured.value); +}).pipe(Effect.orDie); const engineFailure = () => new WorkflowFailure({ reason: "engine", retryable: true }); const protocolFailure = () => new RuntimeProtocolFailed(); /** @@ -222,6 +236,7 @@ export const connectedWorkerdApps = (blobs: BlobStorage, transport: WorkerdTrans Effect.gen(function* () { const provideBlobs = Effect.provideService(BlobStore, blobs); const rpc = transport.rpc; + const outage = yield* compilerOutage; const runtime = yield* appRuntime({ name: "runtime.workerd", loadBuild: (build) => @@ -264,16 +279,35 @@ export const connectedWorkerdApps = (blobs: BlobStorage, transport: WorkerdTrans ), ); // The compiler is the apps Worker's own code; the deployer sees why its call failed. + // It answers every build it judged, failed ones included, so a call that failed without + // an answer is the host's failure, not the source's. const result = yield* rpc((api, signal) => Effect.tryPromise({ - try: async () => await api.compile(encoded), + try: async () => + outage === "all" || (outage === "retained" && retain) + ? await Promise.reject(new Error("Network connection lost.")) + : await api.compile(encoded), catch: sessionFailure(signal), }), ).pipe( - Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(CompileWorkerResult))), Effect.mapError( (cause) => - new RuntimeBuildFailed({ stage: "compile", message: describeBuildCause(cause) }), + new RuntimeBuildFailed({ + stage: "compile", + message: describeBuildCause(cause), + unanswered: true, + }), + ), + Effect.flatMap((reply) => + Schema.decodeUnknownEffect(Schema.fromJsonString(CompileWorkerResult))(reply).pipe( + Effect.mapError( + (cause) => + new RuntimeBuildFailed({ + stage: "compile", + message: describeBuildCause(cause), + }), + ), + ), ), ); if (!result.ok) return yield* Effect.fail(result.error); diff --git a/packages/sdk/src/workerd.ts b/packages/sdk/src/workerd.ts index 24a2177598..41fe81f1c9 100644 --- a/packages/sdk/src/workerd.ts +++ b/packages/sdk/src/workerd.ts @@ -26,6 +26,7 @@ export { export { appRuntime, buildLoadSpan, type AppRuntimeHost } from "./implementation/app-runtime.ts"; export { remoteAppRunner, + RunnerUnanswered, serveAppRunner, type RemoteAppRunner, type RemoteCapabilities, diff --git a/scripts/catalog-copy-snapshots.commits b/scripts/catalog-copy-snapshots.commits new file mode 100644 index 0000000000..e7cf543e37 --- /dev/null +++ b/scripts/catalog-copy-snapshots.commits @@ -0,0 +1,47 @@ +# Catalog commits (UsefulSoftwareCo/executor-apps) the feed published before the pin moved to +# beta.140: the first-parent history of fea499e1 (2026-10-11 to 2026-10-30), then c97f0dbb and +# 2118206f. Each is reachable from a branch of that repository. Input to +# scripts/catalog-copy-snapshots.ts --commits. +fea499e16cd3888f494066e16b0e5f62a0f102bf +16b02440841139f29251c5109b8b13943328782d +94a80fe5c437047a8389975365470d663fea18f5 +df879ef42a2f2fe61b8044f866d8f7332543e53b +f8e542ba74abf8257ce69fd063580a70a2988b6d +97ba6d9d35f2be2e72434af5078dd4d64282d1a7 +1fefdb4231b25870fe772e5ee55afee7fef2759d +7e0b1c1659d9ad240dbc9b56a96be422a1049fd4 +b7e11657e84822be1a4ce4d2c2da1e940e78002b +8bb9269d7aa9164c9365f8ffd6025b58731f2bb2 +51200db674b2974ea97f643f7093beeba05b9177 +b71c02bae2341086d37dece1a52fc62cbfe1590b +26754c4fa5ad9e09b26ae1797f72207bf3bc74cc +a7022ef6f70ebf3c08136fe8633d3679c0f211e0 +3b8731550db99d86bbd9ec5c812106f09cce6a05 +b1757d517b6ad1a0e1a614520f025c209b911c4b +b7b05d9a1a0253e621fccdd9020acf67edb616a5 +3817dc60889add355b7afea65c6804cc6fc220b8 +f19cb3c3063082516b67eda5719afbe80138ee06 +493e0b7f5ca7f7eabf881ed49d5d1190bdf84704 +f1e00d0646a4932d2b09a147a2e393c1e6b1fe07 +274e09b4d92939597109235c32421112e6c92dd5 +d90189061753a542dd03b03d5bd131457b275931 +842deac82d1121a28fcbd35b4d6fd3d91d6c853d +07bfb38299c0a47e808ed88b962ff53a9179b6db +9d9a483d1f994737b0aad542fd4ae341e4a278d8 +2b2f5461d87e14cdf54eea83d1328b762d87a3e1 +c2ed2329f38a65144f0e3fa1350aa5814267d9a6 +6166c8bd346408403b1a4fe122c16b91f14cfdad +1496148710e1a97f4c4aed2e4ded402cf005e41f +cdfc319876c27c25372d53dc29aaab9ce8504b44 +45e5d12b6fe3f4ad06fcc3f29e68ee22ffc7734f +b6d6e363e88b1e23c6e4100b13df9dbbe66a6ad8 +0dd3748f4b3e20b629dd022517222563309d22a3 +dbc8796b8fd16333977ed7384c770715f119098c +54c835da3d6918eb2bb62f26048a0d36edbb85ee +e7ccab9aecc4c976bd718b507d867d48f2c9d0ce +5422227c6c730de9f7772f89bbb6f9f53d7fd8e7 +3baf8ac093fe70c5c121ea0aec0a6b9b7cc69b82 +ca60da513076f426b21cdd03454b74098ee6f4bf +e08709de8a2242ee2a3b92721097d18ab5465f5e +c97f0dbb +2118206f diff --git a/scripts/catalog-copy-snapshots.ts b/scripts/catalog-copy-snapshots.ts new file mode 100644 index 0000000000..bb3e95245b --- /dev/null +++ b/scripts/catalog-copy-snapshots.ts @@ -0,0 +1,439 @@ +/** + * Generate the reviewed targets of the catalog-copy rebuild (data step + * `13_rebuild_catalog_copies_on_current_apps`) from the catalog repository's history. + * + * bun scripts/catalog-copy-snapshots.ts --catalog \ + * --commits scripts/catalog-copy-snapshots.commits --reviewed 1fefdb42:97ba6d9d \ + * [--stats ] [--dump ] + * + * A catalog install copies the feed's files unchanged: every file of `packages//` except + * `node_modules` and `.DS_Store`, as UTF-8 text (executor-apps `scripts/feed.ts`). Each commit + * listed in `--commits` is one the feed published (the catalog's `main`). For every distinct + * package tree they hold, on a release before the step's target, this applies the step's own + * upgrade (`upgradedFiles`) and lists the result's digest only when every check passes: + * + * 1. The upgrade recognizes the source (`upgradedFiles` is defined). + * 2. Before protocol 13, the official codemod (`scripts/codemods/app-user-accounts.ts`) changes + * exactly the account declaration and the factory's binding, in its own style, and nothing + * else in any script file: the source reads no context's accounts the upgrade would miss. + * 3. Every upgraded script file parses with the TypeScript compiler, and, before protocol 13, the + * compiler confirms each rewritten read: it was the object of a property access, and the upgraded + * `index.ts` names `accounts` only as a property or key (`readsResolve`). + * 4. Before protocol 13, the catalog's own move of the package to beta.100 on its main (`--reviewed`: + * the commits before and after it) changed only `package.json` and `index.ts`, and its + * `index.ts` equals the upgrade's. A package whose move needed anything else (a restructure, a + * provider file) has none of its older trees listed. + * + * The output replaces `packages/app-management/src/implementation/catalog-copy-snapshots.ts`. + * Builds are not run here: the step builds every target before it deploys one and compares its + * requirements with the running version's. + */ +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { Effect } from "effect"; +import ts from "typescript-5"; +import { SourceFiles } from "@executor-js/sdk/core"; +import { + applyEdits, + compareReleases, + scopedIndexEdits, + type ScopedEdit, + declaredRelease, + scopedRequirementsRelease, + sourceDigest, + upgradedFiles, +} from "../packages/app-management/src/implementation/catalog-copy-upgrade.ts"; +import { catalogCopyRebuildTargetRelease } from "../packages/app-management/src/contracts/catalog-copy-rebuild.ts"; + +const root = new URL("..", import.meta.url).pathname; +const output = join(root, "packages/app-management/src/implementation/catalog-copy-snapshots.ts"); + +const argument = (name: string) => { + const index = process.argv.indexOf(`--${name}`); + return index === -1 ? undefined : process.argv[index + 1]; +}; +const catalog = argument("catalog"); +const commitsFile = argument("commits"); +const reviewed = argument("reviewed"); +const statsFile = argument("stats"); +/** A directory to write each file the codemod disagrees on, for a person to read. */ +const dump = argument("dump"); +if (catalog === undefined || commitsFile === undefined || reviewed === undefined) { + console.error( + "Usage: bun scripts/catalog-copy-snapshots.ts --catalog --commits --reviewed : [--stats ]", + ); + process.exit(2); +} +const [reviewedBefore, reviewedAfter] = reviewed.split(":"); +if (reviewedBefore === undefined || reviewedAfter === undefined) process.exit(2); + +const git = (...args: string[]) => { + const result = spawnSync("git", ["-C", catalog, ...args], { + encoding: "utf8", + maxBuffer: 1 << 30, + }); + if (result.status !== 0) throw new Error(`git ${args.join(" ")}: ${result.stderr}`); + return result.stdout; +}; + +/** Read many blobs in one `git cat-file --batch`. */ +const readBlobs = (shas: ReadonlyArray) => { + const result = spawnSync("git", ["-C", catalog, "cat-file", "--batch"], { + input: `${shas.join("\n")}\n`, + maxBuffer: 2 ** 31, + }); + if (result.status !== 0) throw new Error("git cat-file failed"); + const out = result.stdout; + const blobs = new Map(); + let offset = 0; + while (offset < out.length) { + const newline = out.indexOf(10, offset); + const [sha, type, size] = out.subarray(offset, newline).toString("utf8").split(" "); + if (type !== "blob" || sha === undefined || size === undefined) + throw new Error(`unexpected object ${sha} ${type}`); + const start = newline + 1; + blobs.set(sha, out.subarray(start, start + Number(size))); + offset = start + Number(size) + 1; + } + return blobs; +}; + +const decoder = new TextDecoder("utf-8", { fatal: true }); +const ignored = (path: string) => + path.split("/").some((part) => part === "node_modules" || part === ".DS_Store"); + +/** Each distinct package tree of `commits`, by package. */ +const packageTrees = (commits: ReadonlyArray) => { + const trees = new Map(); + for (const commit of commits) + for (const line of git("ls-tree", commit, "packages/").split("\n")) { + const match = /^040000 tree ([0-9a-f]+)\tpackages\/(.+)$/u.exec(line); + if (match !== null) trees.set(match[1]!, match[2]!); + } + return trees; +}; + +/** A tree's files as the feed serves them, or undefined when the feed skips the package. */ +const treeFiles = (tree: string, pkg: string, blobs: Map) => { + const entries = git("ls-tree", "-r", tree) + .split("\n") + .filter((line) => line !== "") + .map((line) => { + const [meta, path] = line.split("\t"); + const [, , sha] = meta!.split(" "); + return { path: path!, sha: sha! }; + }) + .filter((entry) => !ignored(entry.path)) + .toSorted((left, right) => (left.path < right.path ? -1 : 1)); + const missing = entries.filter((entry) => !blobs.has(entry.sha)).map((entry) => entry.sha); + if (missing.length > 0) for (const [sha, bytes] of readBlobs(missing)) blobs.set(sha, bytes); + const files = entries.map((entry) => ({ + path: entry.path, + content: decoder.decode(blobs.get(entry.sha)), + })); + if (!files.some((file) => file.path === "index.ts")) return undefined; + const manifest = files.find((file) => file.path === "package.json"); + if (manifest === undefined) return undefined; + const parsed = JSON.parse(manifest.content) as { + name?: string; + executor?: { title?: string }; + }; + if (parsed.name !== `@executor.sh/${pkg}` || !parsed.executor?.title) return undefined; + return SourceFiles.make(files as [(typeof files)[number], ...typeof files]); +}; + +const scripts = (files: SourceFiles) => + files.filter((file) => /\.(?:[cm]?[jt]sx?)$/u.test(file.path) && "content" in file); + +/** Each `accounts` identifier in `text` by its start, with whether it reads the binding. */ +const accountsIdentifiers = (text: string) => { + const source = ts.createSourceFile( + "index.ts", + text, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TS, + ); + const found: Array<{ readonly start: number; readonly role: "read" | "property" | "other" }> = []; + const visit = (node: ts.Node) => { + if (ts.isIdentifier(node) && node.text === "accounts") { + const parent = node.parent; + const role = + ts.isPropertyAccessExpression(parent) && parent.expression === node + ? ("read" as const) + : (ts.isPropertyAccessExpression(parent) && parent.name === node) || + ((ts.isPropertyAssignment(parent) || + ts.isPropertySignature(parent) || + ts.isMethodDeclaration(parent) || + ts.isPropertyDeclaration(parent)) && + parent.name === node) + ? ("property" as const) + : ("other" as const); + found.push({ start: node.getStart(source), role }); + } + ts.forEachChild(node, visit); + }; + visit(source); + return found; +}; + +/** + * The compiler's view of the upgrade: every `read` edit starts at an `accounts` identifier that + * is the object of a property access, and the upgraded file names `accounts` only as a property + * or key, so no reference to the renamed binding is left. + */ +const readsResolve = (original: string, upgraded: string) => { + const edits = scopedIndexEdits(original); + if (edits === undefined) return false; + const before = new Map(accountsIdentifiers(original).map((entry) => [entry.start, entry.role])); + if (edits.some((edit) => edit.kind === "read" && before.get(edit.start) !== "read")) return false; + return accountsIdentifiers(upgraded).every((entry) => entry.role === "property"); +}; + +const parses = (path: string, text: string) => { + const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS); + return ( + (source as unknown as { parseDiagnostics: ReadonlyArray }).parseDiagnostics.length === + 0 + ); +}; + +/** + * What the codemod writes for the catalog's shape, from the step's own edits: the same + * declaration, except that an empty one is dropped with the comma after it, `user: { accounts }` + * for the factory's binding, and the reads of the requirements left as they are. + */ +const codemodStyle = (original: string) => { + const edits = scopedIndexEdits(original); + if (edits === undefined) return undefined; + const declaration = edits.filter((edit) => edit.kind === "declaration"); + const opened = declaration[0]; + const closed = declaration[1]; + if (opened === undefined || closed === undefined) return undefined; + const value = original.slice(opened.start, closed.start); + const empty = /^accounts\s*:\s*\{\s*\}$/u.test(value); + const styled = edits.flatMap((edit): ScopedEdit[] => { + if (edit.kind === "read") return []; + if (edit.kind === "binding") return [{ ...edit, text: "user: { accounts }" }]; + if (!empty) return [edit]; + if (edit !== opened) return []; + // `{ accounts: {}, icons }` becomes `{ icons }`, `{ icons, accounts: {} }` becomes + // `{ icons }` and `{ accounts: {} }` becomes `{}`. + const after = /^,\s*/u.exec(original.slice(closed.start)); + if (after !== null) return [{ ...edit, end: closed.start + after[0].length, text: "" }]; + const before = /,\s*$/u.exec(original.slice(0, opened.start)); + if (before !== null) return [{ ...edit, start: before.index, end: closed.start, text: "" }]; + const open = /\{\s*$/u.exec(original.slice(0, opened.start)); + const close = /^\s*\}/u.exec(original.slice(closed.start)); + if (open === null || close === null) return [edit]; + return [{ ...edit, start: open.index + 1, end: closed.start + close[0].length - 1, text: "" }]; + }); + return applyEdits(original, styled); +}; + +const commits = readFileSync(commitsFile, "utf8") + .split("\n") + .map((line) => line.trim()) + .filter((line) => line !== "" && !line.startsWith("#")); +const trees = packageTrees(commits); +const blobs = new Map(); +const work = mkdtempSync(join(tmpdir(), "catalog-copy-snapshots-")); + +type Candidate = { + readonly pkg: string; + readonly tree: string; + readonly from: string; + readonly files: SourceFiles; + readonly upgraded: SourceFiles; +}; +const stats = { + commits: commits.length, + trees: trees.size, + feedSkipped: 0, + byRelease: {} as Record, + current: 0, + notRecognized: 0, + codemodDisagrees: 0, + doesNotParse: 0, + /** Upgrades whose reads the TypeScript compiler does not confirm (see `readsResolve`). */ + readsUnresolved: 0, + readsUnresolvedPackages: [] as string[], + listed: 0, + reviewedCompared: 0, + reviewedEqual: 0, + /** Packages whose own move to beta.100 was not exactly the upgrade; their older trees are not listed. */ + reviewedDiffer: [] as string[], + /** Trees before protocol 13 left out because their package's move was not exactly the upgrade. */ + notReviewed: 0, + notRecognizedPackages: [] as string[], + codemodPackages: [] as string[], +}; +const candidates: Candidate[] = []; +for (const [tree, pkg] of trees) { + const files = treeFiles(tree, pkg, blobs); + if (files === undefined) { + stats.feedSkipped++; + continue; + } + const from = declaredRelease(files) ?? "none"; + stats.byRelease[from] = (stats.byRelease[from] ?? 0) + 1; + const order = compareReleases(from, catalogCopyRebuildTargetRelease); + if (order !== undefined && order >= 0) { + stats.current++; + continue; + } + const upgraded = upgradedFiles(files, catalogCopyRebuildTargetRelease); + if (upgraded === undefined) { + stats.notRecognized++; + stats.notRecognizedPackages.push(`${pkg}@${from}`); + continue; + } + candidates.push({ pkg, tree, from, files, upgraded }); +} + +// The codemod reads a directory of every candidate before protocol 13, each in its own folder. +const scoped = candidates.filter( + (candidate) => (compareReleases(candidate.from, scopedRequirementsRelease) ?? 0) < 0, +); +for (const candidate of scoped) + for (const file of scripts(candidate.files)) { + const path = join(work, candidate.tree, file.path); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, "content" in file ? file.content : ""); + } +if (scoped.length > 0) { + const codemod = spawnSync("node", [join(root, "scripts/codemods/app-user-accounts.ts"), work], { + encoding: "utf8", + maxBuffer: 1 << 30, + }); + if (codemod.status !== 0) throw new Error(`codemod failed: ${codemod.stderr}`); +} +const disagrees = new Set(); +for (const candidate of scoped) + for (const file of scripts(candidate.files)) { + if (!("content" in file) || "encoding" in file) continue; + const written = readFileSync(join(work, candidate.tree, file.path), "utf8"); + const upgraded = candidate.upgraded.find((entry) => entry.path === file.path); + const expected = + file.path === "index.ts" && upgraded !== undefined && "content" in upgraded + ? (codemodStyle(file.content) ?? file.content) + : file.content; + if (written !== expected) { + disagrees.add(candidate.tree); + if (dump !== undefined) { + const folder = join(dump, `${candidate.pkg}-${candidate.tree.slice(0, 8)}`); + mkdirSync(folder, { recursive: true }); + writeFileSync(join(folder, `${file.path.replaceAll("/", "_")}.codemod`), written); + writeFileSync(join(folder, `${file.path.replaceAll("/", "_")}.expected`), expected); + } + } + } +rmSync(work, { recursive: true, force: true }); + +// The catalog's own move to beta.100 on its main. A package whose move changed any file but +// `package.json` and `index.ts`, or whose `index.ts` after it differs from the upgrade of the one +// before it, needed more than the upgrade makes: none of its trees before protocol 13 is listed. +const reviewedTrees = packageTrees([reviewedBefore]); +const afterIndex = (pkg: string) => { + const sha = git("ls-tree", reviewedAfter, `packages/${pkg}/index.ts`).split(/\s+/u)[2]; + return sha === undefined || sha === "" ? undefined : decoder.decode(readBlobs([sha]).get(sha)); +}; +const movedMore = new Set( + git("diff", "--name-only", reviewedBefore, reviewedAfter, "--", "packages") + .split("\n") + .filter((path) => path !== "" && !/\/(?:index\.ts|package\.json)$/u.test(path)) + .map((path) => path.split("/")[1] ?? ""), +); +const reviewedPackages = new Set(reviewedTrees.values()); +const movedDifferently = new Set(movedMore); +for (const [tree, pkg] of reviewedTrees) { + const before = treeFiles(tree, pkg, blobs); + const upgraded = + before === undefined ? undefined : upgradedFiles(before, catalogCopyRebuildTargetRelease); + const index = upgraded?.find((file) => file.path === "index.ts"); + const expected = afterIndex(pkg); + stats.reviewedCompared++; + if (index !== undefined && "content" in index && index.content === expected) + stats.reviewedEqual++; + else movedDifferently.add(pkg); +} +stats.reviewedDiffer = [...movedDifferently].toSorted(); + +const targets = new Set(); +for (const candidate of candidates) { + if (disagrees.has(candidate.tree)) { + stats.codemodDisagrees++; + stats.codemodPackages.push(`${candidate.pkg}@${candidate.from}`); + continue; + } + if ( + !scripts(candidate.upgraded).every( + (file) => !("content" in file) || "encoding" in file || parses(file.path, file.content), + ) + ) { + stats.doesNotParse++; + continue; + } + if ((compareReleases(candidate.from, scopedRequirementsRelease) ?? 0) < 0) { + const original = candidate.files.find((file) => file.path === "index.ts"); + const upgraded = candidate.upgraded.find((file) => file.path === "index.ts"); + if ( + original === undefined || + upgraded === undefined || + !("content" in original) || + !("content" in upgraded) || + !readsResolve(original.content, upgraded.content) + ) { + stats.readsUnresolved++; + stats.readsUnresolvedPackages.push(`${candidate.pkg}@${candidate.from}`); + continue; + } + } + if ( + (compareReleases(candidate.from, scopedRequirementsRelease) ?? 0) < 0 && + (movedDifferently.has(candidate.pkg) || !reviewedPackages.has(candidate.pkg)) + ) { + stats.notReviewed++; + continue; + } + targets.add(await Effect.runPromise(sourceDigest(candidate.upgraded))); + stats.listed++; +} + +const sorted = [...targets].toSorted(); +const lines: string[] = []; +for (let index = 0; index < sorted.length; index += 8) + lines.push(sorted.slice(index, index + 8).join(" ")); +writeFileSync( + output, + `/** + * Generated by scripts/catalog-copy-snapshots.ts; do not edit. The reviewed targets of the + * catalog-copy rebuild: the digest (\`sourceDigest\`) of each published catalog package tree before + * ${catalogCopyRebuildTargetRelease}, upgraded by \`upgradedFiles\`. A copy whose upgraded files have + * another digest is not rebuilt. + * + * Catalog commits read: ${stats.commits}. Package trees: ${stats.trees}. Listed: ${stats.listed}, + * as ${sorted.length} distinct targets (trees that differ only in their pin share one). + * Packages whose own move to beta.100 (${reviewedBefore} to ${reviewedAfter}) was exactly the upgrade: + * ${stats.reviewedEqual} of ${stats.reviewedCompared}; the older trees of the other packages are not listed. + */ +const packed = \` +${lines.join("\n")} +\`; + +export const catalogCopyTargets: ReadonlySet = new Set( + packed.split(/\\s+/u).filter((digest) => digest !== ""), +); +`, +); +if (statsFile !== undefined) writeFileSync(statsFile, `${JSON.stringify(stats, null, 2)}\n`); +console.log( + JSON.stringify({ + ...stats, + notRecognizedPackages: undefined, + codemodPackages: undefined, + readsUnresolvedPackages: undefined, + }), +); diff --git a/scripts/e2e-npm-packages.ts b/scripts/e2e-npm-packages.ts index c60c4de63c..b24315341c 100644 --- a/scripts/e2e-npm-packages.ts +++ b/scripts/e2e-npm-packages.ts @@ -53,7 +53,9 @@ const roots: ReadonlyArray = [ dependency("zod", "3.25.76"), // The compiler installs Tailwind at the version the host bundles for `@import "tailwindcss"`. alone("tailwindcss", tailwind.version), - ...[0, 1, 2, 4, 5, 9, 10, 14, 22, 33, 59, 84, 95].map((beta) => + // catalog-copy-rebuild.spec.ts installs catalog sources on beta.88 and beta.100 and rebuilds them + // on beta.140. + ...[0, 1, 2, 4, 5, 9, 10, 14, 22, 33, 59, 84, 88, 95, 100, 140].map((beta) => alone("apps", `0.0.1-beta.${beta}`), ), ]; From 40a7e232d0d4e59c3738739569cda3930ad5ce15 Mon Sep 17 00:00:00 2001 From: Rhys Sullivan <39114868+RhysSullivan@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:22:35 +0000 Subject: [PATCH 05/68] Export 65363558 --- .changeset/oauth-declared-pkce-false.md | 12 + bun.lock | 2 +- e2e/support/oauth-setup-issuer.ts | 35 +- e2e/test-plan.ts | 33 + e2e/tests/oauth-pkce-refused.spec.ts | 463 ++++++++ .../executor/skills/app-authoring/accounts.md | 11 +- .../executor-skill-digests.gen.ts | 2 +- packages/apps/package.json | 2 +- packages/apps/protocols/14.json | 990 +++++++++--------- packages/apps/src/contracts/provider.ts | 23 +- packages/sdk/src/contracts/oauth.ts | 3 +- .../sdk/src/implementation/oauth-protocol.ts | 33 +- 12 files changed, 1098 insertions(+), 511 deletions(-) create mode 100644 .changeset/oauth-declared-pkce-false.md create mode 100644 e2e/tests/oauth-pkce-refused.spec.ts diff --git a/.changeset/oauth-declared-pkce-false.md b/.changeset/oauth-declared-pkce-false.md new file mode 100644 index 0000000000..e7a37db061 --- /dev/null +++ b/.changeset/oauth-declared-pkce-false.md @@ -0,0 +1,12 @@ +--- +"apps": patch +"@executor-js/sdk": patch +"@executor-js/app-templates": patch +--- + +Declared `oauth2()` endpoints accept `pkce: false` for a service whose token endpoint refuses a +confidential client's `code_verifier`. LinkedIn's web flow answers such a request with 401 +`invalid_client`, so every LinkedIn sign-in failed at the code exchange whatever secret was saved. +With the declaration, sign-in sends no `code_challenge` and no `code_verifier`. Only a secret +`tokenEndpointAuthMethod` may declare it; without one the build fails. Every other provider keeps +PKCE S256. diff --git a/bun.lock b/bun.lock index 95028b571b..e2fd12a3f7 100644 --- a/bun.lock +++ b/bun.lock @@ -487,7 +487,7 @@ }, "packages/apps": { "name": "apps", - "version": "0.0.1-beta.141", + "version": "0.0.1-beta.142", "dependencies": { "@cfworker/json-schema": "4.1.1", "@csstools/css-tokenizer": "4.0.2", diff --git a/e2e/support/oauth-setup-issuer.ts b/e2e/support/oauth-setup-issuer.ts index db976e4ae6..6787aa50aa 100644 --- a/e2e/support/oauth-setup-issuer.ts +++ b/e2e/support/oauth-setup-issuer.ts @@ -130,6 +130,8 @@ export const oauthSetupIssuer = Effect.gen(function* () { const tokenContentTypes: Array = []; /** The `scope` parameter of the latest authorization request. */ let authorizationScope: string | null | undefined; + /** Whether the latest authorization request carried a PKCE challenge. */ + let authorizationChallenged: boolean | undefined; /** * The RFC 8707 `resource` parameter of the latest authorization request, code exchange and * refresh; null when it named none. @@ -250,7 +252,7 @@ export const oauthSetupIssuer = Effect.gen(function* () { { clientId: string; redirect: string; - challenge: string; + challenge: string | null; nonce: string | null; scope: string | null; } @@ -299,6 +301,14 @@ export const oauthSetupIssuer = Effect.gen(function* () { * section 2.3.1. "literal" compares them as sent, as Google and PlanetScale (Doorkeeper) do. */ let basicCredentials: "form-decoded" | "literal" = "form-decoded"; + /** + * "required" refuses an authorization request without an S256 challenge. "refused" models + * LinkedIn's web flow: a token request that carries `code_verifier` fails client authentication + * with 401 `invalid_client`, even with the right secret and challenge. + */ + let pkce: "required" | "refused" = "required"; + /** Token requests, as received, whose client authentication was refused. */ + let refusedClientAuthentications = 0; /** Credentials issued by the next registrations; unset issues numbered synthetic clients. */ let registeredClient: { readonly clientId: string; readonly clientSecret: string } | undefined; /** RFC 6749 section 2.3.1 client authentication presented at the token or revocation endpoint. */ @@ -407,13 +417,14 @@ export const oauthSetupIssuer = Effect.gen(function* () { if ( clientId === null || redirect === null || - challenge === null || - params.get("code_challenge_method") !== "S256" || + (pkce === "required" && + (challenge === null || params.get("code_challenge_method") !== "S256")) || !clients.get(clientId)?.redirects.includes(redirect) ) return HttpServerResponse.empty({ status: 400 }); const code = randomUUID(); nonceRequested = params.get("nonce") !== null; + authorizationChallenged = challenge !== null; authorizationScope = params.get("scope"); authorizationResource = params.get("resource"); const requested = authorizationScope?.split(" ") ?? []; @@ -542,10 +553,19 @@ export const oauthSetupIssuer = Effect.gen(function* () { redirect: issued !== undefined && input.get("redirect_uri") === issued.redirect, pkce: issued !== undefined && - verifier !== null && - createHash("sha256").update(verifier).digest("base64url") === issued.challenge, + (pkce === "refused" + ? verifier === null && issued.challenge === null + : verifier !== null && + createHash("sha256").update(verifier).digest("base64url") === issued.challenge), ...authChecks, }; + if (!refreshing && pkce === "refused" && verifier !== null) { + refusedClientAuthentications++; + return yield* HttpServerResponse.json( + { error: "invalid_client", error_description: "Client authentication failed" }, + { status: 401 }, + ); + } if ( clientId === undefined || client === undefined || @@ -1064,6 +1084,8 @@ export const oauthSetupIssuer = Effect.gen(function* () { readonly revocation?: typeof revocation; /** How the token and revocation endpoints read HTTP Basic client credentials. */ readonly basicCredentials?: typeof basicCredentials; + /** Whether sign-in requires PKCE or, like LinkedIn's web flow, refuses it. */ + readonly pkce?: typeof pkce; /** Credentials issued by the next registrations; null restores numbered synthetic clients. */ readonly registeredClient?: typeof registeredClient | null; /** The token request encoding the service accepts; it refuses the other one. */ @@ -1152,6 +1174,7 @@ export const oauthSetupIssuer = Effect.gen(function* () { input.refreshedExpiresIn === null ? undefined : input.refreshedExpiresIn; if (input.revocation !== undefined) revocation = input.revocation; if (input.basicCredentials !== undefined) basicCredentials = input.basicCredentials; + if (input.pkce !== undefined) pkce = input.pkce; if (input.registeredClient !== undefined) registeredClient = input.registeredClient === null ? undefined : input.registeredClient; }), @@ -1223,6 +1246,7 @@ export const oauthSetupIssuer = Effect.gen(function* () { tokenChecks, tokenContentTypes: [...tokenContentTypes], authorizationScope, + authorizationChallenged, authorizationResource, exchangeResource, refreshResource, @@ -1230,6 +1254,7 @@ export const oauthSetupIssuer = Effect.gen(function* () { refreshes, refreshChecks, lastExchangeAuth, + refusedClientAuthentications, nonceRequested, revocations: [...revocations], revocationArrivals, diff --git a/e2e/test-plan.ts b/e2e/test-plan.ts index 9d2067f5b5..28720a77da 100644 --- a/e2e/test-plan.ts +++ b/e2e/test-plan.ts @@ -5690,6 +5690,39 @@ export const scenarios = plan({ local: na("Exercises shared OAuth through the hosted API."), }, }, + oauthPkceRefused: { + fixtures: "actors", + file: "oauth-pkce-refused.spec.ts", + title: + "A service that refuses PKCE from confidential clients signs in and reconnects when its provider declares pkce: false, with secrets of reserved characters unchanged however the client was saved", + targets: { + "self-host": scheduled, + cloud: na("Uses a scoped loopback OAuth issuer."), + local: na("Exercises shared OAuth through the hosted API."), + }, + }, + oauthPkceDefault: { + fixtures: "actors", + file: "oauth-pkce-refused.spec.ts", + title: + "A provider that declares nothing about PKCE signs in and reconnects with an S256 challenge and its verifier", + targets: { + "self-host": scheduled, + cloud: na("Uses a scoped loopback OAuth issuer."), + local: na("Exercises shared OAuth through the hosted API."), + }, + }, + oauthPkceChanged: { + fixtures: "actors", + file: "oauth-pkce-refused.spec.ts", + title: + "Turning PKCE off gives a new provider: an account connected before is refused a reconnect and a sign-in in flight fails when it saves, each telling the person to connect again", + targets: { + "self-host": scheduled, + cloud: na("Uses a scoped loopback OAuth issuer."), + local: na("Exercises shared OAuth through the hosted API."), + }, + }, oauthDeclaredEndpoints: { fixtures: "actors", file: "oauth-declared-endpoints.spec.ts", diff --git a/e2e/tests/oauth-pkce-refused.spec.ts b/e2e/tests/oauth-pkce-refused.spec.ts new file mode 100644 index 0000000000..636c1e2148 --- /dev/null +++ b/e2e/tests/oauth-pkce-refused.spec.ts @@ -0,0 +1,463 @@ +/** + * A service whose token endpoint refuses PKCE from confidential clients, as LinkedIn's web flow + * does: a token request carrying `code_verifier` fails client authentication with 401 + * `invalid_client`, even with the right secret. Its provider declares `pkce: false`, and sign-in + * and reconnect then send neither a challenge nor a verifier. Secrets with reserved characters + * reach the token endpoint unchanged however the client was saved. A provider that declares + * nothing keeps signing in with PKCE S256. Turning PKCE off gives the requirement a new provider: + * accounts connected before cannot reconnect into it, and a sign-in in flight fails when it saves; + * both errors tell the person to connect again. + */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Schema } from "effect"; +import { FetchHttpClient, HttpClient } from "effect/http"; +import { randomUUID } from "node:crypto"; +import { Actors } from "../support/actors.ts"; +import { Api, body } from "../support/api.ts"; +import { appsManifest } from "../support/apps-release.ts"; +import { HostedLive, withHostedCase } from "../support/case.ts"; +import { Resource } from "../support/contracts.ts"; +import { oauthSetupIssuer } from "../support/oauth-setup-issuer.ts"; +import { connectionsPath } from "../support/app-accounts.ts"; +import { scenarios } from "../test-plan.ts"; + +const AppProvider = Schema.Struct({ + id: Schema.String, + requirements: Schema.Struct({ + accounts: Schema.Struct({ service: Schema.Struct({ provider: Schema.String }) }), + }), +}); +const Redirect = Schema.Struct({ + status: Schema.Literal("redirect"), + authorizationUrl: Schema.String, + redirectUri: Schema.String, +}); +const Setup = Schema.Struct({ issuer: Schema.String }); +const Registered = Schema.Struct({ + client: Schema.Struct({ id: Schema.String }), + access: Schema.Struct({ revision: Schema.String }), +}); +const BuildFailed = Schema.Struct({ stage: Schema.String, message: Schema.String }); +const CompletionFailure = Schema.Struct({ _tag: Schema.String, reason: Schema.String }); +/** What the person and an agent read: the error's description and recovery. */ +const Presented = Schema.Struct({ + _tag: Schema.String, + message: Schema.String, + recovery: Schema.Struct({ action: Schema.String }), +}); +const Redeployed = Schema.Struct({ app: AppProvider }); + +/** Synthetic secrets with every character a form or Basic credential encodes. */ +const secrets = { + reserved: "Ab+c/d=e%f&g:h", + encoded: "x%2By%20z", + inner: "inner space", + unicode: "sécrét-✓", + linkedinShaped: "WPL_AP1.syntheticSecret.Ab12==", +}; + +type Method = "client_secret_post" | "client_secret_basic"; +type Credentials = { readonly clientId: string; readonly clientSecret: string }; + +/** Deploy, connect and sign in against the shared loopback issuer. */ +const harness = Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors, + http = yield* HttpClient.HttpClient; + const issuer = yield* oauthSetupIssuer; + const prefix = `/api/organizations/${actors.organization.id}`; + const source = (name: string, config: object) => + `import { defineApp, defineProvider, oauth2, query, object, router } from "apps"; +const service=defineProvider({name:${JSON.stringify(name)},auth:{oauth:oauth2(${JSON.stringify(config)})}}); +export default defineApp({user: { accounts:{service} }},async()=>({tools: router({ + read:query({input:object({})},async()=>({ok:true})), +})}));`; + /** Redeploy an app with a changed provider declaration; returns its new requirement. */ + const redeploy = (app: string, name: string, config: object) => + Effect.gen(function* () { + const response = yield* api.request(actors.owner, "POST", `${prefix}/apps/${app}/deploy`, { + files: [{ path: "index.ts", content: source(name, config) }, appsManifest], + }); + expect(response.status, JSON.stringify(response.body)).toBe(200); + return (yield* body(Redeployed, response)).app; + }); + const deployRequest = (name: string, config: object) => + api.request(actors.owner, "POST", `${prefix}/apps/deploy`, { + name: `${name} ${randomUUID().slice(0, 8)}`, + files: [{ path: "index.ts", content: source(name, config) }, appsManifest], + }); + const deploy = (name: string, config: object) => + Effect.gen(function* () { + const response = yield* deployRequest(name, config); + expect(response.status, JSON.stringify(response.body)).toBe(200); + const app = yield* body(AppProvider, response); + yield* Effect.addFinalizer(() => + api.request(actors.owner, "DELETE", `${prefix}/apps/${app.id}`).pipe(Effect.orDie), + ); + return app; + }); + const endpoints = { + authorizationUrl: `${issuer.origin}/authorize`, + tokenUrl: `${issuer.origin}/token`, + scopes: ["openid", "profile"], + }; + /** A new connection, or with `account` a reconnect of that account. */ + const connectionRequest = (app: string, account?: string) => + api.request( + actors.owner, + "POST", + connectionsPath(`${prefix}/apps/${app}`, "user", "service"), + account === undefined ? {} : { account }, + ); + const connection = (app: string, account?: string) => + connectionRequest(app, account).pipe( + Effect.flatMap((response) => body(Resource, response)), + Effect.map((resource) => resource.id), + ); + const start = (id: string, client: object) => + Effect.gen(function* () { + const response = yield* api.request( + actors.owner, + "POST", + `${prefix}/connections/${id}/oauth/start`, + { method: "oauth", label: `PKCE ${randomUUID().slice(0, 6)}`, client }, + ); + expect(response.status, JSON.stringify(response.body)).toBe(200); + return yield* body(Redirect, response); + }); + const consent = (authorizationUrl: string) => + Effect.scoped( + Effect.gen(function* () { + const response = yield* HttpClient.withScope(http).get(authorizationUrl); + expect(response.status).toBe(302); + const location = response.headers.location; + if (location === undefined) return yield* Effect.die("Issuer did not return a callback"); + return location; + }), + ).pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" })); + const complete = (id: string, callbackUrl: string) => + api.request(actors.owner, "POST", `${prefix}/connections/${id}/oauth/complete`, { + callbackUrl, + }); + /** + * Sign in through one app with a client, as the service registered it; with `account`, reconnect + * that account. Returns what the authorization URL and the issuer saw. + */ + const signIn = ( + app: typeof AppProvider.Type, + credentials: Credentials, + method: Method, + client: object, + account?: string, + ) => + Effect.gen(function* () { + const id = yield* connection(app.id, account); + const started = yield* start(id, client); + yield* issuer.allowClient({ + ...credentials, + redirect: started.redirectUri, + methods: [method], + }); + const query = new URL(started.authorizationUrl).searchParams; + const response = yield* complete(id, yield* consent(started.authorizationUrl)); + const completed = response.status === 200 ? yield* body(Resource, response) : undefined; + if (completed !== undefined && account === undefined) + yield* Effect.addFinalizer(() => + api + .request(actors.owner, "DELETE", `${prefix}/accounts/${completed.id}`) + .pipe(Effect.orDie), + ); + return { + response, + account: completed?.id, + challenge: query.get("code_challenge"), + challengeMethod: query.get("code_challenge_method"), + metrics: yield* issuer.metrics, + }; + }); + return { + api, + actors, + prefix, + issuer, + deploy, + redeploy, + deployRequest, + endpoints, + signIn, + connection, + connectionRequest, + start, + consent, + complete, + }; +}); + +layer(HostedLive, { excludeTestServices: true })("OAuth PKCE refused", (it) => { + it.effect(scenarios.oauthPkceRefused.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { api, actors, prefix, issuer, deploy, deployRequest, endpoints, signIn } = + yield* harness; + yield* issuer.configure({ pkce: "refused" }); + + // Without the declaration, Executor signs in with PKCE, and the service refuses the + // exchange as a client authentication failure although the secret is right. That is what + // people saw: a correct secret, replaced and refused again. + const undeclared = yield* deploy("PKCE sent", { + ...endpoints, + tokenEndpointAuthMethod: "client_secret_post", + }); + const refusedBefore = (yield* issuer.metrics).refusedClientAuthentications; + const undeclaredClient = { + clientId: `undeclared-${randomUUID()}`, + clientSecret: secrets.linkedinShaped, + }; + const refused = yield* signIn( + undeclared, + undeclaredClient, + "client_secret_post", + undeclaredClient, + ); + expect(refused.challenge).not.toBeNull(); + expect(refused.response.status, JSON.stringify(refused.response.body)).toBe(400); + expect(yield* body(CompletionFailure, refused.response)).toMatchObject({ + _tag: "OAuthCompletionFailed", + reason: "invalid_client", + }); + // The issuer counts only token requests that carried a `code_verifier`. + expect(refused.metrics.refusedClientAuthentications).toBe(refusedBefore + 1); + + for (const method of ["client_secret_post", "client_secret_basic"] as const) { + const app = yield* deploy(`PKCE refused ${method}`, { + ...endpoints, + tokenEndpointAuthMethod: method, + pkce: false, + }); + const setup = yield* body( + Setup, + yield* api.request( + actors.owner, + "GET", + `${prefix}/providers/${app.requirements.accounts.service.provider}/oauth/oauth/setup`, + ), + ); + const expectNoPkce = ( + signedIn: Effect.Success>, + label: string, + ) => { + expect( + signedIn.response.status, + `${label}: ${JSON.stringify(signedIn.response.body)} checks=${JSON.stringify(signedIn.metrics.tokenChecks)}`, + ).toBe(200); + expect(signedIn.challenge, label).toBeNull(); + expect(signedIn.challengeMethod, label).toBeNull(); + expect(signedIn.metrics.authorizationChallenged, label).toBe(false); + expect(signedIn.metrics.lastExchangeAuth, label).toBe(method); + // In "refused" mode `pkce` holds only when the token request carried no verifier. + expect(signedIn.metrics.tokenChecks, label).toMatchObject({ + pkce: true, + authClient: true, + authSecret: true, + }); + }; + let last: { credentials: Credentials; client: object; account: string } | undefined; + for (const [name, clientSecret] of Object.entries(secrets)) + for (const saved of ["entered", "registered", "updated"] as const) { + // Client IDs carry the characters Basic credentials must encode too. + const credentials = { + clientId: `${saved}-${name}-${randomUUID().slice(0, 8)}:a+b`, + clientSecret, + }; + let client: object = credentials; + if (saved !== "entered") { + const registered = yield* body( + Registered, + yield* api.request(actors.owner, "POST", `${prefix}/oauth-clients`, { + issuer: setup.issuer, + clientId: credentials.clientId, + clientSecret: saved === "updated" ? "synthetic-replaced-secret" : clientSecret, + }), + ); + yield* Effect.addFinalizer(() => + api + .request( + actors.owner, + "DELETE", + `${prefix}/oauth-clients/${registered.client.id}`, + ) + .pipe(Effect.orDie), + ); + if (saved === "updated") { + const updated = yield* api.request( + actors.owner, + "PATCH", + `${prefix}/oauth-clients/${registered.client.id}`, + { clientSecret, revision: registered.access.revision }, + ); + expect(updated.status, JSON.stringify(updated.body)).toBe(200); + } + client = { id: registered.client.id }; + } + const signedIn = yield* signIn(app, credentials, method, client); + expectNoPkce(signedIn, `${method} ${saved} ${name}`); + if (signedIn.account !== undefined) + last = { credentials, client, account: signedIn.account }; + } + // Reconnecting an account signs in again the same way, without PKCE. + if (last === undefined) return yield* Effect.die("No account signed in"); + const reconnected = yield* signIn( + app, + last.credentials, + method, + last.client, + last.account, + ); + expectNoPkce(reconnected, `${method} reconnect`); + expect(reconnected.account).toBe(last.account); + } + // `pkce: false` needs a secret: without one, nothing but the code would bind it. + for (const tokenEndpointAuthMethod of [undefined, "none"]) { + const publicClient = yield* deployRequest("PKCE refused public", { + ...endpoints, + ...(tokenEndpointAuthMethod === undefined ? {} : { tokenEndpointAuthMethod }), + pkce: false, + }); + expect(publicClient.status, JSON.stringify(publicClient.body)).toBe(422); + const failure = yield* body(BuildFailed, publicClient); + expect(failure.stage).toBe("declaration"); + expect(failure.message).toContain( + "DeclarationInvalid: The oauth2() declaration is invalid. pkce: pkce: false requires tokenEndpointAuthMethod client_secret_post, client_secret_basic or client_secret_basic_raw.", + ); + } + + // Only the undeclared provider's exchange carried a verifier. + expect((yield* issuer.metrics).refusedClientAuthentications).toBe(refusedBefore + 1); + }), + ), + ); + + it.effect(scenarios.oauthPkceDefault.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { issuer, deploy, endpoints, signIn } = yield* harness; + // The issuer's default requires an S256 challenge and checks the verifier against it. + yield* issuer.configure({ pkce: "required" }); + const app = yield* deploy("PKCE default", { + ...endpoints, + tokenEndpointAuthMethod: "client_secret_post", + }); + const credentials = { + clientId: `default-${randomUUID()}`, + clientSecret: secrets.linkedinShaped, + }; + const expectPkce = (signedIn: Effect.Success>, label: string) => { + expect( + signedIn.response.status, + `${label}: ${JSON.stringify(signedIn.response.body)} checks=${JSON.stringify(signedIn.metrics.tokenChecks)}`, + ).toBe(200); + expect(signedIn.challenge, label).toMatch(/^[\w-]{43}$/); + expect(signedIn.challengeMethod, label).toBe("S256"); + expect(signedIn.metrics.authorizationChallenged, label).toBe(true); + // In "required" mode `pkce` holds only when the verifier hashes to the challenge. + expect(signedIn.metrics.tokenChecks, label).toMatchObject({ pkce: true }); + }; + const signedIn = yield* signIn(app, credentials, "client_secret_post", credentials); + expectPkce(signedIn, "sign-in"); + if (signedIn.account === undefined) return yield* Effect.die("No account signed in"); + const reconnected = yield* signIn( + app, + credentials, + "client_secret_post", + credentials, + signedIn.account, + ); + expectPkce(reconnected, "reconnect"); + expect(reconnected.account).toBe(signedIn.account); + }), + ), + ); + it.effect(scenarios.oauthPkceChanged.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { + api, + actors, + prefix, + issuer, + deploy, + redeploy, + endpoints, + signIn, + connection, + connectionRequest, + start, + consent, + complete, + } = yield* harness; + yield* issuer.configure({ pkce: "required" }); + const declared = { ...endpoints, tokenEndpointAuthMethod: "client_secret_post" }; + const app = yield* deploy("PKCE changed", declared); + const credentials = { + clientId: `changed-${randomUUID()}`, + clientSecret: secrets.linkedinShaped, + }; + const signedIn = yield* signIn(app, credentials, "client_secret_post", credentials); + expect(signedIn.response.status, JSON.stringify(signedIn.response.body)).toBe(200); + expect(signedIn.challenge).not.toBeNull(); + if (signedIn.account === undefined) return yield* Effect.die("No account signed in"); + + // A second sign-in reaches the service's consent before the app changes. + const pending = yield* connection(app.id); + const started = yield* start(pending, credentials); + expect(new URL(started.authorizationUrl).searchParams.get("code_challenge")).not.toBeNull(); + const callbackUrl = yield* consent(started.authorizationUrl); + + // The app turns PKCE off, which is part of the provider's identity. + const changed = yield* redeploy(app.id, "PKCE changed", { ...declared, pkce: false }); + expect(changed.requirements.accounts.service.provider).not.toBe( + app.requirements.accounts.service.provider, + ); + + // The sign-in in flight exchanges its code as it started, then cannot save against the + // changed requirement, and tells the person to start again. + const completed = yield* complete(pending, callbackUrl); + expect(completed.status, JSON.stringify(completed.body)).toBe(409); + expect(yield* body(Presented, completed)).toEqual({ + _tag: "AccountConnectionTargetChanged", + message: "This connection no longer matches the app’s requirements.", + recovery: { action: "Close this form and start account setup again." }, + }); + + // The account connected before cannot be reconnected into the changed provider; the + // error says to connect a new account. + const reconnect = yield* connectionRequest(app.id, signedIn.account); + expect(reconnect.status, JSON.stringify(reconnect.body)).toBe(422); + expect(yield* body(CompletionFailure, reconnect)).toMatchObject({ + _tag: "AccountSelectionInvalid", + reason: "provider_mismatch", + }); + expect((yield* body(Presented, reconnect)).recovery.action).toBe( + "Open Accounts and connect a new account for this requirement.", + ); + // It is kept, with the credentials it had. + const kept = yield* api.request( + actors.owner, + "GET", + `${prefix}/accounts/${signedIn.account}`, + ); + expect(kept.status, JSON.stringify(kept.body)).toBe(200); + + // A new connection signs in to the changed provider without PKCE. + yield* issuer.configure({ pkce: "refused" }); + const fresh = yield* signIn(changed, credentials, "client_secret_post", credentials); + expect(fresh.response.status, JSON.stringify(fresh.response.body)).toBe(200); + expect(fresh.challenge).toBeNull(); + expect(fresh.account).not.toBe(signedIn.account); + }), + ), + ); +}); diff --git a/packages/app-templates/executor/skills/app-authoring/accounts.md b/packages/app-templates/executor/skills/app-authoring/accounts.md index e35fb44bcb..77724a175b 100644 --- a/packages/app-templates/executor/skills/app-authoring/accounts.md +++ b/packages/app-templates/executor/skills/app-authoring/accounts.md @@ -517,6 +517,10 @@ in app code: of the token response when the top level has no access token or scope. Slack returns user tokens there. Comma-separated scopes in that member become space-separated. +- `pkce: false` signs in without PKCE, for declared endpoints whose token + endpoint refuses a confidential client's `code_verifier`. LinkedIn answers + `invalid_client` to it, which looks like a wrong secret. It requires a secret + `tokenEndpointAuthMethod`. ```ts oauth2({ @@ -529,8 +533,11 @@ oauth2({ }); ``` -A connected account keeps the settings it signed in with; reconnect it after -changing them. +A connected account keeps the settings it signed in with. These settings, +`pkce` included, are part of the provider ID, so changing one after users +connect gives a new provider: accounts connected before can't be reconnected +into it, and users must connect a new account. A sign-in in progress when the +app is redeployed fails when it saves, and the user starts it again. When the service documents an RFC 7009 token revocation endpoint, also declare `revocationUrl`. Executor calls it when a user deletes the account, so the diff --git a/packages/app-templates/src/implementation/executor-skill-digests.gen.ts b/packages/app-templates/src/implementation/executor-skill-digests.gen.ts index 146e20b6d0..9521a3c880 100644 --- a/packages/app-templates/src/implementation/executor-skill-digests.gen.ts +++ b/packages/app-templates/src/implementation/executor-skill-digests.gen.ts @@ -3,7 +3,7 @@ /** SHA-256 of each file the Executor app publishes as a skill, keyed by `/`. */ export const executorSkillDigests: Readonly> = { "app-authoring/SKILL.md": "09694ffe3aa62cbaec0ea9fead118392107440267dd3b6f4676595e45e1eba6e", - "app-authoring/accounts.md": "d2b361588f445bec226a97a0647f6f69ff443da8c60de9d7de0d9b4578cef475", + "app-authoring/accounts.md": "3d29ca0463e894356626561df11da1ddccd328b04ac4ee65603e1327dfa15f2a", "app-authoring/deploy.md": "11d69a371903f8ba051ee6b844a890604c5d90c12a69340b4b5feb62d2c2e3f4", "app-authoring/events.md": "421c322f147a6da7a0bdc5513367e25b96667cf34f74b71918c84fdbe91727d1", "app-authoring/integrations.md": "1788ddee892c69a9d895a2d8c7bec63f1d41963ed5b00ed3e6f0b5c4a671d867", diff --git a/packages/apps/package.json b/packages/apps/package.json index ea2c0e4b29..6224763dc5 100644 --- a/packages/apps/package.json +++ b/packages/apps/package.json @@ -1,6 +1,6 @@ { "name": "apps", - "version": "0.0.1-beta.141", + "version": "0.0.1-beta.142", "private": true, "description": "TypeScript apps with typed tools, accounts, storage, and UI.", "type": "module", diff --git a/packages/apps/protocols/14.json b/packages/apps/protocols/14.json index 82ae6e15e3..47937b260c 100644 --- a/packages/apps/protocols/14.json +++ b/packages/apps/protocols/14.json @@ -412,14 +412,14 @@ { "name": "app", "type": { - "$shared": "6a7c54b880211a59" + "$shared": "fa10a18585e99273" }, "isOptional": false }, { "name": "user", "type": { - "$shared": "6a7c54b880211a59" + "$shared": "fa10a18585e99273" }, "isOptional": false } @@ -650,14 +650,14 @@ { "name": "app", "type": { - "$shared": "5b3ec400ec8d4e6b" + "$shared": "2c3d9239495bdaed" }, "isOptional": false }, { "name": "user", "type": { - "$shared": "5b3ec400ec8d4e6b" + "$shared": "2c3d9239495bdaed" }, "isOptional": true } @@ -683,46 +683,6 @@ ], "references": {}, "shared": { - "04391ff3503b0509": { - "name": "provider", - "type": { - "$shared": "a404e4e6d6c1b68e" - }, - "isOptional": false - }, - "1aeb6460b73a0de1": { - "_tag": "Objects", - "propertySignatures": [ - { - "$shared": "886147c8b4038b62" - }, - { - "name": "cardinality", - "type": { - "_tag": "Union", - "types": [ - { - "_tag": "Literal", - "literal": "one" - }, - { - "_tag": "Literal", - "literal": "many" - } - ] - }, - "isOptional": false - }, - { - "name": "health", - "type": { - "_tag": "Literal", - "literal": true - }, - "isOptional": true - } - ] - }, "24303971fc45ad9c": { "_tag": "Objects", "propertySignatures": [ @@ -1013,14 +973,12 @@ } ] }, - "35750fcf0fdbdf55": { - "_tag": "Union", - "types": [ - { - "$shared": "62074447437351d3" - }, + "2c3d9239495bdaed": { + "_tag": "Objects", + "propertySignatures": [], + "indexSignatures": [ { - "$shared": "85338c9d2dc7c3b0" + "$shared": "d57482dfc9bd7bc2" } ] }, @@ -1170,91 +1128,20 @@ } ] }, - "4ded759dcdba2403": { - "_tag": "Arrays", - "rest": [ - { - "$shared": "3634cfd2d0b776b7" - } - ] - }, - "5b3ec400ec8d4e6b": { - "_tag": "Objects", - "propertySignatures": [], - "indexSignatures": [ - { - "$shared": "61625abfe10d1ccf" - } - ] - }, - "5d5ace296568a88a": { - "parameter": { - "_tag": "String", - "checks": [ - { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isMinLength", - "payload": { - "minLength": 1 - } - } - } - ] - }, - "type": { - "$shared": "1aeb6460b73a0de1" - } - }, - "5e57cc565536ebba": { - "name": "auth", - "type": { - "$shared": "8a2d57e2fc31e064" - }, - "isOptional": false - }, - "61625abfe10d1ccf": { - "parameter": { - "_tag": "String", - "checks": [ - { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isMinLength", - "payload": { - "minLength": 1 - } - } - } - ] - }, - "type": { - "$shared": "35750fcf0fdbdf55" - } - }, - "62074447437351d3": { + "4dabb4c5075f39ee": { "_tag": "Objects", "propertySignatures": [ { - "name": "id", + "name": "name", "type": { "_tag": "String", "checks": [ - { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isStartingWith", - "payload": { - "startsWith": "acc_" - } - } - }, { "_tag": "Filter", "representation": { "id": "effect/schema/isMinLength", "payload": { - "minLength": 5 + "minLength": 1 } } } @@ -1263,72 +1150,86 @@ "isOptional": false }, { - "$shared": "04391ff3503b0509" + "$shared": "e755f69e762ed5d5" }, { - "name": "method", + "name": "hosts", "type": { - "_tag": "String", - "checks": [ + "_tag": "Arrays", + "rest": [ { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isMinLength", - "payload": { - "minLength": 1 + "_tag": "Union", + "types": [ + { + "_tag": "String", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isPattern", + "payload": { + "source": "^(\\*\\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*(?::[0-9]{1,5})?$", + "flags": "" + } + } + } + ] + }, + { + "_tag": "String", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isPattern", + "payload": { + "source": "^(\\*\\.)?[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?(?:\\.[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?)*(?::[0-9]{1,5})?$", + "flags": "" + } + } + } + ] } - } - } - ] - }, - "isOptional": false - }, - { - "name": "generation", - "type": { - "_tag": "Number", - "checks": [ - { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isInt", - "payload": null - } + ] } ] }, "isOptional": true - }, + } + ] + }, + "4ded759dcdba2403": { + "_tag": "Arrays", + "rest": [ { - "name": "fields", - "type": { - "_tag": "Objects", - "propertySignatures": [], - "indexSignatures": [ - { - "parameter": { - "_tag": "String" - }, - "type": { - "_tag": "Declaration", - "representation": { - "id": "effect/schema/Json", - "payload": null - } - } - } - ] - }, - "isOptional": false + "$shared": "3634cfd2d0b776b7" } ] }, - "6a7c54b880211a59": { - "_tag": "Objects", - "propertySignatures": [], - "indexSignatures": [ + "4e7495d26fdf46fa": { + "parameter": { + "_tag": "String", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isMinLength", + "payload": { + "minLength": 1 + } + } + } + ] + }, + "type": { + "$shared": "f032123577c19525" + } + }, + "59be27bc36aa674c": { + "_tag": "Arrays", + "rest": [ { - "$shared": "5d5ace296568a88a" + "$shared": "d977ddb8aed7458d" } ] }, @@ -1710,74 +1611,30 @@ }, "isOptional": true }, - "830e6aa3f78d2c88": { - "parameter": { - "_tag": "String", - "checks": [ - { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isMinLength", - "payload": { - "minLength": 1 - } - } - } - ] - }, - "type": { - "$shared": "9604aa9855f3cd16" - } - }, - "85338c9d2dc7c3b0": { - "_tag": "Arrays", - "rest": [ + "835dd8be1d88f376": { + "_tag": "Union", + "types": [ + { + "$shared": "d977ddb8aed7458d" + }, { - "$shared": "62074447437351d3" + "$shared": "59be27bc36aa674c" } ] }, - "886147c8b4038b62": { - "name": "definition", - "type": { - "$shared": "a404e4e6d6c1b68e" - }, - "isOptional": false - }, - "8a2d57e2fc31e064": { + "a2cfd530d9a633b5": { "_tag": "Objects", - "propertySignatures": [], - "indexSignatures": [ + "propertySignatures": [ { - "$shared": "830e6aa3f78d2c88" - } - ] - }, - "9604aa9855f3cd16": { - "_tag": "Union", - "types": [ - { - "$shared": "e8644c38bd7a5d31" - }, - { - "$shared": "24303971fc45ad9c" - }, - { - "$shared": "cbda9dac6e6f3a24" - }, - { - "$shared": "bdb650b73e07a5e1" + "name": "type", + "type": { + "_tag": "Literal", + "literal": "oauth2" + }, + "isOptional": false }, { - "$shared": "7ed8e66c05334e80" - } - ] - }, - "a404e4e6d6c1b68e": { - "_tag": "Objects", - "propertySignatures": [ - { - "name": "name", + "name": "scopeSeparator", "type": { "_tag": "String", "checks": [ @@ -1792,95 +1649,127 @@ } ] }, - "isOptional": false + "isOptional": true }, { - "$shared": "5e57cc565536ebba" + "name": "tokenRequestFormat", + "type": { + "_tag": "Union", + "types": [ + { + "_tag": "Literal", + "literal": "form" + }, + { + "_tag": "Literal", + "literal": "json" + } + ] + }, + "isOptional": true }, { - "name": "hosts", + "name": "tokenResponse", "type": { - "_tag": "Arrays", - "rest": [ + "_tag": "Objects", + "propertySignatures": [ { - "_tag": "Union", - "types": [ - { - "_tag": "String", - "checks": [ - { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isPattern", - "payload": { - "source": "^(\\*\\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*(?::[0-9]{1,5})?$", - "flags": "" - } - } - } - ] - }, - { - "_tag": "String", - "checks": [ - { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isPattern", - "payload": { - "source": "^(\\*\\.)?[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?(?:\\.[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?)*(?::[0-9]{1,5})?$", - "flags": "" - } + "name": "path", + "type": { + "_tag": "String", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isPattern", + "payload": { + "source": "^[^.]+(\\.[^.]+)*$", + "flags": "" } } - ] - } - ] + } + ] + }, + "isOptional": false } ] }, "isOptional": true - } - ] - }, - "bdb650b73e07a5e1": { - "_tag": "Objects", - "propertySignatures": [ + }, { - "name": "type", + "name": "grant", "type": { "_tag": "Literal", - "literal": "oauth2" + "literal": "authorization_code" }, - "isOptional": false + "isOptional": true }, { - "name": "grant", + "name": "authorizationParams", "type": { - "_tag": "Literal", - "literal": "client_credentials" + "_tag": "Objects", + "propertySignatures": [], + "indexSignatures": [ + { + "parameter": { + "_tag": "String" + }, + "type": { + "_tag": "String" + } + } + ], + "checks": [ + { + "_tag": "Filter", + "annotations": { + "message": "Authorization parameters cannot replace protocol parameters such as state or scope." + } + } + ] }, - "isOptional": false + "isOptional": true }, { - "name": "discover", + "name": "tokenEndpointAuthMethod", "type": { - "_tag": "String", - "checks": [ + "_tag": "Union", + "types": [ { - "_tag": "Filter" + "_tag": "Literal", + "literal": "none" + }, + { + "_tag": "Literal", + "literal": "client_secret_post" + }, + { + "_tag": "Literal", + "literal": "client_secret_basic" + }, + { + "_tag": "Literal", + "literal": "client_secret_basic_raw" } ] }, - "isOptional": false + "isOptional": true }, { - "name": "authorizationServerMetadataUrl", + "name": "resource", "type": { - "_tag": "String", - "checks": [ + "_tag": "Union", + "types": [ { - "_tag": "Filter" + "_tag": "String", + "checks": [ + { + "_tag": "Filter" + } + ] + }, + { + "_tag": "Null" } ] }, @@ -1889,21 +1778,36 @@ { "name": "authorizationUrl", "type": { - "_tag": "Never" + "_tag": "String", + "checks": [ + { + "_tag": "Filter" + } + ] }, - "isOptional": true + "isOptional": false }, { "name": "tokenUrl", "type": { - "_tag": "Never" + "_tag": "String", + "checks": [ + { + "_tag": "Filter" + } + ] }, - "isOptional": true + "isOptional": false }, { "name": "revocationUrl", "type": { - "_tag": "Never" + "_tag": "String", + "checks": [ + { + "_tag": "Filter" + } + ] }, "isOptional": true }, @@ -1917,81 +1821,39 @@ } ] }, - "isOptional": true + "isOptional": false }, { - "name": "scopeSeparator", + "name": "issuer", "type": { "_tag": "String", "checks": [ { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isMinLength", - "payload": { - "minLength": 1 - } - } + "_tag": "Filter" } ] }, "isOptional": true }, { - "name": "tokenRequestFormat", + "name": "pkce", "type": { - "_tag": "Union", - "types": [ - { - "_tag": "Literal", - "literal": "form" - }, - { - "_tag": "Literal", - "literal": "json" - } - ] + "_tag": "Literal", + "literal": false }, "isOptional": true }, { - "name": "tokenEndpointAuthMethod", + "name": "discover", "type": { - "_tag": "Union", - "types": [ - { - "_tag": "Literal", - "literal": "client_secret_post" - }, - { - "_tag": "Literal", - "literal": "client_secret_basic" - }, - { - "_tag": "Literal", - "literal": "client_secret_basic_raw" - } - ] + "_tag": "Never" }, - "isOptional": false + "isOptional": true }, { - "name": "resource", + "name": "authorizationServerMetadataUrl", "type": { - "_tag": "Union", - "types": [ - { - "_tag": "String", - "checks": [ - { - "_tag": "Filter" - } - ] - }, - { - "_tag": "Null" - } - ] + "_tag": "Never" }, "isOptional": true }, @@ -2075,7 +1937,40 @@ } ] }, - "cbda9dac6e6f3a24": { + "b10d246bc4dc9b25": { + "_tag": "Objects", + "propertySignatures": [ + { + "$shared": "e4c9fad4e3fe588b" + }, + { + "name": "cardinality", + "type": { + "_tag": "Union", + "types": [ + { + "_tag": "Literal", + "literal": "one" + }, + { + "_tag": "Literal", + "literal": "many" + } + ] + }, + "isOptional": false + }, + { + "name": "health", + "type": { + "_tag": "Literal", + "literal": true + }, + "isOptional": true + } + ] + }, + "bdb650b73e07a5e1": { "_tag": "Objects", "propertySignatures": [ { @@ -2087,97 +1982,100 @@ "isOptional": false }, { - "name": "scopeSeparator", + "name": "grant", + "type": { + "_tag": "Literal", + "literal": "client_credentials" + }, + "isOptional": false + }, + { + "name": "discover", "type": { "_tag": "String", "checks": [ { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isMinLength", - "payload": { - "minLength": 1 - } - } + "_tag": "Filter" } ] }, - "isOptional": true + "isOptional": false }, { - "name": "tokenRequestFormat", + "name": "authorizationServerMetadataUrl", "type": { - "_tag": "Union", - "types": [ - { - "_tag": "Literal", - "literal": "form" - }, + "_tag": "String", + "checks": [ { - "_tag": "Literal", - "literal": "json" + "_tag": "Filter" } ] }, "isOptional": true }, { - "name": "tokenResponse", + "name": "authorizationUrl", "type": { - "_tag": "Objects", - "propertySignatures": [ + "_tag": "Never" + }, + "isOptional": true + }, + { + "name": "tokenUrl", + "type": { + "_tag": "Never" + }, + "isOptional": true + }, + { + "name": "revocationUrl", + "type": { + "_tag": "Never" + }, + "isOptional": true + }, + { + "name": "scopes", + "type": { + "_tag": "Arrays", + "rest": [ { - "name": "path", - "type": { - "_tag": "String", - "checks": [ - { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isPattern", - "payload": { - "source": "^[^.]+(\\.[^.]+)*$", - "flags": "" - } - } - } - ] - }, - "isOptional": false + "_tag": "String" } ] }, "isOptional": true }, { - "name": "grant", + "name": "scopeSeparator", "type": { - "_tag": "Literal", - "literal": "authorization_code" + "_tag": "String", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isMinLength", + "payload": { + "minLength": 1 + } + } + } + ] }, "isOptional": true }, { - "name": "authorizationParams", + "name": "tokenRequestFormat", "type": { - "_tag": "Objects", - "propertySignatures": [], - "indexSignatures": [ + "_tag": "Union", + "types": [ { - "parameter": { - "_tag": "String" - }, - "type": { - "_tag": "String" - } - } - ], - "checks": [ + "_tag": "Literal", + "literal": "form" + }, { - "_tag": "Filter", - "annotations": { - "message": "Authorization parameters cannot replace protocol parameters such as state or scope." - } + "_tag": "Literal", + "literal": "json" } ] }, @@ -2188,10 +2086,6 @@ "type": { "_tag": "Union", "types": [ - { - "_tag": "Literal", - "literal": "none" - }, { "_tag": "Literal", "literal": "client_secret_post" @@ -2206,7 +2100,7 @@ } ] }, - "isOptional": true + "isOptional": false }, { "name": "resource", @@ -2228,80 +2122,6 @@ }, "isOptional": true }, - { - "name": "authorizationUrl", - "type": { - "_tag": "String", - "checks": [ - { - "_tag": "Filter" - } - ] - }, - "isOptional": false - }, - { - "name": "tokenUrl", - "type": { - "_tag": "String", - "checks": [ - { - "_tag": "Filter" - } - ] - }, - "isOptional": false - }, - { - "name": "revocationUrl", - "type": { - "_tag": "String", - "checks": [ - { - "_tag": "Filter" - } - ] - }, - "isOptional": true - }, - { - "name": "scopes", - "type": { - "_tag": "Arrays", - "rest": [ - { - "_tag": "String" - } - ] - }, - "isOptional": false - }, - { - "name": "issuer", - "type": { - "_tag": "String", - "checks": [ - { - "_tag": "Filter" - } - ] - }, - "isOptional": true - }, - { - "name": "discover", - "type": { - "_tag": "Never" - }, - "isOptional": true - }, - { - "name": "authorizationServerMetadataUrl", - "type": { - "_tag": "Never" - }, - "isOptional": true - }, { "name": "clientGuide", "type": { @@ -2382,6 +2202,165 @@ } ] }, + "c6afd70b53c5f872": { + "name": "provider", + "type": { + "$shared": "4dabb4c5075f39ee" + }, + "isOptional": false + }, + "d57482dfc9bd7bc2": { + "parameter": { + "_tag": "String", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isMinLength", + "payload": { + "minLength": 1 + } + } + } + ] + }, + "type": { + "$shared": "835dd8be1d88f376" + } + }, + "d9139edb619b7be9": { + "_tag": "Objects", + "propertySignatures": [], + "indexSignatures": [ + { + "$shared": "4e7495d26fdf46fa" + } + ] + }, + "d977ddb8aed7458d": { + "_tag": "Objects", + "propertySignatures": [ + { + "name": "id", + "type": { + "_tag": "String", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isStartingWith", + "payload": { + "startsWith": "acc_" + } + } + }, + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isMinLength", + "payload": { + "minLength": 5 + } + } + } + ] + }, + "isOptional": false + }, + { + "$shared": "c6afd70b53c5f872" + }, + { + "name": "method", + "type": { + "_tag": "String", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isMinLength", + "payload": { + "minLength": 1 + } + } + } + ] + }, + "isOptional": false + }, + { + "name": "generation", + "type": { + "_tag": "Number", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isInt", + "payload": null + } + } + ] + }, + "isOptional": true + }, + { + "name": "fields", + "type": { + "_tag": "Objects", + "propertySignatures": [], + "indexSignatures": [ + { + "parameter": { + "_tag": "String" + }, + "type": { + "_tag": "Declaration", + "representation": { + "id": "effect/schema/Json", + "payload": null + } + } + } + ] + }, + "isOptional": false + } + ] + }, + "dfe4b13c46818e91": { + "parameter": { + "_tag": "String", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isMinLength", + "payload": { + "minLength": 1 + } + } + } + ] + }, + "type": { + "$shared": "b10d246bc4dc9b25" + } + }, + "e4c9fad4e3fe588b": { + "name": "definition", + "type": { + "$shared": "4dabb4c5075f39ee" + }, + "isOptional": false + }, + "e755f69e762ed5d5": { + "name": "auth", + "type": { + "$shared": "d9139edb619b7be9" + }, + "isOptional": false + }, "e8644c38bd7a5d31": { "_tag": "Objects", "propertySignatures": [ @@ -2479,6 +2458,35 @@ "$shared": "7fa3e0fa96a362fd" } ] + }, + "f032123577c19525": { + "_tag": "Union", + "types": [ + { + "$shared": "e8644c38bd7a5d31" + }, + { + "$shared": "24303971fc45ad9c" + }, + { + "$shared": "a2cfd530d9a633b5" + }, + { + "$shared": "bdb650b73e07a5e1" + }, + { + "$shared": "7ed8e66c05334e80" + } + ] + }, + "fa10a18585e99273": { + "_tag": "Objects", + "propertySignatures": [], + "indexSignatures": [ + { + "$shared": "dfe4b13c46818e91" + } + ] } } } diff --git a/packages/apps/src/contracts/provider.ts b/packages/apps/src/contracts/provider.ts index cd775c8ab1..18a244f51f 100644 --- a/packages/apps/src/contracts/provider.ts +++ b/packages/apps/src/contracts/provider.ts @@ -93,6 +93,22 @@ const declaredAuthorizationQuery = Schema.makeFilter( }, ); +/** + * Signing in without PKCE leaves the code bound to the client by its secret alone, so only a + * method that requires a secret may declare it. + */ +const declaredPkce = Schema.makeFilter( + (config: { readonly pkce?: false; readonly tokenEndpointAuthMethod?: OAuthClientAuth }) => + config.pkce === false && + (config.tokenEndpointAuthMethod === undefined || config.tokenEndpointAuthMethod === "none") + ? { + path: ["pkce"], + issue: + "pkce: false requires tokenEndpointAuthMethod client_secret_post, client_secret_basic or client_secret_basic_raw.", + } + : undefined, +); + /** How the token endpoint reads requests. RFC 6749 uses a form; some services want JSON. */ export const OAuthTokenRequestFormat = Schema.Literals(["form", "json"]); export type OAuthTokenRequestFormat = typeof OAuthTokenRequestFormat.Type; @@ -159,9 +175,14 @@ export const OAuth2Config = Schema.Union([ scopes: Schema.Array(Schema.String), /** RFC 8414 issuer identifier. Declared issuers are checked against the callback's `iss`. */ issuer: Schema.optionalKey(HttpUrl), + /** + * `false` signs in without PKCE, for a service whose token endpoint refuses a confidential + * client's `code_verifier`: LinkedIn answers `invalid_client`. Requires a secret client method. + */ + pkce: Schema.optionalKey(Schema.Literal(false)), discover: Schema.optionalKey(Schema.Never), authorizationServerMetadataUrl: Schema.optionalKey(Schema.Never), - }).check(declaredAuthorizationQuery), + }).check(declaredAuthorizationQuery, declaredPkce), Schema.Struct({ grant: Schema.Literal("client_credentials"), discover: HttpUrl, diff --git a/packages/sdk/src/contracts/oauth.ts b/packages/sdk/src/contracts/oauth.ts index 8c417ccfd9..a3d98929c3 100644 --- a/packages/sdk/src/contracts/oauth.ts +++ b/packages/sdk/src/contracts/oauth.ts @@ -1564,7 +1564,8 @@ const attemptFields = { reconnect: Schema.optional(Schema.Boolean), redirectUri: HttpUrl, state: Schema.NonEmptyString, - verifier: Schema.NonEmptyString, + /** Absent when the provider declares `pkce: false`; only a secret client signs in so. */ + verifier: Schema.optionalKey(Schema.NonEmptyString), response: JsonObject, }; /** Protocol context frozen when authorization starts, preventing callback-supplied identity changes. */ diff --git a/packages/sdk/src/implementation/oauth-protocol.ts b/packages/sdk/src/implementation/oauth-protocol.ts index 5091241493..ffccb223b7 100644 --- a/packages/sdk/src/implementation/oauth-protocol.ts +++ b/packages/sdk/src/implementation/oauth-protocol.ts @@ -1604,6 +1604,7 @@ export const makeOAuthProtocol = (options: OAuthOptions) => { ? {} : { authorizationParams: method.authorizationParams }), ...(method.tokenResponse === undefined ? {} : { tokenResponse: method.tokenResponse }), + ...("pkce" in method && method.pkce === false ? { pkce: false as const } : {}), }; }).pipe(protocolStage("discover")), /** @@ -1737,11 +1738,20 @@ export const makeOAuthProtocol = (options: OAuthOptions) => { resource?: string; authorizationParams?: Readonly>; scopeSeparator?: string; + /** `false` when the provider declares that its token endpoint refuses PKCE. */ + pkce?: false; }) => Effect.gen(function* () { + // Without PKCE only the client's secret binds the code to this client. + if (input.pkce === false && input.client.token_endpoint_auth_method === "none") + return yield* new OAuthProtocolFailed({ reason: "invalid_client" }); const state = `${options.statePrefix ?? ""}${yield* Effect.sync(oauth.generateRandomState)}`; - const verifier = yield* Effect.sync(oauth.generateRandomCodeVerifier); - const challenge = yield* request(() => oauth.calculatePKCECodeChallenge(verifier)); + const verifier = + input.pkce === false ? undefined : yield* Effect.sync(oauth.generateRandomCodeVerifier); + const challenge = + verifier === undefined + ? undefined + : yield* request(() => oauth.calculatePKCECodeChallenge(verifier)); const url = new URL(input.server.authorization_endpoint); for (const [key, value] of Object.entries(renewableGrantParams(url))) if (!url.searchParams.has(key)) url.searchParams.set(key, value); @@ -1753,15 +1763,21 @@ export const makeOAuthProtocol = (options: OAuthOptions) => { client_id: input.client.client_id, redirect_uri: input.redirectUri, state, - code_challenge: challenge, - code_challenge_method: "S256", + ...(challenge === undefined + ? {} + : { code_challenge: challenge, code_challenge_method: "S256" }), })) url.searchParams.set(key, value); if (input.scopes.length > 0) url.searchParams.set("scope", input.scopes.join(input.scopeSeparator ?? " ")); if (input.resource !== undefined) url.searchParams.set("resource", input.resource); - // No `nonce`: Executor ignores ID tokens, and PKCE S256 binds the code to this attempt. - return { state, verifier, authorizationUrl: url.href }; + // No `nonce`: Executor ignores ID tokens, and PKCE S256, when sent, binds the code to this + // attempt. + return { + state, + ...(verifier === undefined ? {} : { verifier }), + authorizationUrl: url.href, + }; }).pipe(protocolStage("authorize")), /** * Validate the authorization response before any token request: its state, its RFC 9207 @@ -1803,7 +1819,8 @@ export const makeOAuthProtocol = (options: OAuthOptions) => { client: OAuthRegistration; clientKind: OAuthClientKind; redirectUri: string; - verifier: string; + /** Absent when the attempt signed in without PKCE. */ + verifier?: string | undefined; resource?: string | undefined; tokenRequestFormat?: OAuthTokenRequestFormat | undefined; tokenResponse?: OAuthTokenResponse | undefined; @@ -1820,7 +1837,7 @@ export const makeOAuthProtocol = (options: OAuthOptions) => { clientAuth(input.client), parameters, input.redirectUri, - input.verifier, + input.verifier ?? oauth.nopkce, { ...settings, ...(input.resource === undefined From 9239541b0b10af6da88b7984c52ad1586cb9ccd6 Mon Sep 17 00:00:00 2001 From: Rhys Sullivan <39114868+RhysSullivan@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:52:56 +0000 Subject: [PATCH 06/68] Export aea22914 --- apps/local/desktop/scripts/build.mjs | 10 +- .../src/implementation/development-updates.ts | 18 + .../desktop/src/implementation/updates.ts | 72 +++- apps/local/desktop/src/main.ts | 68 +++- .../local/web/src/contracts/desktop-update.ts | 31 ++ apps/local/web/src/implementation/app.tsx | 8 + .../web/src/implementation/desktop-update.tsx | 128 ++++++ e2e/README.md | 16 + e2e/ci-selection.ts | 1 + e2e/desktop-update.config.ts | 16 + e2e/test-plan.ts | 24 ++ e2e/tests/desktop-update.spec.ts | 297 ++++++++++++++ e2e/tests/local-desktop-update.spec.ts | 384 ++++++++++++++++++ .../ui/src/implementation/dashboard/shell.tsx | 20 +- scripts/releases/desktop.ts | 21 +- 15 files changed, 1078 insertions(+), 36 deletions(-) create mode 100644 apps/local/desktop/src/implementation/development-updates.ts create mode 100644 apps/local/web/src/contracts/desktop-update.ts create mode 100644 apps/local/web/src/implementation/desktop-update.tsx create mode 100644 e2e/desktop-update.config.ts create mode 100644 e2e/tests/desktop-update.spec.ts create mode 100644 e2e/tests/local-desktop-update.spec.ts diff --git a/apps/local/desktop/scripts/build.mjs b/apps/local/desktop/scripts/build.mjs index e167b93970..981e823ae3 100644 --- a/apps/local/desktop/scripts/build.mjs +++ b/apps/local/desktop/scripts/build.mjs @@ -1,11 +1,13 @@ /** * Bundle the native entry, and the server starter it runs in a utility process, while keeping - * Electron's runtime API external, as T3 Code does. + * Electron's runtime API external, as T3 Code does. `--release` builds what the release packages: + * like the CLI's release bundles it defines EXECUTOR_DESKTOP_DEV as "0", which leaves the desktop's + * development-only code out of the bundle. */ import { fileURLToPath } from "node:url"; import { build } from "esbuild"; -export async function buildDesktop() { +export async function buildDesktop({ release = false } = {}) { const desktop = fileURLToPath(new URL("..", import.meta.url)); await build({ entryPoints: { @@ -20,7 +22,9 @@ export async function buildDesktop() { target: "node24", external: ["electron"], sourcemap: true, + define: release ? { "process.env.EXECUTOR_DESKTOP_DEV": '"0"' } : {}, }); } -if (process.argv[1] === fileURLToPath(import.meta.url)) await buildDesktop(); +if (process.argv[1] === fileURLToPath(import.meta.url)) + await buildDesktop({ release: process.argv.includes("--release") }); diff --git a/apps/local/desktop/src/implementation/development-updates.ts b/apps/local/desktop/src/implementation/development-updates.ts new file mode 100644 index 0000000000..4711fee4d5 --- /dev/null +++ b/apps/local/desktop/src/implementation/development-updates.ts @@ -0,0 +1,18 @@ +/** + * A development desktop's update feed, for the desktop update scenario: the updater config that + * EXECUTOR_DESKTOP_DEV_UPDATE_CONFIG names, in app-update.yml's form. `updates.ts` imports this + * module only where `process.env.EXECUTOR_DESKTOP_DEV` is not "0", and the release build defines it + * as "0" (`scripts/build.mjs --release`), so a release bundle does not contain this module. + */ +import { autoUpdater } from "electron-updater"; +import { Config, Effect, Option, Path } from "effect"; + +/** Point the updater at the named feed. Whether one was named. */ +export const developmentFeed = Effect.gen(function* () { + const path = yield* Path.Path; + const file = yield* Config.String("EXECUTOR_DESKTOP_DEV_UPDATE_CONFIG").pipe(Config.option); + if (Option.isNone(file)) return false; + autoUpdater.forceDevUpdateConfig = true; + autoUpdater.updateConfigPath = path.resolve(file.value); + return true; +}); diff --git a/apps/local/desktop/src/implementation/updates.ts b/apps/local/desktop/src/implementation/updates.ts index 0781454fbb..6956e8accb 100644 --- a/apps/local/desktop/src/implementation/updates.ts +++ b/apps/local/desktop/src/implementation/updates.ts @@ -1,12 +1,15 @@ /** * Desktop updater. The packaged build's app-update.yml names its channel feed; * builds without one (unsigned macOS, Linux packages other than AppImage) only - * point people to the download page. + * point people to the download page. A development build checks only a feed that + * EXECUTOR_DESKTOP_DEV_UPDATE_CONFIG names, as the desktop update scenario does + * (`development-updates.ts`); a release build does not contain that setting. */ -import { dialog } from "electron"; +import { app, dialog } from "electron"; import { autoUpdater } from "electron-updater"; import { Duration, Effect, FileSystem, Option, Path, Ref, Schedule, Semaphore } from "effect"; +import type { DesktopUpdate } from "../../../web/src/contracts/desktop-update.ts"; import { UpdateFailed } from "../contracts/desktop.ts"; const invoke = (operation: () => Promise) => Effect.tryPromise({ try: operation, catch: () => new UpdateFailed() }); @@ -15,17 +18,28 @@ const firstCheck = Duration.seconds(15); const checkInterval = Duration.hours(4); /** - * Check in the background, download quietly and offer one restart per version. - * Returns the menu action, which also offers a version declined earlier. + * Check in the background and download quietly. The update is shown, never offered in a dialog: + * `show` receives it while it downloads and once it is ready, and the dashboard's sidebar offers + * the restart that `install` performs. The menu's check answers in dialogs, since it was asked. */ -export const makeUpdater = (restart: (install: () => void) => void) => +export const makeUpdater = (options: { + readonly restart: (install: () => void) => void; + readonly show: (update: Option.Option) => void; +}) => Effect.gen(function* () { const lock = yield* Semaphore.make(1); const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; + // Release bundles define EXECUTOR_DESKTOP_DEV as "0", which leaves this import out of them. + const development = + process.env.EXECUTOR_DESKTOP_DEV !== "0" && !app.isPackaged + ? yield* Effect.promise(() => import("./development-updates.ts")).pipe( + Effect.flatMap(({ developmentFeed }) => developmentFeed), + ) + : false; const configured = (process.platform !== "linux" || process.env.APPIMAGE !== undefined) && - (yield* fs.exists(path.join(process.resourcesPath, "app-update.yml"))); + (development || (yield* fs.exists(path.join(process.resourcesPath, "app-update.yml")))); // Assigning a channel at runtime would also allow downgrades, so the feed's channel stays in app-update.yml. autoUpdater.autoDownload = false; autoUpdater.autoInstallOnAppQuit = false; @@ -35,7 +49,16 @@ export const makeUpdater = (restart: (install: () => void) => void) => yield* Effect.addFinalizer(() => Effect.sync(() => autoUpdater.removeListener("error", onError)), ); - const declined = yield* Ref.make(Option.none()); + const update = yield* Ref.make(Option.none()); + const set = (next: Option.Option) => + Ref.set(update, next).pipe(Effect.andThen(Effect.sync(() => options.show(next)))); + + /** Restart into the downloaded version, if one is ready. */ + const install = Effect.gen(function* () { + const current = yield* Ref.get(update); + if (Option.isSome(current) && current.value.state === "ready") + options.restart(() => autoUpdater.quitAndInstall()); + }); const offerRestart = (version: string) => Effect.gen(function* () { @@ -50,36 +73,47 @@ export const makeUpdater = (restart: (install: () => void) => void) => cancelId: 1, }), ); - if (confirmation.response === 0) restart(() => autoUpdater.quitAndInstall()); - else yield* Ref.set(declined, Option.some(version)); + if (confirmation.response === 0) yield* install; }); + /** + * Download a newer version, shown as downloading meanwhile and as ready once it is. A failed + * download or verification shows nothing: electron-updater drops the installer it held + * before, so an older version shown as ready could no longer be installed. The next check, + * on the schedule, from the menu or at the next start, downloads it again. + */ const download = (announce: boolean) => Effect.gen(function* () { const result = yield* invoke(() => autoUpdater.checkForUpdates()); if (result === null || !result.isUpdateAvailable) return Option.none(); + const version = result.updateInfo.version; + const previous = yield* Ref.get(update); + if ( + Option.isSome(previous) && + previous.value.state === "ready" && + previous.value.version === version + ) + return Option.some(version); // The download can take a while; the restart prompt follows when it finishes. if (announce) void dialog.showMessageBox({ type: "info", - message: `Downloading Executor 2 ${result.updateInfo.version}.`, + message: `Downloading Executor 2 ${version}.`, detail: "You will be asked to restart when it is ready.", }); const cancellation = result.cancellationToken; if (cancellation === undefined) return yield* new UpdateFailed(); + yield* set(Option.some({ state: "downloading", version })); yield* invoke(() => autoUpdater.downloadUpdate(cancellation)).pipe( Effect.onInterrupt(() => Effect.sync(() => cancellation.cancel())), + Effect.onError(() => set(Option.none())), ); - return Option.some(result.updateInfo.version); + yield* set(Option.some({ state: "ready", version })); + return Option.some(version); }); - const background = Effect.gen(function* () { - const version = yield* download(false); - if (Option.isNone(version)) return; - const skipped = yield* Ref.get(declined); - if (Option.isSome(skipped) && skipped.value === version.value) return; - yield* offerRestart(version.value); - }).pipe( + const background = download(false).pipe( + Effect.asVoid, lock.withPermitsIfAvailable(1), Effect.catch(() => Effect.logWarning("Desktop update check failed")), ); @@ -123,5 +157,5 @@ export const makeUpdater = (restart: (install: () => void) => void) => Effect.delay(firstCheck), Effect.forkScoped, ); - return manual; + return { check: manual, install, configured }; }); diff --git a/apps/local/desktop/src/main.ts b/apps/local/desktop/src/main.ts index 7b87818013..39993907b4 100644 --- a/apps/local/desktop/src/main.ts +++ b/apps/local/desktop/src/main.ts @@ -33,6 +33,11 @@ import { ServiceFailed } from "../../server/src/contracts/service.ts"; import { DesktopFailed, externalUrl, type DesktopRecovery } from "./contracts/desktop.ts"; import { release } from "../../../../scripts/releases/config.ts"; import { makeUpdater } from "./implementation/updates.ts"; +import { + type DesktopUpdate, + desktopUpdateRestartUrl, + desktopUpdateScript, +} from "../../web/src/contracts/desktop-update.ts"; import { makeOpenBrowserAction } from "./implementation/browser.ts"; import { movingUrl, startupUrl } from "./implementation/startup.ts"; import { makeConnection, type Connection } from "./implementation/connection.ts"; @@ -666,6 +671,39 @@ const desktop = Effect.gen(function* () { } }; + /** The page `current` shows is the dashboard, not the startup or recovery page. */ + const showsDashboard = (current: BrowserWindow) => { + const dashboard = origin(); + if (current.isDestroyed() || dashboard === undefined) return false; + return URL.parse(current.webContents.getURL())?.origin === dashboard; + }; + /** The update the dashboard's sidebar shows while it downloads and once it is ready. */ + let update = Option.none(); + const showUpdate = (current: BrowserWindow) => { + if (!showsDashboard(current)) return; + const script = desktopUpdateScript(Option.getOrUndefined(update)); + run( + Effect.tryPromise(() => current.webContents.executeJavaScript(script)).pipe( + Effect.catch(() => Effect.logWarning("Desktop window could not show the update")), + ), + ); + }; + /** + * The application menu, set once the desktop's actions exist. Its Updates menu also + * offers the ready update's restart, as the sidebar does, for someone who keeps no + * window open. + */ + let menu: ((update: Option.Option) => Menu) | undefined; + const updater = yield* makeUpdater({ + restart: after, + show: (next) => { + update = next; + if (window !== undefined) showUpdate(window); + if (menu !== undefined) Menu.setApplicationMenu(menu(update)); + }, + }); + yield* closing("its updater"); + const followAppearance = () => { if (window !== undefined && !window.isDestroyed()) window.setBackgroundColor(windowBackground()); @@ -693,6 +731,8 @@ const desktop = Effect.gen(function* () { current.once("ready-to-show", () => { if (!current.isDestroyed()) current.show(); }); + // Each document the dashboard loads is told about the update. + current.webContents.on("dom-ready", () => showUpdate(current)); current.webContents.on("did-finish-load", () => { if (!current.isDestroyed() && origin() !== undefined) current.webContents.setBackgroundThrottling(true); @@ -709,6 +749,12 @@ const desktop = Effect.gen(function* () { recover(current, url); return; } + // The sidebar card's restart button, a link; only the dashboard can follow it. + if (url === desktopUpdateRestartUrl) { + event.preventDefault(); + if (showsDashboard(current)) run(updater.install); + return; + } if (new URL(url).origin !== origin()) { event.preventDefault(); openExternal(url); @@ -769,8 +815,6 @@ const desktop = Effect.gen(function* () { ); yield* closing("its windows"); - const checkForUpdates = yield* makeUpdater(after); - yield* closing("its updater"); const openBrowser = yield* makeOpenBrowserAction(browserSession, origin); const exportDiagnostics = yield* makeExportDiagnosticsAction({ directory, @@ -817,12 +861,20 @@ const desktop = Effect.gen(function* () { { label: "Rotate local API key…", click: () => run(rotateKeyAction) }, ]; }); - Menu.setApplicationMenu( + menu = (current) => applicationMenu({ file: [{ label: "Open in browser", click: () => run(openBrowser) }, ...dataActions], - updates: app.isPackaged - ? [{ label: "Check for updates…", click: () => run(checkForUpdates) }] - : [], + updates: [ + ...Option.toArray(Option.filter(current, ({ state }) => state === "ready")).map( + ({ version }) => ({ + label: `Restart to update (v${version})`, + click: () => run(updater.install), + }), + ), + ...(app.isPackaged || updater.configured + ? [{ label: "Check for updates…", click: () => run(updater.check) }] + : []), + ], help: [ { label: "Show diagnostics folder", click: () => void shell.openPath(diagnostics) }, { label: "Export diagnostics…", click: () => run(exportDiagnostics) }, @@ -833,8 +885,8 @@ const desktop = Effect.gen(function* () { { label: "Reset Executor data…", click: () => run(reset) }, ]), ], - }), - ); + }); + Menu.setApplicationMenu(menu(update)); if (Result.isFailure(migration)) view = { kind: "recovery", diff --git a/apps/local/web/src/contracts/desktop-update.ts b/apps/local/web/src/contracts/desktop-update.ts new file mode 100644 index 0000000000..d3a23ca627 --- /dev/null +++ b/apps/local/web/src/contracts/desktop-update.ts @@ -0,0 +1,31 @@ +/** + * The desktop app's update, shown in the dashboard's sidebar. The desktop window has no preload + * or IPC bridge, so its main process writes the update on the dashboard's document, as this + * attribute's JSON, and announces each change with this event. The sidebar's action is a link to + * `executor-update:restart`, which the main process intercepts as it does the recovery page's + * links. A dashboard outside the desktop never gets the attribute and shows nothing. + */ +import { Schema } from "effect"; + +export const DesktopUpdate = Schema.Struct({ + /** `downloading` while the desktop fetches it; `ready` once a restart installs it. */ + state: Schema.Literals(["downloading", "ready"]), + version: Schema.String, +}); +export type DesktopUpdate = typeof DesktopUpdate.Type; + +export const desktopUpdateAttribute = "data-desktop-update"; +export const desktopUpdateEvent = "executor:desktop-update"; +export const desktopUpdateRestartUrl = "executor-update:restart"; + +/** + * The script the desktop runs in the dashboard's page to show `update`, or to clear it. The value + * is JSON, written into the script as a string literal. + */ +export const desktopUpdateScript = (update: DesktopUpdate | undefined) => + `((value) => { + const root = document.documentElement; + if (value === null) root.removeAttribute(${JSON.stringify(desktopUpdateAttribute)}); + else root.setAttribute(${JSON.stringify(desktopUpdateAttribute)}, value); + window.dispatchEvent(new Event(${JSON.stringify(desktopUpdateEvent)})); +})(${JSON.stringify(update === undefined ? null : JSON.stringify(update))});`; diff --git a/apps/local/web/src/implementation/app.tsx b/apps/local/web/src/implementation/app.tsx index 6b2d2515db..319eaeb0c6 100644 --- a/apps/local/web/src/implementation/app.tsx +++ b/apps/local/web/src/implementation/app.tsx @@ -25,6 +25,11 @@ import { publicDocsBaseUrl } from "@executor-js/ui/contracts/documentation"; import { documentBuild } from "@executor-js/dashboard-start/document-build"; import { NameAccountDialog } from "./pages/name-account-dialog.tsx"; import { OwnerMigrationBanner } from "./owner-migration.tsx"; +import { + DesktopUpdateAnnouncement, + DesktopUpdateCard, + useDesktopUpdate, +} from "./desktop-update.tsx"; /** Finish pairing and session checks before mounting any dashboard data consumers. */ export function AuthenticationGate({ @@ -124,11 +129,13 @@ function Dashboard() { const refresh = useAtomRefresh(overviewAtom); const data = AsyncResult.value(result); const error = AsyncResult.isFailure(result) ? Cause.findErrorOption(result.cause) : Option.none(); + const update = useDesktopUpdate(); if (Option.isSome(error) && Schema.is(DashboardUnauthorized)(error.value)) return ; return ( } brand={ + ); } diff --git a/apps/local/web/src/implementation/desktop-update.tsx b/apps/local/web/src/implementation/desktop-update.tsx new file mode 100644 index 0000000000..bbc4953b3d --- /dev/null +++ b/apps/local/web/src/implementation/desktop-update.tsx @@ -0,0 +1,128 @@ +import { useSyncExternalStore } from "react"; +import { Option, Schema } from "effect"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { Download04Icon, RefreshIcon } from "@hugeicons/core-free-icons"; +import { Button } from "@executor-js/ui/components/button"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@executor-js/ui/components/tooltip"; +import { useSidebarCollapsed } from "@executor-js/ui/dashboard/shell"; +import { + DesktopUpdate, + desktopUpdateAttribute, + desktopUpdateEvent, + desktopUpdateRestartUrl, +} from "../contracts/desktop-update.ts"; + +const decode = Schema.decodeUnknownOption(Schema.fromJsonString(DesktopUpdate)); + +const subscribe = (listener: () => void) => { + window.addEventListener(desktopUpdateEvent, listener); + return () => window.removeEventListener(desktopUpdateEvent, listener); +}; +const snapshot = () => document.documentElement.getAttribute(desktopUpdateAttribute); + +/** The update the desktop app has told this dashboard about; none outside the desktop. */ +export function useDesktopUpdate() { + const value = useSyncExternalStore(subscribe, snapshot, () => null); + return value === null ? Option.none() : decode(value); +} + +/** + * The desktop app's update, as the sidebar's card above its links: what it downloads, then a + * button that restarts Executor into it. The icon rail shows the same as an icon with a tooltip. + * On a short window the card drops its description, and the sidebar scrolls as it always has. + */ +export function DesktopUpdateCard({ update }: { readonly update: DesktopUpdate }) { + const collapsed = useSidebarCollapsed(); + const version = `v${update.version}`; + const restart = `Restart Executor to install ${version}`; + if (collapsed) + return ( +
+ + + + {update.state === "ready" ? ( + + ) : ( + + + + )} + + + {update.state === "ready" ? restart : `Downloading ${version}`} + + + +
+ ); + if (update.state === "downloading") + return ( +
+ + Downloading {version} +
+ ); + return ( +
+
+

+ Update ready + + {version} + +

+

+ Executor restarts to install it. +

+
+ +
+ ); +} + +/** + * Says once, to a screen reader, that the desktop's update is ready, whichever form the sidebar + * shows it in. The region is always on the page, so the change into it is announced; it is empty + * while there is nothing ready, as in any browser. + */ +export function DesktopUpdateAnnouncement({ + update, +}: { + readonly update: Option.Option; +}) { + const ready = Option.filter(update, (value) => value.state === "ready"); + return ( +
+ {Option.isSome(ready) && + `Update ready: Executor v${ready.value.version}. Restart Executor to install it.`} +
+ ); +} diff --git a/e2e/README.md b/e2e/README.md index 869ee26679..709be66fe0 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -1146,6 +1146,22 @@ EXECUTOR_E2E_DESKTOP_EXECUTABLE='/path/to/Executor Preview.app/Contents/MacOS/Ex bunx vitest run --config e2e/desktop-release.config.ts ``` +### Desktop update + +The desktop update scenario (`desktopUpdate`) runs the desktop's updater from its feed to its +restart: the sidebar's card and the Updates menu offer a downloaded version, a newer download that +fails verification clears both, and the menu's item and the card's button each install. It runs +only on macOS, against a development build, which reads the loopback feed the scenario serves from +`EXECUTOR_DESKTOP_DEV_UPDATE_CONFIG` (a release build does not contain that setting). Squirrel.Mac, which installs a +macOS update and accepts only Executor's signed app, is played through Electron's `autoUpdater`. +No CI job runs it; run it before merging a change to the desktop's updater or its menu: + +```sh +node apps/local/desktop/scripts/build.mjs +bun run web:build +bunx vitest run --config e2e/desktop-update.config.ts +``` + Verify a locally built image without pushing it: ```sh diff --git a/e2e/ci-selection.ts b/e2e/ci-selection.ts index fd7f0f8d4d..1542539855 100644 --- a/e2e/ci-selection.ts +++ b/e2e/ci-selection.ts @@ -783,6 +783,7 @@ const suiteConfigs: Record Promise> = { "desktop-next-server.config.ts": () => import("./desktop-next-server.config.ts"), "desktop-recovery.config.ts": () => import("./desktop-recovery.config.ts"), "desktop-release.config.ts": () => import("./desktop-release.config.ts"), + "desktop-update.config.ts": () => import("./desktop-update.config.ts"), "emulator-failures.config.ts": () => import("./emulator-failures.config.ts"), "export-public.config.ts": () => import("./export-public.config.ts"), "docker-release.config.ts": () => import("./docker-release.config.ts"), diff --git a/e2e/desktop-update.config.ts b/e2e/desktop-update.config.ts new file mode 100644 index 0000000000..23a76d68b2 --- /dev/null +++ b/e2e/desktop-update.config.ts @@ -0,0 +1,16 @@ +import { defineConfig } from "vitest/config"; + +/** + * The desktop update scenario, on a development build of the desktop on macOS: it stands in for + * Squirrel.Mac, which installs macOS updates. Run it after `node apps/local/desktop/scripts/build.mjs` + * (e2e/README.md, "Desktop update"). The scenario itself refuses another platform or a + * packaged build; this file only names it, as the CI selection reads every config on Linux. + */ +export default defineConfig({ + test: { + include: ["e2e/tests/desktop-update.spec.ts"], + testTimeout: 240_000, + // Prints each desktop close's duration. + globalSetup: ["e2e/desktop-close-durations.ts"], + }, +}); diff --git a/e2e/test-plan.ts b/e2e/test-plan.ts index 28720a77da..78cb1ce95d 100644 --- a/e2e/test-plan.ts +++ b/e2e/test-plan.ts @@ -1798,6 +1798,20 @@ export const scenarios = plan({ "self-host": na("Desktop clipboard permission"), }, }, + desktopUpdate: { + file: "desktop-update.spec.ts", + title: + "desktop shows a downloaded update in the sidebar and the Updates menu, clears both when a newer download fails verification, and installs from either", + targets: { + local: { + status: "not-run", + reason: + "Runs on macOS against a development build with desktop-update.config.ts (e2e/README.md, Desktop update).", + }, + cloud: na("Only the desktop app updates itself."), + "self-host": na("Only the desktop app updates itself."), + }, + }, desktopReset: { file: "desktop-recovery.spec.ts", title: @@ -3356,6 +3370,16 @@ export const scenarios = plan({ local: na("The local dashboard is covered by its own support scenario."), }, }, + localDesktopUpdate: { + file: "local-desktop-update.spec.ts", + title: + "local dashboard shows the desktop's update as a card above the sidebar's links only while there is one, as a download status and then a named restart button the keyboard reaches, without moving the navigation or the links, also in a short window and the collapsed rail, announces once that it is ready, and wraps a long version", + targets: { + local: scheduled, + "self-host": na("Only the desktop app, which runs the local dashboard, updates itself."), + cloud: na("Only the desktop app, which runs the local dashboard, updates itself."), + }, + }, localSupportDialog: { file: "local-support-dialog.spec.ts", title: "local dashboard keeps its resource links without the Cloud support dialog", diff --git a/e2e/tests/desktop-update.spec.ts b/e2e/tests/desktop-update.spec.ts new file mode 100644 index 0000000000..13f80cce2b --- /dev/null +++ b/e2e/tests/desktop-update.spec.ts @@ -0,0 +1,297 @@ +/** + * The desktop app's own update path, from its updater's feed to its restart, on a development + * build of the desktop (`node apps/local/desktop/scripts/build.mjs`) on macOS. The scenario serves + * the feed from a loopback server and names it with EXECUTOR_DESKTOP_DEV_UPDATE_CONFIG, which a + * release build does not contain. electron-updater downloads and verifies each version as it would from + * the release feed; only Squirrel.Mac, which installs the download and refuses an app that is not + * Executor's signed one, is played by the scenario through Electron's `autoUpdater`, which records + * the install it is asked for and ends the desktop as Squirrel.Mac would. + */ +import { expect, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Config, Effect, FileSystem, Layer, Path, Schedule } from "effect"; +import { FetchHttpClient } from "effect/http"; +import type { ElectronApplication, Page } from "playwright"; +import { createHash, randomBytes } from "node:crypto"; +import { createServer } from "node:http"; +import { driver } from "../support/platform.ts"; +import { localNpmRegistry } from "../support/npm-registry.ts"; +import { freePort } from "../support/ports.ts"; +import { + answerDialogs, + answeredDialogs, + clickMenuItem, + launchDesktop, + menuLabels, + runnerSession, + stopBackgroundServers, +} from "../support/desktop.ts"; +import { scenarios } from "../test-plan.ts"; + +/** What the feed offers: a version, and whether its download's bytes fail verification. */ +interface Offer { + readonly version: string; + readonly corrupt: boolean; +} + +/** + * A generic electron-updater feed on loopback that offers `offer.version`. The update's file is + * random bytes the feed lists with their SHA-512, or, when the offer is corrupt, other bytes of + * the same size, so electron-updater's verification of the download fails. + */ +const updateFeed = Effect.gen(function* () { + const port = yield* freePort; + let offer: + | { readonly version: string; readonly listed: Buffer; readonly served: Buffer } + | undefined; + const file = (version: string) => `Executor-${version}-mac-arm64.zip`; + yield* Effect.acquireRelease( + Effect.callback>((resume) => { + const created = createServer((request, response) => { + const name = new URL(request.url ?? "/", "http://127.0.0.1").pathname.slice(1); + if (name === "latest-mac.yml" && offer !== undefined) { + const bytes = offer.listed; + const sha512 = createHash("sha512").update(bytes).digest("base64"); + response.writeHead(200, { "content-type": "text/yaml" }); + response.end( + [ + `version: ${offer.version}`, + "files:", + ` - url: ${file(offer.version)}`, + ` sha512: ${sha512}`, + ` size: ${bytes.length}`, + `path: ${file(offer.version)}`, + `sha512: ${sha512}`, + `releaseDate: '2026-11-17T00:00:00.000Z'`, + "", + ].join("\n"), + ); + return; + } + const bytes = + offer !== undefined && name === file(offer.version) ? offer.served : undefined; + if (bytes === undefined) { + response.writeHead(404); + response.end(); + return; + } + response.writeHead(200, { + "content-type": "application/zip", + "content-length": bytes.length, + }); + response.end(bytes); + }); + created.listen(port, "127.0.0.1", () => resume(Effect.succeed(created))); + }), + (server) => + Effect.callback((resume) => { + server.close(() => resume(Effect.void)); + }), + ); + return { + url: `http://127.0.0.1:${port}/`, + offer: (next: Offer) => + Effect.sync(() => { + const listed = randomBytes(64 * 1024); + offer = { + version: next.version, + listed, + served: next.corrupt ? randomBytes(listed.length) : listed, + }; + }), + }; +}); + +/** + * Play Squirrel.Mac in the desktop's main process: it accepts electron-updater's download as + * fetched and, asked to install, writes `marker` and ends the desktop as an install does. + */ +const standInForSquirrel = (electron: ElectronApplication, marker: string) => + driver("stand in for Squirrel.Mac", () => + electron.evaluate(({ app, autoUpdater }, marker) => { + const fs = process.getBuiltinModule("node:fs"); + Object.assign(autoUpdater, { + setFeedURL: () => undefined, + checkForUpdates: () => + void setImmediate(() => + autoUpdater.emit("update-downloaded", {}, "", "", new Date(), ""), + ), + quitAndInstall: () => { + fs.writeFileSync(marker, "installed"); + app.exit(0); + }, + }); + }, marker), + ); + +const sidebar = (page: Page) => page.locator("aside.sidebar"); +const restartLink = (page: Page, version: string) => + sidebar(page).getByRole("link", { name: `Restart Executor to install v${version}` }); + +const dashboard = (page: Page) => + driver("dashboard is visible", () => + page.getByRole("heading", { name: /^Apps/ }).waitFor({ state: "visible", timeout: 60_000 }), + ); + +/** The labels of the Updates menu, once `ready` says they are what the scenario waits for. */ +const updatesMenu = (electron: ElectronApplication, ready: (labels: Array) => boolean) => + menuLabels(electron, "Updates").pipe( + Effect.flatMap((labels) => + ready(labels) + ? Effect.succeed(labels) + : Effect.fail(new Error(`The Updates menu is ${JSON.stringify(labels)}`)), + ), + Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 300 }), + ); + +/** Wait for a native message box whose message starts with `message`. */ +const dialogShown = (electron: ElectronApplication, message: string) => + answeredDialogs(electron).pipe( + Effect.flatMap((boxes) => + boxes?.some((box) => box.message.startsWith(message)) === true + ? Effect.succeed(boxes) + : Effect.fail(new Error(`No dialog said ${message}`)), + ), + Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 300 }), + ); + +/** Wait until the Squirrel.Mac stand-in wrote `marker`, as it does when asked to install. */ +const installed = (marker: string) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + return yield* fs.readFileString(marker); + }).pipe(Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 300 })); + +const screenshot = (page: Page, name: string) => + Effect.gen(function* () { + const path = yield* Path.Path; + const directory = yield* Config.String("EXECUTOR_E2E_DESKTOP_SCREENSHOTS").pipe( + Config.withDefault(".local/desktop-recovery"), + ); + yield* driver(`capture ${name}`, () => + page.screenshot({ path: path.resolve(directory, `${name}.png`) }), + ); + }); + +it.live(scenarios.desktopUpdate.title, () => + Effect.scoped( + Effect.gen(function* () { + // A stand-in for Squirrel.Mac only means something on macOS, and a release build does not + // contain the setting that names the feed the scenario serves. + if (process.platform !== "darwin") + return yield* Effect.fail( + new Error("The desktop update scenario stands in for Squirrel.Mac, so it runs on macOS."), + ); + if (process.env.EXECUTOR_E2E_DESKTOP_EXECUTABLE !== undefined) + return yield* Effect.fail( + new Error( + "The desktop update scenario runs a development build, whose updater reads the feed it serves; unset EXECUTOR_E2E_DESKTOP_EXECUTABLE.", + ), + ); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "executor-desktop-update-" }); + const data = path.join(home, "data"); + const feed = yield* updateFeed; + const config = path.join(home, "app-update.yml"); + yield* fs.writeFileString( + config, + `provider: generic\nurl: ${feed.url}\nchannel: latest\nupdaterCacheDirName: executor-desktop-update-e2e\n`, + ); + const registry = yield* localNpmRegistry; + // macOS has no variable for its cache directory, where the updater downloads, only the + // home it is in. + const env: Record = { + ...runnerSession(), + DO_NOT_TRACK: "1", + EXECUTOR_NO_UPDATE_CHECK: "1", + PATH: process.env.PATH ?? "", + HOME: path.join(home, "cache-home"), + EXECUTOR_PORT: String(yield* freePort), + EXECUTOR_DESKTOP_DATA_DIR: data, + EXECUTOR_DESKTOP_PROFILE_DIR: path.join(home, "profile"), + EXECUTOR_DESKTOP_DEV_UPDATE_CONFIG: config, + EXECUTOR_NPM_REGISTRY: registry.url, + EXECUTOR_API_KEY: randomBytes(32).toString("hex"), + EXECUTOR_ENCRYPTION_KEY: randomBytes(32).toString("hex"), + }; + yield* Effect.addFinalizer(() => stopBackgroundServers(data, () => [])); + + // The first check, shortly after the desktop starts, downloads the version the feed offers. + // Once it is ready the sidebar offers its restart, and so does the Updates menu, for + // someone who keeps no window open. + yield* feed.offer({ version: "2.0.0-beta.122", corrupt: false }); + const first = path.join(home, "installed-from-menu"); + yield* Effect.scoped( + Effect.gen(function* () { + const electron = yield* launchDesktop({ cwd: home, env }); + yield* standInForSquirrel(electron, first); + yield* answerDialogs(electron, {}); + const page = yield* driver("desktop window", () => electron.firstWindow()); + yield* dashboard(page); + yield* driver("the first update is ready in the sidebar", () => + restartLink(page, "2.0.0-beta.122").waitFor({ timeout: 60_000 }), + ); + expect(yield* updatesMenu(electron, (labels) => labels.length === 2)).toEqual([ + "Restart to update (v2.0.0-beta.122)", + "Check for updates…", + ]); + + // A newer version whose download fails verification leaves nothing to restart into: + // the card and the menu's restart go, and the menu's check says it failed. + yield* feed.offer({ version: "2.0.0-beta.123", corrupt: true }); + yield* clickMenuItem(electron, "Updates", "Check for updates…"); + yield* dialogShown(electron, "The update could not be completed."); + yield* driver("the card goes", () => + sidebar(page).locator(".sidebar-update").waitFor({ state: "detached" }), + ); + expect(yield* updatesMenu(electron, (labels) => labels.length === 1)).toEqual([ + "Check for updates…", + ]); + expect( + yield* driver("read the announcement", () => + page.locator(".desktop-update-announcement").innerText(), + ), + ).toBe(""); + + // Checking again downloads it whole. The menu's check offers the restart in a dialog, + // which is declined here; the card and the menu keep offering it with the long version. + yield* feed.offer({ version: "2.0.0-beta.123", corrupt: false }); + yield* clickMenuItem(electron, "Updates", "Check for updates…"); + yield* dialogShown(electron, "Executor 2 2.0.0-beta.123 is ready to install."); + yield* driver("the newer update is ready in the sidebar", () => + restartLink(page, "2.0.0-beta.123").waitFor({ timeout: 60_000 }), + ); + expect( + yield* driver("read the announcement", () => + page.locator(".desktop-update-announcement").innerText(), + ), + ).toBe("Update ready: Executor v2.0.0-beta.123. Restart Executor to install it."); + yield* screenshot(page, "desktop-update-ready"); + expect(yield* updatesMenu(electron, (labels) => labels.length === 2)).toEqual([ + "Restart to update (v2.0.0-beta.123)", + "Check for updates…", + ]); + + // The menu's restart installs it, as the card's button does. + yield* clickMenuItem(electron, "Updates", "Restart to update (v2.0.0-beta.123)"); + expect(yield* installed(first)).toBe("installed"); + }), + ); + + // A restart that did not install, as here, leaves the update to the next start's check, + // which makes it ready again; the card's button, a link the desktop intercepts, installs it. + const second = path.join(home, "installed-from-card"); + const electron = yield* launchDesktop({ cwd: home, env }); + yield* standInForSquirrel(electron, second); + const page = yield* driver("desktop window", () => electron.firstWindow()); + yield* dashboard(page); + yield* driver("press the card's restart button", () => + restartLink(page, "2.0.0-beta.123") + .waitFor({ timeout: 60_000 }) + .then(() => restartLink(page, "2.0.0-beta.123").click()), + ); + expect(yield* installed(second)).toBe("installed"); + }), + ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer))), +); diff --git a/e2e/tests/local-desktop-update.spec.ts b/e2e/tests/local-desktop-update.spec.ts new file mode 100644 index 0000000000..ffceee4189 --- /dev/null +++ b/e2e/tests/local-desktop-update.spec.ts @@ -0,0 +1,384 @@ +/** + * The desktop app's update in the local dashboard's sidebar. The desktop window has no preload or + * IPC bridge: its main process writes the update on the dashboard's document as the + * `data-desktop-update` attribute's JSON and announces it with the `executor:desktop-update` + * event, and intercepts the `executor-update:restart` navigation of the sidebar card's button to restart into + * it. This scenario plays the desktop's part in a browser, so it checks the dashboard's side. + */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Redacted, Schema } from "effect"; +import type { Page } from "playwright"; +import { Api, body } from "../support/api.ts"; +import { Browser } from "../support/browser.ts"; +import { TestLive, withCase } from "../support/case.ts"; +import { Target } from "../support/platform.ts"; +import { scenarios } from "../test-plan.ts"; + +type Update = { readonly state: "downloading" | "ready"; readonly version: string } | null; + +/** What the desktop's main process runs in the dashboard's page when its update changes. */ +const showUpdate = (page: Page, update: Update) => + page.evaluate( + (value) => { + const root = document.documentElement; + if (value === null) root.removeAttribute("data-desktop-update"); + else root.setAttribute("data-desktop-update", value); + window.dispatchEvent(new Event("executor:desktop-update")); + }, + update === null ? null : JSON.stringify(update), + ); + +const restartLink = (page: Page) => + page.locator("aside.sidebar").getByRole("link", { name: "Restart Executor to install v2.4.0" }); + +const box = (page: Page, selector: string) => page.locator(selector).first().boundingBox(); + +/** The polite live region that says once that the update is ready. */ +const announcement = (page: Page) => + Promise.all([ + page.locator('[role="status"][aria-live="polite"].desktop-update-announcement').count(), + page.locator(".desktop-update-announcement").innerText(), + ]).then(([count, text]) => ({ count, text })); + +/** + * The card's text that is cut off or runs out of the sidebar: each element whose content is wider + * than its box, and whether the card itself reaches past the sidebar. + */ +const clipped = (page: Page) => + page.evaluate(() => { + const card = document.querySelector("aside.sidebar .sidebar-update"); + const sidebar = document.querySelector("aside.sidebar"); + if (card === null || sidebar === null) return { missing: true }; + const cut = [card, ...card.querySelectorAll("*")] + .filter((element) => element.scrollWidth > element.clientWidth + 1) + .map((element) => element.textContent ?? ""); + return { + cut, + outside: card.getBoundingClientRect().right > sidebar.getBoundingClientRect().right, + }; + }); + +/** Where the navigation, the divider above the links, the links and the version row sit. */ +const layout = (page: Page) => + Promise.all([ + box(page, "aside.sidebar nav"), + box(page, "aside.sidebar .sidebar-utilities"), + page.locator("aside.sidebar").getByRole("link", { name: "Docs" }).boundingBox(), + box(page, "aside.sidebar .sidebar-build"), + ]).then(([navigation, divider, docs, version]) => ({ navigation, divider, docs, version })); + +/** The card's box, and whether it sits below the navigation and above the links' divider. */ +const placement = (page: Page) => + Promise.all([ + box(page, "aside.sidebar .sidebar-update"), + box(page, "aside.sidebar nav"), + box(page, "aside.sidebar .sidebar-utilities"), + ]).then(([card, navigation, divider]) => ({ + belowNavigation: + card !== null && navigation !== null && card.y >= navigation.y + navigation.height, + aboveDivider: card !== null && divider !== null && card.y + card.height <= divider.y, + })); + +layer(TestLive, { excludeTestServices: true })("Local desktop update", (it) => { + it.effect(scenarios.localDesktopUpdate.title, (context) => + withCase( + context, + Effect.gen(function* () { + const api = yield* Api, + browser = yield* Browser, + target = yield* Target, + session = yield* api.session(); + const { url } = yield* body( + Schema.Struct({ url: Schema.String }), + yield* session.send("POST", "/auth/pair", undefined, { + authorization: `Bearer ${Redacted.value(target.apiKey)}`, + }), + ); + yield* browser.use("Pair the local dashboard", (page) => + page.setViewportSize({ width: 1180, height: 800 }).then(() => page.goto(url)), + ); + yield* browser.use("Wait for apps", (page) => + page.getByRole("heading", { level: 1, name: /^Apps/ }).waitFor(), + ); + + // A dashboard the desktop has told about no update, as in any browser, shows no card and + // keeps nothing in its place. + expect( + yield* browser.use("Check the sidebar has no update", (page) => + Promise.all([ + page.locator("aside.sidebar .sidebar-update").count(), + page.locator("aside.sidebar .sidebar-notice").count(), + ]), + ), + ).toEqual([0, 0]); + const without = yield* browser.use("Measure the sidebar", layout); + // The live region that says the update is ready is on the page already, and empty, so the + // moment it fills is announced. + expect(yield* browser.use("Read the empty announcement", announcement)).toEqual({ + count: 1, + text: "", + }); + + // While the update downloads, a quieter card says so and offers nothing to press. + yield* browser.use("Show a downloading update", (page) => + showUpdate(page, { state: "downloading", version: "2.4.0" }), + ); + yield* browser.use("Wait for the download status", (page) => + page + .locator("aside.sidebar") + .getByRole("status") + .filter({ hasText: "Downloading v2.4.0" }) + .waitFor(), + ); + expect( + yield* browser.use("Check there is no restart yet", (page) => restartLink(page).count()), + ).toBe(0); + expect(yield* browser.use("Read the announcement while downloading", announcement)).toEqual( + { count: 1, text: "" }, + ); + expect(yield* browser.use("Place the downloading card", placement)).toEqual({ + belowNavigation: true, + aboveDivider: true, + }); + expect(yield* browser.use("Measure the sidebar while downloading", layout)).toEqual( + without, + ); + + // Once it is ready, the card names the version, says Executor restarts to install it and + // has one button that restarts into it. It sits above the links' divider and moves neither + // the navigation nor the links. + yield* browser.use("Show a ready update", (page) => + showUpdate(page, { state: "ready", version: "2.4.0" }), + ); + yield* browser.use("Wait for the restart button", (page) => restartLink(page).waitFor()); + yield* browser.checkpoint("Update ready in the sidebar"); + expect( + yield* browser.use("Read the card", (page) => + Promise.all([ + page + .locator("aside.sidebar .sidebar-update") + .innerText() + .then((text) => text.split("\n").filter((line) => line.trim() !== "")), + restartLink(page).getAttribute("href"), + restartLink(page).innerText(), + page.locator("aside.sidebar .sidebar-update a").count(), + ]), + ), + ).toEqual([ + ["Update ready", "v2.4.0", "Executor restarts to install it.", "Restart to update"], + "executor-update:restart", + "Restart to update", + 1, + ]); + expect(yield* browser.use("Read the ready announcement", announcement)).toEqual({ + count: 1, + text: "Update ready: Executor v2.4.0. Restart Executor to install it.", + }); + expect(yield* browser.use("Place the ready card", placement)).toEqual({ + belowNavigation: true, + aboveDivider: true, + }); + expect(yield* browser.use("Measure the sidebar with the update", layout)).toEqual(without); + + // The keyboard reaches it, and pressing it follows the link the desktop intercepts. The + // browser has no handler for that scheme, so the page records where it would go instead. + const focused = (page: Page) => + page.evaluate(() => document.activeElement?.getAttribute("aria-label") ?? null); + yield* browser.use("Start from the page", (page) => page.locator("body").focus()); + let reached = false; + for (let step = 0; step < 40 && !reached; step += 1) { + yield* browser.use("Press Tab", (page) => page.keyboard.press("Tab")); + reached = + (yield* browser.use("Read the focused control", focused)) === + "Restart Executor to install v2.4.0"; + } + expect(reached).toBe(true); + yield* browser.use("Record where links go", (page) => + page.evaluate(() => { + window.addEventListener("click", (event) => { + const link = (event.target as Element).closest("a"); + if (link === null) return; + event.preventDefault(); + document.documentElement.dataset.followed = link.getAttribute("href") ?? ""; + }); + }), + ); + yield* browser.use("Press the restart link", (page) => page.keyboard.press("Enter")); + expect( + yield* browser.use("Read where it went", (page) => + page.evaluate(() => document.documentElement.dataset.followed), + ), + ).toBe("executor-update:restart"); + + // A short window drops the card's description. With a navigation longer than the window, the + // sidebar scrolls as it always has, and the card stays below the navigation. + yield* browser.use("Shorten the window", (page) => + page.setViewportSize({ width: 1180, height: 540 }), + ); + expect( + yield* browser.use("Check the short card", (page) => + page.getByText("Executor restarts to install it.").isVisible(), + ), + ).toBe(false); + yield* browser.use("Lengthen the navigation", (page) => + page.evaluate(() => { + const navigation = document.querySelector("aside.sidebar nav"); + if (navigation === null) return; + const items = [...navigation.querySelectorAll("a")]; + for (let round = 0; round < 3; round += 1) + for (const item of items) navigation.append(item.cloneNode(true)); + }), + ); + expect( + yield* browser.use("Check the sidebar scrolls", (page) => + page.evaluate(() => { + const sidebar = document.querySelector("aside.sidebar"); + return sidebar !== null && sidebar.scrollHeight > sidebar.clientHeight; + }), + ), + ).toBe(true); + expect(yield* browser.use("Place the card under a long navigation", placement)).toEqual({ + belowNavigation: true, + aboveDivider: true, + }); + yield* browser.use("Restore the navigation", (page) => page.reload()); + yield* browser.use("Wait for apps again", (page) => + page.getByRole("heading", { level: 1, name: /^Apps/ }).waitFor(), + ); + yield* browser.use("Show the ready update again", (page) => + showUpdate(page, { state: "ready", version: "2.4.0" }), + ); + + // The collapsed rail keeps it above the divider as an icon button with the same name and + // a tooltip. + yield* browser.use("Collapse the rail", (page) => + page + .setViewportSize({ width: 900, height: 800 }) + .then(() => page.getByRole("button", { name: "Expand sidebar" }).waitFor()), + ); + expect( + yield* browser.use("Check the collapsed restart button", (page) => + Promise.all([restartLink(page).isVisible(), restartLink(page).innerText()]), + ), + ).toEqual([true, ""]); + expect(yield* browser.use("Place the collapsed card", placement)).toEqual({ + belowNavigation: true, + aboveDivider: true, + }); + yield* browser.use("Focus the collapsed restart button", (page) => + restartLink(page).focus(), + ); + expect( + yield* browser.use("Read the tooltip", (page) => page.getByRole("tooltip").innerText()), + ).toBe("Restart Executor to install v2.4.0"); + // The collapsed rail's icon has no text of its own; the same region still says it. + expect(yield* browser.use("Read the collapsed announcement", announcement)).toEqual({ + count: 1, + text: "Update ready: Executor v2.4.0. Restart Executor to install it.", + }); + yield* browser.checkpoint("Update ready in the collapsed rail"); + + // When the desktop clears it, as after a failed download, the card goes away and the + // sidebar is as it was. + yield* browser.use("Widen the window", (page) => + page.setViewportSize({ width: 1180, height: 800 }), + ); + yield* browser.use("Clear the update", (page) => showUpdate(page, null)); + yield* browser.use("Wait for the update to go", (page) => + page.locator("aside.sidebar .sidebar-update").waitFor({ state: "detached" }), + ); + expect(yield* browser.use("Measure the sidebar without the update", layout)).toEqual( + without, + ); + expect(yield* browser.use("Read the cleared announcement", announcement)).toEqual({ + count: 1, + text: "", + }); + + // A long prerelease version wraps instead of being cut off, in the narrowest sidebar, which + // a window under 1,000 px wide shows when the rail is expanded: while it downloads, once + // it is ready, and in the collapsed rail's tooltip. + const long = "2.0.0-beta.123"; + yield* browser.use("Narrow the window and expand the rail", (page) => + page + .setViewportSize({ width: 960, height: 800 }) + .then(() => page.getByRole("button", { name: "Expand sidebar" }).click()) + .then(() => page.getByRole("button", { name: "Collapse sidebar" }).waitFor()), + ); + expect( + yield* browser.use("Measure the narrow sidebar", (page) => + box(page, "aside.sidebar").then((sidebar) => sidebar?.width), + ), + ).toBe(190); + yield* browser.use("Show a long downloading version", (page) => + showUpdate(page, { state: "downloading", version: long }), + ); + yield* browser.use("Wait for the long download status", (page) => + page + .locator("aside.sidebar") + .getByRole("status") + .filter({ hasText: `Downloading v${long}` }) + .waitFor(), + ); + expect(yield* browser.use("Check the long download status fits", clipped)).toEqual({ + cut: [], + outside: false, + }); + yield* browser.checkpoint("Long version downloading"); + yield* browser.use("Show a long ready version", (page) => + showUpdate(page, { state: "ready", version: long }), + ); + const longRestart = (page: Page) => + page + .locator("aside.sidebar") + .getByRole("link", { name: `Restart Executor to install v${long}` }); + yield* browser.use("Wait for the long restart button", (page) => + longRestart(page).waitFor(), + ); + expect( + yield* browser.use("Read the long card", (page) => + page + .locator("aside.sidebar .sidebar-update") + .innerText() + .then((text) => text.split("\n").filter((line) => line.trim() !== "")), + ), + ).toEqual([ + "Update ready", + `v${long}`, + "Executor restarts to install it.", + "Restart to update", + ]); + expect(yield* browser.use("Check the long ready card fits", clipped)).toEqual({ + cut: [], + outside: false, + }); + expect(yield* browser.use("Read the long announcement", announcement)).toEqual({ + count: 1, + text: `Update ready: Executor v${long}. Restart Executor to install it.`, + }); + yield* browser.checkpoint("Long version ready"); + yield* browser.use("Collapse the rail for the long version", (page) => + page + .getByRole("button", { name: "Collapse sidebar" }) + .click() + .then(() => page.getByRole("button", { name: "Expand sidebar" }).waitFor()), + ); + yield* browser.use("Focus the long collapsed restart button", (page) => + longRestart(page).focus(), + ); + expect( + yield* browser.use("Read the long tooltip", (page) => + Promise.all([ + page.getByRole("tooltip").innerText(), + page.getByRole("tooltip").evaluate((tooltip) => { + const bounds = tooltip.getBoundingClientRect(); + return bounds.right <= window.innerWidth && bounds.left >= 0; + }), + ]), + ), + ).toEqual([`Restart Executor to install v${long}`, true]); + yield* browser.checkpoint("Long version in the collapsed tooltip"); + }), + ), + ); +}); diff --git a/packages/ui/src/implementation/dashboard/shell.tsx b/packages/ui/src/implementation/dashboard/shell.tsx index 59e366853f..d7bab1344d 100644 --- a/packages/ui/src/implementation/dashboard/shell.tsx +++ b/packages/ui/src/implementation/dashboard/shell.tsx @@ -1,4 +1,4 @@ -import { useState, type ReactNode } from "react"; +import { createContext, useContext, useState, type ReactNode } from "react"; import { HugeiconsIcon } from "@hugeicons/react"; import { BookOpen01Icon, @@ -38,6 +38,11 @@ const navigationClass = const collapsedClass = "[&_.sidebar-header]:justify-center [&_.wordmark]:hidden [&_nav_a]:justify-center [&_nav_a]:gap-0! [&_nav_a]:px-0! [&_nav_a]:h-9 [&_nav_a]:text-[0px]! [&_nav_a_>_span]:hidden [&_.sidebar-resource-links]:items-center [&_.sidebar-resource-links]:px-0 [&_.sidebar-resource-links_a]:w-full [&_.sidebar-resource-links_a]:justify-center [&_.sidebar-resource-links_a]:min-h-8 [&_.sidebar-resource-links_a_>_span]:hidden [&_.sidebar-resource-links_button]:w-full [&_.sidebar-resource-links_button]:justify-center [&_.sidebar-resource-links_button]:min-h-8 [&_.sidebar-resource-links_button_>_span]:hidden [&_.hosted-identity]:px-0 [&_.organization-trigger]:justify-center [&_.organization-trigger]:px-0 [&_.organization-name]:hidden [&_.organization-chevron]:hidden [&_.session-menu]:justify-center [&_.session-menu]:px-0 [&_.session-name]:hidden [&_.sidebar-version]:hidden"; +const SidebarCollapsed = createContext(false); + +/** Whether the sidebar is the icon rail, for a notice that renders a compact form there. */ +export const useSidebarCollapsed = () => useContext(SidebarCollapsed); + /** Links and the optional support trigger share one compact style. */ function ResourceLinks({ docsUrl, @@ -83,7 +88,10 @@ export function DashboardShell({ readonly banner?: ReactNode; /** A product-owned way to reach the team, shown with the resource links. */ readonly support?: ReactNode; - /** A small product-owned card above the resource links; the icon rail hides it. */ + /** + * A small product-owned card above the resource links' divider, also in the icon rail, where + * it reads `useSidebarCollapsed` to render a compact form. Pass nothing when there is none. + */ readonly notice?: ReactNode; readonly footer?: ReactNode; readonly children: ReactNode; @@ -132,9 +140,13 @@ export function DashboardShell({ {brand} - {notice && !collapsed &&
{notice}
} + {notice && ( +
+ {notice} +
+ )}
{footer} diff --git a/scripts/releases/desktop.ts b/scripts/releases/desktop.ts index 16b6b8dc37..d3d589fafe 100644 --- a/scripts/releases/desktop.ts +++ b/scripts/releases/desktop.ts @@ -13,6 +13,17 @@ import { desktopRuntimeBuildFile, } from "../../apps/local/desktop/src/contracts/desktop.ts"; +/** + * Development-only desktop code, which `build.mjs --release` leaves out of the bundle. The bundled + * electron-updater defines `forceDevUpdateConfig` itself, so the check names the desktop's use of it. + */ +const developmentOnly = [ + "EXECUTOR_DESKTOP_DEV_UPDATE_CONFIG", + "autoUpdater.forceDevUpdateConfig", + "autoUpdater.updateConfigPath", + "development-updates", +]; + const build = Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -83,10 +94,16 @@ const build = Effect.gen(function* () { build: Hex.encode(crypto.getRandomValues(new Uint8Array(6))), }), ); - yield* run("node", ["apps/local/desktop/scripts/build.mjs"], root); + yield* run("node", ["apps/local/desktop/scripts/build.mjs", "--release"], root); // The main entry and the server starter it runs in a utility process. - for (const entry of ["main.cjs", "starter.cjs"]) + for (const entry of ["main.cjs", "starter.cjs"]) { yield* fs.copyFile(path.join(root, "apps/local/desktop/dist", entry), path.join(stage, entry)); + // A development override that names where updates come from must not exist in a release. + const bundled = yield* fs.readFileString(path.join(stage, entry)); + for (const development of developmentOnly) + if (bundled.includes(development)) + return yield* Effect.die(new Error(`The release ${entry} contains ${development}`)); + } yield* fs.writeFileString( path.join(stage, "package.json"), JSON.stringify({ From b85898541e7af4948c3762d2a10f5a99e185af9c Mon Sep 17 00:00:00 2001 From: Rhys Sullivan <39114868+RhysSullivan@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:16:11 +0000 Subject: [PATCH 07/68] Export 0b10ece5 --- .../pages/connection-dialog.tsx | 2 +- .../src/implementation/pages/app-accounts.tsx | 4 +- e2e/test-plan.ts | 21 ++ e2e/tests/account-check-failures.spec.ts | 12 +- e2e/tests/account-secret-fields.spec.ts | 4 +- e2e/tests/connect-form-layout.spec.ts | 311 ++++++++++++++++++ .../components/credential-fields.tsx | 2 +- .../implementation/dashboard/account-form.tsx | 92 ++++-- 8 files changed, 401 insertions(+), 47 deletions(-) create mode 100644 e2e/tests/connect-form-layout.spec.ts diff --git a/apps/hosted/web/src/implementation/pages/connection-dialog.tsx b/apps/hosted/web/src/implementation/pages/connection-dialog.tsx index 1ef3c92917..e4672b23dd 100644 --- a/apps/hosted/web/src/implementation/pages/connection-dialog.tsx +++ b/apps/hosted/web/src/implementation/pages/connection-dialog.tsx @@ -58,7 +58,7 @@ export function ConnectionDialogHeader({
- + {action} {provider.definition.name} diff --git a/apps/local/web/src/implementation/pages/app-accounts.tsx b/apps/local/web/src/implementation/pages/app-accounts.tsx index d4a0723576..ccbe9b0df9 100644 --- a/apps/local/web/src/implementation/pages/app-accounts.tsx +++ b/apps/local/web/src/implementation/pages/app-accounts.tsx @@ -157,7 +157,9 @@ export function AppAccounts({ }} > - Connect {connection?.requirement.definition.name} + + Connect {connection?.requirement.definition.name} + Connect an account for {app.name}. diff --git a/e2e/test-plan.ts b/e2e/test-plan.ts index 78cb1ce95d..848eb67116 100644 --- a/e2e/test-plan.ts +++ b/e2e/test-plan.ts @@ -5009,6 +5009,27 @@ export const scenarios = plan({ local: na("The hosted and local dashboards share the credential form and check contract."), }, }, + connectFormLongLabel: { + fixtures: "actors", + file: "connect-form-layout.spec.ts", + title: + "The connect form keeps a paragraph-long sign-in method label, an unbroken field title and a long host list inside its dialog at desktop and phone widths, and its submit button says Validate and keeps its accessible name while the form announces the check once", + targets: { + "self-host": scheduled, + cloud: na("Self-host renders the same hosted connect dialog and shared form."), + local: na("The local dialog has its own scenario."), + }, + }, + localConnectFormLongLabel: { + file: "connect-form-layout.spec.ts", + title: + "The local connect dialog keeps a paragraph-long sign-in method label and a long host list inside it at desktop and phone widths", + targets: { + local: scheduled, + "self-host": na("The hosted connect dialog has its own scenario."), + cloud: na("The hosted connect dialog has its own scenario."), + }, + }, accountSecretFieldsExact: { fixtures: "actors", file: "account-secret-fields.spec.ts", diff --git a/e2e/tests/account-check-failures.spec.ts b/e2e/tests/account-check-failures.spec.ts index a67b72d07b..2a415bb0b0 100644 --- a/e2e/tests/account-check-failures.spec.ts +++ b/e2e/tests/account-check-failures.spec.ts @@ -81,7 +81,7 @@ export default defineApp({ user: { accounts: { service } } }, async () => ({ too response.request().method() === "POST" && new URL(response.url()).pathname.endsWith("/credential-checks"), ), - connect.getByRole("button", { name: "Validate API key", exact: true }).click(), + connect.getByRole("button", { name: "Validate", exact: true }).click(), ]), ) .then(([response]) => response.json() as Promise), @@ -114,8 +114,8 @@ export default defineApp({ user: { accounts: { service } } }, async () => ({ too }); // The check is the app's own code, so the form says it may be wrong and saving stays open. expect(yield* verdict("The form shows the app's explanation")).toBe( - "Couldn't verify this API key: 403: token [redacted] lacks the accounts scope\n" + - "The app's check may be wrong. You can still add this API key and ask your agent to fix the check.\n" + + "Couldn't verify these credentials: 403: token [redacted] lacks the accounts scope\n" + + "The app's check may be wrong. You can still add these credentials and ask your agent to fix the check.\n" + "Copy fix prompt", ); yield* browser.checkpoint("App explains why the check failed"); @@ -133,11 +133,11 @@ export default defineApp({ user: { accounts: { service } } }, async () => ({ too ); expect(prompt).toBe( [ - `The account check in my Executor app (app ID: ${app.id}) failed for my Check fixture API key, and the check itself may be wrong.`, + `The account check in my Executor app (app ID: ${app.id}) failed for my Check fixture credentials (sign-in method: API key), and the check itself may be wrong.`, "", - "The check reported: Couldn't verify this API key: 403: token [redacted] lacks the accounts scope", + "The check reported: Couldn't verify these credentials: 403: token [redacted] lacks the accounts scope", "", - "Start with the Executor app's executor skill. Read the app's source, find the health check for the Check fixture provider, and fix it so it accepts a working API key and still rejects a bad one. Deploy the updated app. Don't ask me to paste the API key into chat.", + "Start with the Executor app's executor skill. Read the app's source, find the health check for the Check fixture provider, and fix it so it accepts working credentials and still rejects bad ones. Deploy the updated app. Don't ask me to paste the credentials into chat.", ].join("\n"), ); expect(prompt).not.toContain(missingScope); diff --git a/e2e/tests/account-secret-fields.spec.ts b/e2e/tests/account-secret-fields.spec.ts index 706dc46405..fe952c3b14 100644 --- a/e2e/tests/account-secret-fields.spec.ts +++ b/e2e/tests/account-secret-fields.spec.ts @@ -225,7 +225,7 @@ layer(HostedLive, { excludeTestServices: true })("Account secret fields", (it) = response.request().method() === "POST" && new URL(response.url()).pathname.endsWith("/credential-checks"), ), - connect.getByRole("button", { name: "Validate API key", exact: true }).click(), + connect.getByRole("button", { name: "Validate", exact: true }).click(), ]).then(([response]) => response.json() as Promise), ) .pipe(Effect.flatMap(Schema.decodeUnknownEffect(Check))); @@ -284,7 +284,7 @@ layer(HostedLive, { excludeTestServices: true })("Account secret fields", (it) = request.method() === "POST" && new URL(request.url()).pathname.endsWith("/credential-checks"), ), - connect.getByRole("button", { name: "Validate API key", exact: true }).click(), + connect.getByRole("button", { name: "Validate", exact: true }).click(), ]).then(([request]) => connect .getByRole("button", { name: /^Continue/ }) diff --git a/e2e/tests/connect-form-layout.spec.ts b/e2e/tests/connect-form-layout.spec.ts new file mode 100644 index 0000000000..72186f0459 --- /dev/null +++ b/e2e/tests/connect-form-layout.spec.ts @@ -0,0 +1,311 @@ +/** + * The connect form stays inside its dialog whatever an app declares: a sign-in method label as + * long as a paragraph, an unbroken field title and a long list of hosts wrap or truncate instead of + * widening the form, and the submit button says "Validate" rather than repeating the label. While + * the check runs, the button keeps an accessible name and the form announces the check once. + */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Redacted, Schema } from "effect"; +import { randomUUID } from "node:crypto"; +import type { Locator } from "playwright"; +import { Actors } from "../support/actors.ts"; +import { Api, body } from "../support/api.ts"; +import { Browser } from "../support/browser.ts"; +import { HostedLive, TestLive, withCase, withHostedCase } from "../support/case.ts"; +import { App } from "../support/contracts.ts"; +import { Target } from "../support/platform.ts"; +import { scenarios } from "../test-plan.ts"; +import { appsManifest } from "../support/apps-release.ts"; + +const products = [ + "email-reputation", + "phone-intelligence", + "ip-intelligence", + "ip-geolocation", + "company-enrichment", + "iban-validation", + "vat-validation", + "exchange-rates", + "holidays", + "timezones", + "scrape", + "images", +]; +/** 219 characters, as a catalog app once declared. */ +const longLabel = `API key for one Abstract product (product: ${products.join(", ")})`; +const longTitle = "Product_identifier_written_as_one_unbroken_word_that_never_wraps_by_itself"; + +/** A provider with a paragraph for a label, an unbroken field title and twelve long hosts. */ +const source = (name: string) => ` +import { defineApp, defineProvider, object, plain, router, secrets, string } from "apps"; +const service = defineProvider({ + name: ${JSON.stringify(name)}, + hosts: ${JSON.stringify(products.map((product) => `${product}.a-long-regional-subdomain-for-layout.example.com`))}, + auth: { + key: secrets({ + label: ${JSON.stringify(longLabel)}, + fields: object({ + product: plain(string({ minLength: 1, title: ${JSON.stringify(longTitle)} })), + token: string({ minLength: 1 }), + }), + }), + personal: secrets({ label: "Personal access token", fields: object({ token: string() }) }), + }, + async health() { + throw new Error("403: the token lacks the accounts scope"); + }, +}); +export default defineApp({ user: { accounts: { service } } }, async () => ({ tools: router({}) })); +`; + +/** The local deploy route answers with the app under `app`. */ +const Deployed = Schema.Struct({ app: App }); + +/** + * Elements of the dialog that reach past its left or right edge, and how far its content scrolls + * sideways. Vertical overflow is the dialog's own scrolling and is allowed. + */ +const outside = (dialog: Locator) => + dialog.evaluate((element) => { + const edge = element.getBoundingClientRect(); + const sticking = [...element.querySelectorAll("*")].flatMap((child) => { + const box = child.getBoundingClientRect(); + if (box.width === 0 && box.height === 0) return []; + return box.left < edge.left - 0.5 || box.right > edge.right + 0.5 + ? [`${child.tagName.toLowerCase()} "${(child.textContent ?? "").slice(0, 60)}"`] + : []; + }); + return { sticking, sideways: element.scrollWidth - element.clientWidth }; + }); + +/** + * Each outermost live region in the dialog that holds text, with its politeness and its text, hidden + * text included. A region inside another, such as a copy button's own feedback, is part of it. + * `role="status"` is polite. + */ +const liveRegions = (dialog: Locator) => + dialog.evaluate((element) => { + const selector = "[aria-live], [role=status], [role=alert]"; + return [...element.querySelectorAll(selector)].flatMap((region) => { + if (region.parentElement?.closest(selector) !== null) return []; + const walker = document.createTreeWalker(region, NodeFilter.SHOW_TEXT); + const parts: string[] = []; + while (walker.nextNode()) parts.push(walker.currentNode.textContent ?? ""); + const text = parts.join(" ").replace(/\s+/g, " ").trim(); + if (text === "") return []; + const role = region.getAttribute("role"); + const live = + region.getAttribute("aria-live") ?? + (role === "alert" ? "assertive" : role === "status" ? "polite" : "off"); + return [{ live, text }]; + }); + }); + +/** The open connect dialog fits at the browser's width and at a phone's, with a short submit button. */ +const fitsAtBothWidths = (dialog: Locator) => + Effect.gen(function* () { + const browser = yield* Browser; + for (const [width, height] of [ + [1280, 900], + [390, 844], + ] as const) { + yield* browser.use(`Resize to ${width} pixels wide`, (page) => + page.setViewportSize({ width, height }), + ); + yield* browser.checkpoint(`Connect form at ${width} pixels`); + expect( + yield* browser.use(`Nothing sticks out at ${width} pixels`, () => outside(dialog)), + ).toEqual({ sticking: [], sideways: 0 }); + expect( + yield* browser.use("The submit button says Validate", () => + dialog.locator("button[type=submit]").innerText(), + ), + ).toBe("Validate"); + } + }); + +layer(HostedLive, { excludeTestServices: true })("Connect form layout", (it) => { + it.effect(scenarios.connectFormLongLabel.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const actors = yield* Actors; + const api = yield* Api; + const browser = yield* Browser; + const prefix = `/api/organizations/${actors.organization.id}`; + const name = `Layout fixture ${randomUUID().slice(0, 8)}`; + const deployed = yield* api.request(actors.owner, "POST", `${prefix}/apps/deploy`, { + name, + files: [{ path: "index.ts", content: source(name) }, appsManifest], + }); + expect(deployed.status, JSON.stringify(deployed.body)).toBe(200); + const app = yield* body(App, deployed); + yield* Effect.addFinalizer(() => + api.request(actors.owner, "DELETE", `${prefix}/apps/${app.id}`).pipe( + Effect.map((response) => expect(response.status).toBe(200)), + Effect.orDie, + ), + ); + + yield* browser.login(actors.owner); + yield* browser.use("Open the app's accounts", (page) => + page.goto(`/org/${actors.organization.slug}/apps/${app.id}?view=accounts`), + ); + yield* browser.use("Connect a new account", (page) => + page.getByRole("button", { name: "Connect new account", exact: true }).click(), + ); + const connect = yield* browser.use("The connection dialog opens", (page) => { + const dialog = page.getByRole("dialog", { name: `Connect ${name}`, exact: true }); + return dialog.waitFor({ state: "visible" }).then(() => dialog); + }); + yield* fitsAtBothWidths(connect); + + // The method menu is as wide as its field, and the long name wraps inside it. + // An open menu hides the dialog from the accessibility tree, so measure the field first. + const field = yield* browser.use("Measure the sign-in method field", () => + connect.getByRole("combobox").boundingBox(), + ); + const [menu, listed] = yield* browser.use("Open the sign-in method menu", (page) => + connect + .getByRole("combobox") + .click() + .then(() => page.getByRole("listbox").waitFor({ state: "visible" })) + .then(() => + Promise.all([ + page.getByRole("listbox").boundingBox(), + page.getByRole("option", { name: longLabel, exact: true }).isVisible(), + ]), + ), + ); + expect(listed).toBe(true); + expect(menu?.width).toBeLessThanOrEqual((field?.width ?? 0) + 0.5); + yield* browser.checkpoint("The method menu wraps a long name"); + yield* browser.use("Close the menu", (page) => page.keyboard.press("Escape")); + + // While the check runs, the button keeps its name and the form's one live region says + // "Validating…"; the result then replaces it there. The check is held until both are seen. + let release = () => {}; + const held = new Promise((resolve) => (release = resolve)); + yield* browser.use("Hold the account check", (page) => + page.route( + (url) => url.pathname.endsWith("/credential-checks"), + (route) => held.then(() => route.continue()), + ), + ); + yield* browser.use("Fill and validate the credentials", () => + connect + .getByLabel(longTitle, { exact: true }) + .fill("email-reputation") + .then(() => connect.getByLabel("Token", { exact: true }).fill("synthetic-layout-token")) + .then(() => connect.getByRole("button", { name: "Validate", exact: true }).click()), + ); + yield* browser.use("The button is named Validating… while the check runs", () => + connect.getByRole("button", { name: "Validating…", exact: true }).waitFor(), + ); + // The spinner's own "Loading" name stays out of what the button announces. + expect( + yield* browser.use("The submit button as assistive technology reads it", () => + connect.locator("button[type=submit]").ariaSnapshot(), + ), + ).toBe('- button "Validating…" [disabled]'); + expect( + yield* browser.use("What the form's live regions say while checking", () => + liveRegions(connect), + ), + ).toEqual([{ live: "polite", text: "Validating…" }]); + yield* browser.checkpoint("Validating"); + const [response] = yield* browser.use("Let the check finish", (page) => + Promise.all([ + page.waitForResponse((response) => + new URL(response.url()).pathname.endsWith("/credential-checks"), + ), + Promise.resolve().then(release), + ]), + ); + expect(response.status()).toBe(200); + expect( + yield* browser.use("The check's result", () => + connect + .locator('[data-credential-check="check_failed"]') + .waitFor({ state: "visible" }) + .then(() => + connect + .locator('[data-credential-check="check_failed"] > div > span') + .first() + .innerText(), + ), + ), + ).toBe("Couldn't verify these credentials: 403: the token lacks the accounts scope"); + const after = yield* browser.use("What the form's live regions say after the check", () => + liveRegions(connect), + ); + expect(after.map(({ live }) => live)).toEqual(["polite"]); + expect(after[0]?.text).toMatch( + /^Couldn't verify these credentials: 403: the token lacks the accounts scope The app's check may be wrong\./, + ); + expect(after[0]?.text).not.toContain("Validating"); + expect( + yield* browser.use("The button is named for what it does next", () => + connect.getByRole("button", { name: "Continue anyway", exact: true }).count(), + ), + ).toBe(1); + expect( + yield* browser.use("Nothing sticks out after the check", () => outside(connect)), + ).toEqual({ sticking: [], sideways: 0 }); + yield* browser.checkpoint("The check result wraps inside the dialog"); + }), + ), + ); +}); + +layer(TestLive, { excludeTestServices: true })("Local connect form layout", (it) => { + it.effect(scenarios.localConnectFormLongLabel.title, (context) => + withCase( + context, + Effect.gen(function* () { + const api = yield* Api; + const browser = yield* Browser; + const target = yield* Target; + const session = yield* api.session(); + const headers = { authorization: `Bearer ${Redacted.value(target.apiKey)}` }; + const name = `Local layout fixture ${randomUUID().slice(0, 8)}`; + const deployed = yield* session.send( + "POST", + "/v1/apps/deploy", + { + owner: "local", + name, + files: [{ path: "index.ts", content: source(name) }, appsManifest], + }, + headers, + ); + expect(deployed.status, JSON.stringify(deployed.body)).toBe(200); + const { app } = yield* body(Deployed, deployed); + yield* Effect.addFinalizer(() => + session.send("DELETE", `/v1/apps/${app.id}`, undefined, headers).pipe( + Effect.map((response) => expect(response.status).toBe(200)), + Effect.orDie, + ), + ); + const pairing = yield* session.send("POST", "/auth/pair", undefined, headers); + expect(pairing.status).toBe(200); + const { url } = yield* body(Schema.Struct({ url: Schema.String }), pairing); + yield* browser.use("Pair the local browser", (page) => page.goto(url)); + yield* browser.use("The paired inventory is visible", (page) => + page.getByRole("heading", { name: /^Apps/ }).waitFor({ state: "visible" }), + ); + yield* browser.use("Open the app's accounts", (page) => + page.goto(`/apps/${app.id}?view=accounts`), + ); + yield* browser.use("Connect a new account", (page) => + page.getByRole("button", { name: "Connect new account", exact: true }).click(), + ); + const connect = yield* browser.use("The connection dialog opens", (page) => { + const dialog = page.getByRole("dialog", { name: `Connect ${name}`, exact: true }); + return dialog.waitFor({ state: "visible" }).then(() => dialog); + }); + yield* fitsAtBothWidths(connect); + }), + ), + ); +}); diff --git a/packages/ui/src/implementation/components/credential-fields.tsx b/packages/ui/src/implementation/components/credential-fields.tsx index 760b45c73a..402f88b097 100644 --- a/packages/ui/src/implementation/components/credential-fields.tsx +++ b/packages/ui/src/implementation/components/credential-fields.tsx @@ -171,7 +171,7 @@ export function CredentialFields({