diff --git a/CHANGELOG.md b/CHANGELOG.md index 881ac38..e772677 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 0.15.0 (unreleased) + +`Convex.HubClient` registers a deployment as a client of the identity hub of the team, with the +Convex credential of the stack. It replaces `IdentityHub.Client` of +`@samebase/alchemy-identity-hub`, which needed a registration token and the address of the hub. A +client that a stack registered with the old resource stays: the resource type is the same, and a +deploy with the same redirect URI stores the new props and does not reach the hub. The first deploy +needs a hub with `@samebase/identity-broker` 0.7.0. + +The command `alchemy-convex hub-client` does the same for a development deployment. + ## 0.14.1 (unreleased) A base app compiles the exported store functions under its own tsconfig. `reader:repository` reads diff --git a/README.md b/README.md index a4a8945..0a1bf98 100644 --- a/README.md +++ b/README.md @@ -283,6 +283,24 @@ call. as the build inputs `["src/**", "public/**", "vite.config.ts"]`. A minted key for a command has every action, because the command can do more than a push. +- `Convex.HubClient`: `{ team, app, redirectUri, deploymentType, clientName, softwareVersion? }` + registers one deployment as a client of the identity hub of the team. The hub is in the base of the + team, the production deployment of the project `samebase`. The resource finds it by name and runs + its internal function `identityBroker:registerClient` with a short-lived key, so the stack needs no + other credential and no hub address. The first client of an `app` creates the app. Outputs + `issuer`, `clientId`, `clientSecret`, `redirectUri`, `deploymentType`, and `clientName`, which the + `env` of the `Convex.Deployment` writes to the deployment. Another `redirectUri` is a new client, and + a destroy deletes the client. + +A development deployment has no stack, so the package has a command for it. Run it in the directory +of the app, before the first push: it registers the deployment of that directory with +`CONVEX_ACCESS_TOKEN` or the Convex CLI login, and writes `HUB_ISSUER`, `HUB_CLIENT_ID`, and +`HUB_CLIENT_SECRET` to it. A deployment with all three variables keeps them. + +```sh +npx alchemy-convex hub-client --team my-team --app scout --callback-path /auth/hub/callback +``` + ## Data safety - `Convex.Project` and `Convex.Deployment` have the removal policy `retain`. `alchemy destroy` diff --git a/docs/design/convex-plane.md b/docs/design/convex-plane.md index 2cc90d1..b26cbea 100644 --- a/docs/design/convex-plane.md +++ b/docs/design/convex-plane.md @@ -8,9 +8,9 @@ Problem: 0.3 is shaped for Workers Builds: keys go to a build outside Alchemy, ` ## Decision: adopt the 408 model, keep our implementation, do not vendor or depend -- Resources: `Convex.Project` and `Convex.Deployment({ project, type, name?, source?, env? })`. The - push of `source` happens inside the deployment update, and `url` and `siteUrl` flow to other - resources. Reason: this is the 408 model, and it puts no key between resources. +- Resources: `Convex.Project`, `Convex.HubClient`, and + `Convex.Deployment({ project, type, name?, source?, env? })`. The push of `source` happens inside + the deployment update, and `url` and `siteUrl` flow to other resources. Reason: this is the 408 model, and it puts no key between resources. - Not vendored: 735 keeps a separate `Code` that pushes on every apply (`Code.ts:34`), passes keys between resources, creates a new production deployment by reference and can delete it, writes Alchemy state through internal APIs (`internal/Lifecycle.ts`), and pins beta.82 and TypeScript 7. diff --git a/package.json b/package.json index 0534c3a..d90ee7e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@samebase/alchemy-convex", - "version": "0.14.1", + "version": "0.15.0", "description": "The Convex plane for Alchemy v2: projects, deployments, environment variables, and the push of the functions", "keywords": [ "alchemy", @@ -18,6 +18,9 @@ "type": "git", "url": "git+https://github.com/samebase/alchemy-convex.git" }, + "bin": { + "alchemy-convex": "./lib/cli.js" + }, "files": [ "lib", "src", diff --git a/src/HubClient.ts b/src/HubClient.ts new file mode 100644 index 0000000..4f49d82 --- /dev/null +++ b/src/HubClient.ts @@ -0,0 +1,258 @@ +// Convex.HubClient: one deployment of an app as a client of the identity hub +// of its team. +// +// The hub is an app in the base of the team, the production deployment of the +// project `samebase`, the project that holds the state of the team. It has +// the internal functions of `@samebase/identity-broker` in its module +// `identityBroker`. This resource finds the base by name and runs those +// functions with a short-lived key, so a stack that has the Convex credential +// of the team needs no other credential and no hub address. The hub answers +// with its issuer and the client. +// +// The hub keeps only the hash of the secret, so the state is the only record +// of it. A client belongs to one redirect URI: another URI is a new client. A +// change of `app` updates the stored props and does not move the client: the +// app is the identity of the users of the app, and it does not change. The +// team does not change either: the state of a stack is in the base of its team. +import { Resource } from "alchemy"; +import { isResolved } from "alchemy/Diff"; +import * as Provider from "alchemy/Provider"; +import * as Effect from "effect/Effect"; +import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; +import { ManagementApi, type ManagementApiService } from "./ManagementApi.ts"; +import { findProjectByName, prodDeploymentOf } from "./Project.ts"; +import type { Providers } from "./Providers.ts"; +import { withPushKey } from "./Push.ts"; +import { type FunctionApi, makeFunctionApi, RUN_KEY_ACTIONS, STORE_PROJECT_NAME } from "./State.ts"; + +export type HubDeploymentType = "production" | "development" | "preview"; + +export interface HubClientProps { + /** The Convex team, a slug or an id, whose project `samebase` holds the hub. */ + readonly team: string | number; + /** The app on the hub, such as `scout`. The first client of an app creates it, as a first-party app. */ + readonly app: string; + /** The deployment's callback URL, such as `/auth/hub/callback`. */ + readonly redirectUri: string; + readonly deploymentType: HubDeploymentType; + /** The name the hub records for the client. */ + readonly clientName: string; + /** Recorded on the hub's client, such as the commit. The hub records "unknown" without it. */ + readonly softwareVersion?: string; +} + +export interface HubClientAttributes { + /** The issuer of the hub, which the deployment names to sign in. */ + readonly issuer: string; + readonly redirectUri: string; + readonly deploymentType: HubDeploymentType; + /** The name the client was registered with. */ + readonly clientName: string; + readonly clientId: string; + /** Returned by the hub only at registration. */ + readonly clientSecret: Redacted.Redacted; +} + +export type HubClient = Resource< + "IdentityHub.Client", + HubClientProps, + HubClientAttributes, + never, + Providers +>; +export const HubClient = Resource("IdentityHub.Client"); + +/** The base of the team could not do the call. The reason is the Convex message: it holds no secret. */ +export class HubClientFailed extends Schema.TaggedError()("HubClientFailed", { + team: Schema.Union([Schema.String, Schema.Number]), + reason: Schema.String, +}) { + override get message() { + return `Convex.HubClient: the base of team ${this.team}: ${this.reason}.`; + } +} + +/** The reply of `identityBroker:registerClient`. */ +const Registered = Schema.Struct({ + issuer: Schema.NonEmptyString, + clientId: Schema.NonEmptyString, + clientSecret: Schema.NonEmptyString, +}); + +/** Runs `use` with the function API of the base of `team`, with a key of this call only. */ +const withBase = ( + api: ManagementApiService, + team: string | number, + use: (functions: FunctionApi) => Effect.Effect, +) => + Effect.gen(function* () { + const teamId = yield* api.resolveTeamId(team); + const project = yield* findProjectByName(api, teamId, STORE_PROJECT_NAME); + if (project === undefined) { + return yield* new HubClientFailed({ + team, + reason: `no project ${STORE_PROJECT_NAME}, which holds the hub`, + }); + } + const deployment = yield* prodDeploymentOf(api, project.id); + if (deployment === undefined) { + return yield* new HubClientFailed({ + team, + reason: `project ${STORE_PROJECT_NAME} has no production deployment`, + }); + } + return yield* withPushKey(api, deployment.name, RUN_KEY_ACTIONS, (key) => + use(makeFunctionApi(deployment.deploymentUrl, key)), + ); + }); + +/** One internal function of the hub: its value, or the Convex message as an error. */ +const runHub = ( + functions: FunctionApi, + team: string | number, + name: string, + args: Record, +) => + functions.call(`identityBroker:${name}`, args).pipe( + Effect.mapError((error) => new HubClientFailed({ team, reason: error.message })), + Effect.flatMap((reply) => + reply.status === "success" + ? Effect.succeed(reply.value) + : Effect.fail(new HubClientFailed({ team, reason: reply.errorMessage.trim() })), + ), + ); + +/** + * Registers one client. An attempt that a lost reply repeats leaves one spare + * client on the hub, which signs nobody in. + */ +export const registerHubClient = (api: ManagementApiService, props: HubClientProps) => + withBase(api, props.team, (functions) => + runHub(functions, props.team, "registerClient", { + appId: props.app, + redirectUri: props.redirectUri, + deploymentType: props.deploymentType, + clientName: props.clientName, + softwareVersion: props.softwareVersion ?? "unknown", + // Convex Auth's generic OAuth method posts the client credentials in the body. + tokenEndpointAuthMethod: "client_secret_post", + }), + ).pipe( + Effect.flatMap((value) => + Schema.decodeUnknownEffect(Registered)(value).pipe( + Effect.mapError( + () => new HubClientFailed({ team: props.team, reason: "registerClient gave no client" }), + ), + ), + ), + Effect.map(({ issuer, clientId, clientSecret }) => ({ + issuer, + clientId, + clientSecret: Redacted.make(clientSecret), + })), + ); + +const unregister = (api: ManagementApiService, team: string | number, clientId: string) => + withBase(api, team, (functions) => runHub(functions, team, "deleteClient", { clientId })); + +/** True when the client in state serves the redirect URI and deployment type of `props`. */ +const registeredFor = (output: HubClientAttributes, props: HubClientProps) => + output.redirectUri === props.redirectUri && output.deploymentType === props.deploymentType; + +export const HubClientProvider = () => + Provider.effect( + HubClient, + Effect.gen(function* () { + const api = yield* ManagementApi; + return { + diff: ({ news, olds, output }) => + Effect.succeed( + // Props that are unresolved at plan time, such as a redirectUri from a deployment that + // this run creates, are compared in reconcile. + !isResolved(news) || output === undefined + ? undefined + : !registeredFor(output, news) + ? ({ action: "replace" } as const) + : olds.team === news.team && olds.app === news.app + ? ({ action: "noop" } as const) + : ({ action: "update" } as const), + ), + + read: ({ output }) => Effect.succeed(output), + + reconcile: Effect.fn(function* ({ news, output }) { + if (output !== undefined && registeredFor(output, news)) return output; + const client = yield* registerHubClient(api, news); + // An update whose props were unresolved at plan time registers in place of a + // replacement. The new client is returned whatever happens to the old one. + if (output !== undefined) { + yield* unregister(api, news.team, output.clientId).pipe( + Effect.catchTag("HubClientFailed", (error) => + Effect.logWarning( + `Client ${output.clientId} stays on the hub: ${error.message} Delete it with \`npx convex run --prod identityBroker:deleteClient\`.`, + ), + ), + ); + } + return { + ...client, + redirectUri: news.redirectUri, + deploymentType: news.deploymentType, + clientName: news.clientName, + }; + }), + + delete: ({ olds, output }) => + unregister(api, olds.team, output.clientId).pipe(Effect.asVoid), + }; + }), + ); + +export interface DevelopmentClientOptions { + readonly team: string | number; + readonly app: string; + /** The path of the hub's callback after the site URL of the deployment. */ + readonly callbackPath: string; + /** Runs the Convex CLI on the deployment of this directory, and answers its output. */ + readonly convex: (args: readonly string[], input?: string) => string; +} + +/** The variables that a deployment reads to sign in through the hub. */ +const HUB_VARIABLES = ["HUB_ISSUER", "HUB_CLIENT_ID", "HUB_CLIENT_SECRET"]; + +/** + * `alchemy-convex hub-client`: a stack deploys production and previews, and this covers the + * development deployment, which no stack deploys. A deployment with all three variables keeps + * them. So a deployment that holds placeholder values for a checkout without a hub is left alone. + * The secret reaches the Convex CLI on standard input, never in its arguments. + */ +export const registerDevelopmentClient = (options: DevelopmentClientOptions) => + Effect.gen(function* () { + const { convex } = options; + const names = convex(["env", "list", "--names-only"]).split("\n"); + if (HUB_VARIABLES.every((name) => names.includes(name))) return undefined; + const siteUrl = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.String))( + convex(["run", "--inline-query", "process.env.CONVEX_SITE_URL"]), + ).pipe( + Effect.mapError( + () => new HubClientFailed({ team: options.team, reason: "no CONVEX_SITE_URL to register" }), + ), + ); + const callbackUrl = `${siteUrl.replace(/\/$/, "")}${options.callbackPath}`; + const client = yield* registerHubClient(yield* ManagementApi, { + team: options.team, + app: options.app, + redirectUri: callbackUrl, + deploymentType: "development", + clientName: "development", + softwareVersion: new URL(siteUrl).host, + }); + // One request, so that an interrupted run cannot leave half a client. `--force` replaces the + // values of an earlier one. + convex( + ["env", "set", "--force"], + `HUB_ISSUER='${client.issuer}'\nHUB_CLIENT_ID='${client.clientId}'\nHUB_CLIENT_SECRET='${Redacted.value(client.clientSecret)}'\n`, + ); + return callbackUrl; + }); diff --git a/src/Providers.ts b/src/Providers.ts index e87e3b1..84db70e 100644 --- a/src/Providers.ts +++ b/src/Providers.ts @@ -4,6 +4,7 @@ import * as Provider from "alchemy/Provider"; import * as Layer from "effect/Layer"; import { type Credentials, fromConfig } from "./Credentials.ts"; import { DeploymentProvider, DeploymentResource } from "./Deployment.ts"; +import { HubClient, HubClientProvider } from "./HubClient.ts"; import { ManagementApiLive } from "./ManagementApi.ts"; import { Project, ProjectProvider } from "./Project.ts"; @@ -15,8 +16,8 @@ export class Providers extends Provider.ProviderCollection()("Convex" * `CONVEX_DEPLOY_KEY`). */ export const providers = (credentials: Layer.Layer = fromConfig()) => - Layer.effect(Providers, Provider.collection([Project, DeploymentResource])).pipe( - Layer.provide(Layer.mergeAll(ProjectProvider(), DeploymentProvider())), + Layer.effect(Providers, Provider.collection([Project, DeploymentResource, HubClient])).pipe( + Layer.provide(Layer.mergeAll(ProjectProvider(), DeploymentProvider(), HubClientProvider())), Layer.provide(ManagementApiLive()), Layer.provide(credentials), Layer.orDie, diff --git a/src/cli.ts b/src/cli.ts new file mode 100644 index 0000000..07f9815 --- /dev/null +++ b/src/cli.ts @@ -0,0 +1,62 @@ +#!/usr/bin/env node +// The command of the package: +// +// alchemy-convex hub-client --team --app --callback-path +// +// It runs in the directory of a Convex app, and gives the development deployment of that directory +// a client of the identity hub of the team: see registerDevelopmentClient. It uses +// CONVEX_ACCESS_TOKEN or the Convex CLI login. +import { execFileSync } from "node:child_process"; +import { parseArgs } from "node:util"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { fromConfig } from "./Credentials.ts"; +import { registerDevelopmentClient } from "./HubClient.ts"; +import { ManagementApiLive } from "./ManagementApi.ts"; +import { installedCli } from "./Push.ts"; + +const { positionals, values } = parseArgs({ + allowPositionals: true, + options: { + team: { type: "string" }, + app: { type: "string" }, + "callback-path": { type: "string" }, + }, +}); +const { team, app, "callback-path": callbackPath } = values; +if ( + positionals.join(" ") !== "hub-client" || + team === undefined || + app === undefined || + callbackPath === undefined +) { + console.error( + "Usage: alchemy-convex hub-client --team --app --callback-path ", + ); + process.exit(1); +} + +const program = Effect.gen(function* () { + const [command, ...prefix] = yield* installedCli(process.cwd()); + const callbackUrl = yield* registerDevelopmentClient({ + team, + app, + callbackPath, + convex: (args, input) => + execFileSync(command, [...prefix, ...args], { + encoding: "utf8", + input, + stdio: ["pipe", "pipe", "inherit"], + }).trim(), + }); + console.log( + callbackUrl === undefined + ? "Hub client already registered." + : `Hub client registered for ${callbackUrl}.`, + ); +}).pipe(Effect.provide(ManagementApiLive().pipe(Layer.provide(fromConfig())))); + +await Effect.runPromise(program).catch((error: unknown) => { + console.error(error instanceof Error ? error.message : String(error)); + process.exit(1); +}); diff --git a/src/index.ts b/src/index.ts index 6b14c28..08a8290 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,6 +18,13 @@ export { type DeploymentProps, ProductionDeploymentNotFound, } from "./Deployment.ts"; +export { + HubClient, + type HubClientAttributes, + HubClientFailed, + type HubClientProps, + type HubDeploymentType, +} from "./HubClient.ts"; export { ConvexApiError, ManagementApi } from "./ManagementApi.ts"; export { AmbiguousProject, diff --git a/test/HubClient.test.ts b/test/HubClient.test.ts new file mode 100644 index 0000000..eabb917 --- /dev/null +++ b/test/HubClient.test.ts @@ -0,0 +1,194 @@ +// Convex.HubClient against the fake Convex control plane: the resource finds the base by name and +// runs the admin functions of the hub with a short-lived key. +import * as Output from "alchemy/Output"; +import * as Test from "alchemy/Test/Vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; +import { describe, expect, it, vi } from "vitest"; +import * as Convex from "../src/index.ts"; +import { fromValues } from "../src/Credentials.ts"; +import { registerDevelopmentClient } from "../src/HubClient.ts"; +import { ManagementApiLive } from "../src/ManagementApi.ts"; +import { STORE_PROJECT_NAME, RUN_KEY_ACTIONS } from "../src/State.ts"; +import { FakeConvex, Hub } from "./fakeConvex.ts"; + +const TEAM = 38516; +const ISSUER = "https://auth.test"; +const CALLBACK = "https://happy-otter-123.convex.site/auth/hub/callback"; + +const { test } = Test.make({ + providers: Convex.providers(Convex.fromValues({ accessToken: Redacted.make("test-token") })), +}); + +const props = (overrides: Partial = {}): Convex.HubClientProps => ({ + team: TEAM, + app: "scout", + redirectUri: CALLBACK, + deploymentType: "preview", + clientName: "pr-1", + softwareVersion: "abc", + ...overrides, +}); + +const client = (input: Convex.HubClientProps) => + Effect.gen(function* () { + const hubClient = yield* Convex.HubClient("HubClient", input); + return { + issuer: hubClient.issuer, + clientId: hubClient.clientId, + secret: Output.map(hubClient.clientSecret, Redacted.value), + }; + }); + +/** A fake with the base of the team: the project of the state, with a hub on its production deployment. */ +const withBase = () => { + const fake = new FakeConvex().install(); + const [deployment] = fake.deploymentsOf( + fake.addProject({ name: STORE_PROJECT_NAME, teamId: TEAM }), + ); + if (deployment === undefined) throw new Error("the fake project has no deployment"); + const hub = new Hub(ISSUER); + fake.hubs.set(deployment.name, hub); + return { fake, hub, deployment: deployment.name }; +}; + +const KeyBody = Schema.Struct({ allowedActions: Schema.Array(Schema.String) }); + +describe("Convex.HubClient", () => { + test.provider("registers with a key of the base that runs internal functions only", (stack) => + Effect.gen(function* () { + const { fake, hub, deployment } = withBase(); + const out = yield* stack.deploy(client(props())); + expect(out).toEqual({ issuer: ISSUER, clientId: "cl_1", secret: "secret-of-cl_1" }); + expect(hub.clients.get("cl_1")).toEqual({ + appId: "scout", + redirectUri: CALLBACK, + deploymentType: "preview", + clientName: "pr-1", + softwareVersion: "abc", + tokenEndpointAuthMethod: "client_secret_post", + }); + const created = fake.sent.find((sent) => sent.path.endsWith("/create_deploy_key")); + expect(Schema.decodeUnknownSync(KeyBody)(created?.body).allowedActions).toEqual([ + ...RUN_KEY_ACTIONS, + ]); + // The key of the call is gone again. + expect(fake.lines().filter((line) => line.endsWith("/delete_deploy_key"))).toHaveLength(1); + expect(fake.functionCalls).toEqual([`${deployment} identityBroker:registerClient`]); + }), + ); + + test.provider("a deploy with the same redirect URI does not reach the hub", (stack) => + Effect.gen(function* () { + const { fake, hub } = withBase(); + const first = yield* stack.deploy(client(props())); + const again = yield* stack.deploy( + client(props({ clientName: "other", softwareVersion: "d" })), + ); + expect(again).toEqual(first); + expect(hub.clients.size).toBe(1); + expect(fake.functionCalls).toHaveLength(1); + }), + ); + + test.provider("another app or team stores the new props and keeps the client", (stack) => + Effect.gen(function* () { + const { fake, hub } = withBase(); + const first = yield* stack.deploy(client(props())); + const again = yield* stack.deploy(client(props({ app: "other" }))); + expect(again).toEqual(first); + expect(hub.clients.size).toBe(1); + expect(fake.functionCalls).toHaveLength(1); + }), + ); + + test.provider("another redirect URI is a new client, and the old one goes", (stack) => + Effect.gen(function* () { + const { hub } = withBase(); + yield* stack.deploy(client(props())); + const next = yield* stack.deploy(client(props({ redirectUri: `${CALLBACK}2` }))); + expect(next.clientId).toBe("cl_2"); + expect([...hub.clients.keys()]).toEqual(["cl_2"]); + }), + ); + + test.provider("a destroy deletes the client", (stack) => + Effect.gen(function* () { + const { hub } = withBase(); + yield* stack.deploy(client(props())); + yield* stack.destroy(); + expect(hub.clients.size).toBe(0); + }), + ); + + test.provider("a team without a base fails and names what is missing", (stack) => + Effect.gen(function* () { + new FakeConvex().install(); + const error = yield* Effect.flip(stack.deploy(client(props()))); + expect(error).toBeInstanceOf(Convex.HubClientFailed); + expect(error.message).toContain("no project samebase"); + }), + ); + + test.provider("a base without a hub fails with the Convex message", (stack) => + Effect.gen(function* () { + const { fake, deployment } = withBase(); + fake.hubs.delete(deployment); + const error = yield* Effect.flip(stack.deploy(client(props()))); + expect(error).toBeInstanceOf(Convex.HubClientFailed); + expect(error.message).toContain( + "Could not find function for 'identityBroker:registerClient'", + ); + }), + ); +}); + +describe("registerDevelopmentClient", () => { + const run = (convex: (args: readonly string[], input?: string) => string) => + registerDevelopmentClient({ + team: TEAM, + app: "scout", + callbackPath: "/auth/hub/callback", + convex, + }).pipe( + Effect.provide( + ManagementApiLive().pipe( + Layer.provide(fromValues({ accessToken: Redacted.make("test-token") })), + ), + ), + Effect.runPromise, + ); + + it("a deployment with all three variables keeps them", async () => { + const { hub } = withBase(); + const convex = vi.fn(() => "HUB_ISSUER\nHUB_CLIENT_ID\nHUB_CLIENT_SECRET\nOTHER"); + expect(await run(convex)).toBeUndefined(); + expect(convex).toHaveBeenCalledTimes(1); + expect(hub.clients.size).toBe(0); + }); + + it("a deployment with no complete client registers, and the secret goes on standard input", async () => { + const { hub } = withBase(); + const inputs: (string | undefined)[] = []; + const calls: string[] = []; + const url = await run((args, input) => { + calls.push(args.join(" ")); + inputs.push(input); + if (args[0] === "run") return '"https://happy-otter-123.convex.site/"'; + return args[1] === "list" ? "HUB_ISSUER" : ""; + }); + expect(url).toBe(CALLBACK); + expect(hub.clients.get("cl_1")).toMatchObject({ + appId: "scout", + redirectUri: CALLBACK, + deploymentType: "development", + softwareVersion: "happy-otter-123.convex.site", + }); + expect(calls.at(-1)).toBe("env set --force"); + expect(inputs.at(-1)).toBe( + `HUB_ISSUER='${ISSUER}'\nHUB_CLIENT_ID='cl_1'\nHUB_CLIENT_SECRET='secret-of-cl_1'\n`, + ); + }); +}); diff --git a/test/fakeConvex.ts b/test/fakeConvex.ts index 533b80d..bdc875d 100644 --- a/test/fakeConvex.ts +++ b/test/fakeConvex.ts @@ -67,6 +67,22 @@ export interface Store { readonly outputs: Map; } +/** The admin functions of an identity hub, as the broker answers them. */ +export class Hub { + readonly clients = new Map>(); + private nextClient = 1; + constructor(readonly issuer: string) {} + run(path: string, args: Record) { + if (path === "identityBroker:deleteClient") { + this.clients.delete(String(args["clientId"])); + return null; + } + const clientId = `cl_${this.nextClient++}`; + this.clients.set(clientId, args); + return { issuer: this.issuer, clientId, clientSecret: `secret-of-${clientId}` }; + } +} + /** The internal functions of the store that a query key runs, and those that need a mutation key. */ const STORE_QUERIES = [ "version", @@ -82,6 +98,7 @@ const STORE_QUERIES = [ const STORE_MUTATIONS = ["set", "remove", "removeStack", "setOutput"]; /** The store version that added a function; every other function is in version 1 (0.6.0). */ const STORE_FUNCTION_SINCE: Record = { readStack: 2 }; +const HubCall = Schema.Struct({ args: Schema.Record(Schema.String, Schema.Unknown) }); const FunctionCall = Schema.Struct({ path: Schema.String, args: Schema.Struct({ @@ -158,6 +175,8 @@ export class FakeConvex { readonly stores = new Map(); /** The push events of the fake CLI that this fake applied already, one install for each. */ private appliedPushes = new Set(); + /** The identity hub of each deployment that has one: POST /api/function answers its admin functions. */ + readonly hubs = new Map(); /** The store functions that ran, as " " lines. */ readonly functionCalls: string[] = []; /** Every deploy key secret ever created for each deployment, also the deleted ones. */ @@ -474,6 +493,21 @@ export class FakeConvex { const key = this.keysOf(this.keys, deployment).find((candidate) => candidate.secret === secret); if (key === undefined) return json(403, stateFixture("function_no_key.json")); const { path, args } = Schema.decodeUnknownSync(FunctionCall)(body); + const hub = this.hubs.get(deployment); + if (path.startsWith("identityBroker:") && hub !== undefined) { + if ( + key.actions !== undefined && + !key.actions.includes("deployment:functions:runInternalMutations") + ) { + return json(200, { + ...stateFixture("function_version_missing.json"), + errorMessage: "no permission", + }); + } + this.functionCalls.push(`${deployment} ${path}`); + const { args: hubArgs } = Schema.decodeUnknownSync(HubCall)(body); + return json(200, { ...stateFixture("function_version.json"), value: hub.run(path, hubArgs) }); + } const name = path.replace(/^state:/, ""); // Each push of the fake CLI with a key of this deployment installs the store app once: as a // real push, it replaces whatever answered, a base too, and keeps the rows. diff --git a/vite.config.ts b/vite.config.ts index e136e40..532c764 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -13,6 +13,7 @@ export default defineConfig({ include: ["test/**/*.test.ts"], }, pack: { + entry: ["src/index.ts", "src/cli.ts"], outDir: "lib", // "type": "module" makes the ESM output `index.js`, the file that `exports` names. fixedExtension: false,