Skip to content
This repository was archived by the owner on Oct 31, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
6 changes: 3 additions & 3 deletions docs/design/convex-plane.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand All @@ -18,6 +18,9 @@
"type": "git",
"url": "git+https://github.com/samebase/alchemy-convex.git"
},
"bin": {
"alchemy-convex": "./lib/cli.js"
},
"files": [
"lib",
"src",
Expand Down
258 changes: 258 additions & 0 deletions src/HubClient.ts
Original file line number Diff line number Diff line change
@@ -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 `<deployment site URL>/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<string>;
}

export type HubClient = Resource<
"IdentityHub.Client",
HubClientProps,
HubClientAttributes,
never,
Providers
>;
export const HubClient = Resource<HubClient>("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>()("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 = <A, E, R>(
api: ManagementApiService,
team: string | number,
use: (functions: FunctionApi) => Effect.Effect<A, E, R>,
) =>
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<string, string>,
) =>
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;
});
5 changes: 3 additions & 2 deletions src/Providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -15,8 +16,8 @@ export class Providers extends Provider.ProviderCollection<Providers>()("Convex"
* `CONVEX_DEPLOY_KEY`).
*/
export const providers = (credentials: Layer.Layer<Credentials> = 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,
Expand Down
Loading
Loading