@samebase/alchemy-convex 0.28.0 → 0.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -25
- package/lib/{HubClient-BcegkjaP.js → HubClient-X0-FgJ8v.js} +129 -65
- package/lib/HubClient-X0-FgJ8v.js.map +1 -0
- package/lib/cli.js +4 -4
- package/lib/cli.js.map +1 -1
- package/lib/index.d.ts +62 -24
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +67 -7
- package/lib/index.js.map +1 -1
- package/package.json +1 -1
- package/src/LocalDeployment.ts +105 -0
- package/src/ManagementApi.ts +145 -26
- package/src/Project.ts +39 -53
- package/src/Providers.ts +3 -1
- package/src/SharedHubClient.ts +31 -7
- package/src/State.ts +13 -19
- package/src/cli.ts +11 -11
- package/src/index.ts +6 -0
- package/lib/HubClient-BcegkjaP.js.map +0 -1
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/Component.ts","../src/SharedHubClient.ts","../src/Providers.ts"],"sourcesContent":["import { toPath } from \"alchemy/FQN\";\nimport type { NamespaceNode } from \"alchemy/Namespace\";\nimport { Stack } from \"alchemy/Stack\";\nimport * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport type { Deployment } from \"./Deployment.ts\";\n\n/** A component's resources occupy this namespace in the deployment's Alchemy stack and stage. */\nexport interface ComponentBinding {\n readonly type: \"component\";\n readonly path: string;\n readonly namespace: readonly string[];\n}\n\n/**\n * Associate a native namespace with an installed component. `component` is the\n * installed name from the app's `convex.config.ts`; a nested install joins the\n * names with slashes, such as `\"workspace/mail\"`. An undefined namespace\n * associates the stack root. This records display metadata; it does not install\n * the component, set its environment, or change removal policies.\n */\nexport const bindComponent = (options: {\n deployment: Deployment;\n component: string;\n namespace: NamespaceNode | undefined;\n}) =>\n Effect.gen(function* () {\n if (options.component === \"\") {\n return yield* Effect.die(new Error(\"The component name is empty.\"));\n }\n const namespace = toPath(options.namespace);\n const sid = `convex.component:${JSON.stringify(namespace)}`;\n const stack = yield* Stack;\n const previous = stack.bindings[options.deployment.FQN]?.find((binding) => binding.sid === sid);\n // Alchemy keeps the last binding with a given sid. Reject conflicting owners before that happens.\n if (previous !== undefined) {\n const existing = Schema.decodeUnknownSync(Schema.Struct({ path: Schema.String }))(\n previous.data,\n );\n if (existing.path !== options.component) {\n return yield* Effect.die(\n new Error(\n `Alchemy namespace ${JSON.stringify(namespace)} is already bound to ${existing.path}.`,\n ),\n );\n }\n return;\n }\n yield* options.deployment.bind(sid, {\n type: \"component\",\n path: options.component,\n namespace,\n });\n });\n","// Convex.SharedHubClient: one deployment of an app as a client of the central identity hub, for an\n// app that deploys in its own GitHub Actions run, on any host, and on a laptop as a stage of the same\n// stack.\n//\n// A run in GitHub Actions asks the hub for a new client with a GitHub OIDC token, so the stack needs\n// no key and no Samebase account. The token names the repository. The hub reads\n// `/samebase-verification.json` at the origin of the return address, which must name the same\n// repository, and registers the client on that address. The answer holds the client's own\n// registration access token (RFC 7591), and each later deploy reads the client on the hub with that\n// token (RFC 7592). The hub keeps only hashes, so the state is the only record of the secret and the\n// token.\n//\n// The answer to a production registration also holds the app's initial access token (RFC 7591\n// section 1.2) and the repository id. The state of stage `prod` keeps them. A laptop runs the stack\n// as a stage `dev-<name>`: it reads them with `SharedHubClient.read`, and a client with\n// `deploymentType: \"development\"` asks the hub with the token in place of the GitHub token (RFC 133).\n//\n// A push removes a variable that a deploy stops passing, so a failure here must not drop working\n// variables or stop the deploy. A renewal that fails keeps the saved values. Only a client that\n// cannot work asks for a new one: it is gone, or it has another return address or type. If that\n// request fails, the run gives the off values, so the app has guest sign-in and not a broken button.\n// The off values are the `no-hub` variables of a checkout without a hub: Convex needs the variables,\n// and the app hides the button for this client ID.\n//\n// No text in this file quotes an answer or a fetch error, so no log line can hold a secret.\nimport { Resource } from \"alchemy\";\nimport { isResolved } from \"alchemy/Diff\";\nimport * as Output from \"alchemy/Output\";\nimport * as Provider from \"alchemy/Provider\";\nimport { Stack } from \"alchemy/Stack\";\nimport { State } from \"alchemy/State\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Schema from \"effect/Schema\";\nimport type { Providers } from \"./Providers.ts\";\n\n/** A hung service must not hold a deploy: the time limit of one request. */\nconst REQUEST_TIMEOUT_MS = 30_000;\n\n/** The variables of a deployment without a hub client, as the starter writes them. */\nconst OFF_VALUES = { issuer: \"http://127.0.0.1:1\", clientId: \"no-hub\", clientSecret: \"no-hub\" };\n\ninterface CommonProps {\n /** The stable name of the app, set once in the stack. */\n readonly app: string;\n /**\n * The return address of the hub's sign-ins, such as `${site.siteUrl}/auth/hub/callback`: an https\n * URL whose origin serves `/samebase-verification.json` with the numeric GitHub id of this\n * repository, `{ \"repository\": \"123\" }`. It can come from a resource that this run creates. A\n * development client can also have http on a loopback host, which needs no file.\n */\n readonly redirectUri: string;\n /** Recorded on the hub's client, such as the commit. The hub records \"unknown\" without it. */\n readonly softwareVersion?: string;\n}\n\n/**\n * A production or preview client asks with the GitHub OIDC token of the run. A development client\n * asks with the app's initial access token, which `SharedHubClient.read` gives from stage `prod`.\n */\nexport type SharedHubClientProps =\n | (CommonProps & {\n readonly deploymentType: \"production\" | \"preview\";\n readonly initialAccessToken?: never;\n })\n | (CommonProps & {\n readonly deploymentType: \"development\";\n /** Empty before the first production registration: the client gets the off values. */\n readonly initialAccessToken: Redacted.Redacted<string>;\n });\n\nconst DeploymentType = Schema.Literals([\"production\", \"preview\", \"development\"]);\n\nconst Attributes = Schema.Struct({\n /** `off`: no client, and the values below are the off values. */\n status: Schema.Literals([\"on\", \"off\", \"suspended\"]),\n /** The issuer of the hub, which the deployment names to sign in. */\n issuer: Schema.String,\n clientId: Schema.String,\n /** Returned only at registration. */\n clientSecret: Schema.Redacted(Schema.String),\n /** Returned only at registration. It reads and deletes this client on the hub, and nothing else. */\n registrationAccessToken: Schema.Redacted(Schema.String),\n registrationClientUri: Schema.String,\n deploymentType: DeploymentType,\n /** The return address that the client serves. Empty for the off values. */\n redirectUri: Schema.String,\n /**\n * Returned only at a production registration (RFC 7591 section 1.2). It registers development\n * clients of this app. Empty for a preview, for a development client, and for the off values.\n */\n initialAccessToken: Schema.Redacted(Schema.String),\n /** The numeric GitHub id of the repository, with the initial access token. Empty without it. */\n repository: Schema.String,\n});\n\n/**\n * The attributes keep the real values of a suspended client, so that an unblock needs no new client.\n * `SharedHubClient.variables` gives the values that the app gets.\n */\nexport interface SharedHubClientAttributes extends Schema.Schema.Type<typeof Attributes> {}\n\n/**\n * The attributes of a saved row, or undefined when the row does not have this version's shape, such\n * as a row that 0.26 or earlier saved without the token fields. Only a schema issue gives undefined;\n * any other failure of the decoder stops the run with a fixed message. The text of a schema issue\n * can quote a value of the row, so it is never kept.\n */\nconst savedAttributes = (value: unknown) =>\n Schema.decodeUnknownEffect(Attributes)(value).pipe(\n Effect.map((attributes): SharedHubClientAttributes | undefined => attributes),\n Effect.catch(() => Effect.succeed(undefined)),\n Effect.catchDefect(() =>\n Effect.die(\n new SharedHubClientFailed({\n reason: \"the state holds attributes of Convex.SharedHubClient that it cannot read\",\n }),\n ),\n ),\n );\n\n/** The attributes of no client. */\nconst offAttributes = (\n deploymentType: SharedHubClientAttributes[\"deploymentType\"],\n): SharedHubClientAttributes => ({\n status: \"off\",\n issuer: OFF_VALUES.issuer,\n clientId: OFF_VALUES.clientId,\n clientSecret: Redacted.make(OFF_VALUES.clientSecret),\n registrationAccessToken: Redacted.make(\"\"),\n registrationClientUri: \"\",\n deploymentType,\n redirectUri: \"\",\n initialAccessToken: Redacted.make(\"\"),\n repository: \"\",\n});\n\n/** One request gave no usable answer. The reason holds no secret. */\nclass SharedHubClientFailed extends Schema.TaggedError<SharedHubClientFailed>()(\n \"SharedHubClientFailed\",\n { reason: Schema.String },\n) {\n override get message() {\n return `Convex.SharedHubClient: ${this.reason}.`;\n }\n}\n\nconst OidcToken = Schema.Struct({ value: Schema.NonEmptyString });\n\n/** The 201 answer of `POST /hub-clients`. */\nconst NewClient = Schema.Struct({\n issuer: Schema.NonEmptyString,\n client_id: Schema.NonEmptyString,\n client_secret: Schema.NonEmptyString,\n registration_access_token: Schema.NonEmptyString,\n registration_client_uri: Schema.NonEmptyString,\n redirect_uri: Schema.NonEmptyString,\n /**\n * The terms of the shared sign-in service, which the log shows once, for the new client. Exactly\n * this page: the log line must not print a value that the answer chose.\n */\n terms: Schema.Literal(\"https://samebase.com/terms\"),\n /** Only in the answer to a production registration with the GitHub token. */\n initial_access_token: Schema.optionalKey(Schema.NonEmptyString),\n repository: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^\\d+$/))),\n});\n\n/** The other answers of `POST /hub-clients`, by status. */\nconst REFUSALS: Readonly<Record<number, string>> = {\n 400: \"the identity hub refused the request: the return address must be https on a DNS name, and the app name at most 64 characters\",\n 401: \"the identity hub refused the GitHub OIDC token\",\n 403: \"the identity hub does not allow this repository or return address\",\n 404: \"the identity hub has no /hub-clients\",\n 429: \"the identity hub limits new clients\",\n 502: \"GitHub's keys are not available to the identity hub\",\n};\n\n/** The reasons of a 403 that a log line shows. Any other text of the answer is never logged. */\nconst NOT_ALLOWED = new Map([\n [\"paused\", \"the identity hub pauses new clients of third-party apps\"],\n [\"run_not_allowed\", \"the identity hub gives clients only to runs of main and of pull requests\"],\n [\"blocked\", \"Samebase blocked this repository or its owner\"],\n [\"suspended\", \"the identity hub suspended this repository\"],\n [\"too_many_apps\", \"the repository has as many apps on the identity hub as it may\"],\n [\"too_many_clients\", \"the app has as many clients on the identity hub as it may\"],\n [\"app_taken\", \"the app's name belongs to another app on the identity hub\"],\n [\"host_unreachable\", \"the identity hub could not reach the host of the return address\"],\n [\n \"verification_file_missing\",\n \"the host of the return address does not serve /samebase-verification.json\",\n ],\n [\"verification_file_invalid\", \"/samebase-verification.json on the host holds no repository id\"],\n [\"repository_mismatch\", \"/samebase-verification.json on the host names another repository\"],\n [\"app_mismatch\", \"the initial access token belongs to another app on the identity hub\"],\n]);\n\n/** The windows of a 429, by the name that the answer gives. */\nconst RATE_LIMITED = new Map([\n [\"repository\", \"the identity hub gives one repository at most 30 new clients an hour\"],\n [\"owner\", \"the identity hub gives one owner at most 100 new clients an hour\"],\n [\"new_owners\", \"the identity hub takes at most 50 new owners an hour\"],\n]);\n\nconst Refusal = Schema.Struct({ reason: Schema.String });\nconst RateLimited = Schema.Struct({ window: Schema.String });\n\n/** The text of a refusal: a known reason of a 403 or window of a 429, else the text of its status. */\nconst refusalOf = (status: number, body: unknown) => {\n const known =\n status === 403\n ? NOT_ALLOWED.get(\n Option.getOrUndefined(Schema.decodeUnknownOption(Refusal)(body))?.reason ?? \"\",\n )\n : status === 429\n ? RATE_LIMITED.get(\n Option.getOrUndefined(Schema.decodeUnknownOption(RateLimited)(body))?.window ?? \"\",\n )\n : undefined;\n return known ?? REFUSALS[status] ?? \"the identity hub refused the request\";\n};\n\nconst send = (who: string, url: string, token: string, init: { method: string; body?: string }) =>\n Effect.tryPromise({\n try: async () => {\n const response = await fetch(url, {\n ...init,\n headers: { Authorization: `Bearer ${token}`, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n const body: unknown = await response.json().catch(() => undefined);\n return { status: response.status, body };\n },\n catch: () => new SharedHubClientFailed({ reason: `${who} gave no answer` }),\n });\n\nconst decode =\n <S extends Schema.Codec<unknown, unknown>>(schema: S, who: string) =>\n (value: unknown) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.mapError(() => new SharedHubClientFailed({ reason: `${who} gave a bad answer` })),\n );\n\n/** The OIDC token of this run, read right before the call, because it lives for minutes only. */\nconst readOidcToken = (requestUrl: string, requestToken: string) =>\n Effect.gen(function* () {\n const { body, status } = yield* send(\n \"GitHub\",\n `${requestUrl}&audience=samebase`,\n requestToken,\n { method: \"GET\" },\n );\n if (status !== 200) {\n return yield* new SharedHubClientFailed({\n reason: `GitHub gave no OIDC token (HTTP ${status})`,\n });\n }\n return (yield* decode(OidcToken, \"GitHub\")(body)).value;\n });\n\n/** `POST /hub-clients` with `bearer`: the GitHub OIDC token, or the app's initial access token. */\nconst requestNewClient = (props: SharedHubClientProps, bearer: string) =>\n Effect.gen(function* () {\n const { body, status } = yield* send(\n \"The identity hub\",\n `${process.env[\"HUB_URL\"] ?? \"https://auth.samebase.com\"}/hub-clients`,\n bearer,\n {\n method: \"POST\",\n body: JSON.stringify({\n app: props.app,\n redirectUri: props.redirectUri,\n softwareVersion: props.softwareVersion ?? \"unknown\",\n }),\n },\n );\n if (status !== 201) {\n const reason =\n status === 401 && props.deploymentType === \"development\"\n ? \"the identity hub refused the initial access token\"\n : refusalOf(status, body);\n return yield* new SharedHubClientFailed({ reason: `${reason} (HTTP ${status})` });\n }\n const client = yield* decode(NewClient, \"The identity hub\")(body);\n // The hub registers the address that the request sent. The log names the request's, so no\n // value that the answer chose is printed.\n if (client.redirect_uri !== props.redirectUri) {\n return yield* new SharedHubClientFailed({ reason: \"The identity hub gave a bad answer\" });\n }\n yield* Effect.logInfo(\n `Convex.SharedHubClient: ${props.app} on ${props.redirectUri} has a new client of the identity hub. Its use is under ${client.terms}.`,\n );\n // Only a production registration gives the app's token (RFC 7591); any other answer's is dropped.\n const production = props.deploymentType === \"production\";\n return {\n status: \"on\" as const,\n issuer: client.issuer,\n clientId: client.client_id,\n clientSecret: Redacted.make(client.client_secret),\n registrationAccessToken: Redacted.make(client.registration_access_token),\n registrationClientUri: client.registration_client_uri,\n deploymentType: props.deploymentType,\n redirectUri: props.redirectUri,\n initialAccessToken: Redacted.make(production ? (client.initial_access_token ?? \"\") : \"\"),\n repository: production ? (client.repository ?? \"\") : \"\",\n };\n });\n\n/** A new client, or the off values. */\nconst newClient = (props: SharedHubClientProps) => {\n const label = `Convex.SharedHubClient: ${props.app} on ${props.redirectUri} deploys without the hub`;\n const off = offAttributes(props.deploymentType);\n const request = (bearer: Effect.Effect<string, SharedHubClientFailed>) =>\n bearer.pipe(\n Effect.flatMap((token) => requestNewClient(props, token)),\n Effect.catchTag(\"SharedHubClientFailed\", (error) =>\n Effect.logWarning(`${label}: ${error.reason}. The next deploy asks again.`).pipe(\n Effect.as(off),\n ),\n ),\n );\n\n if (props.deploymentType === \"development\") {\n const token = Redacted.value(props.initialAccessToken);\n return token === \"\"\n ? Effect.logInfo(\n \"Convex.SharedHubClient: deploy to main once for Google sign-in on this laptop.\",\n ).pipe(Effect.as(off))\n : request(Effect.succeed(token));\n }\n\n const requestUrl = process.env[\"ACTIONS_ID_TOKEN_REQUEST_URL\"];\n const requestToken = process.env[\"ACTIONS_ID_TOKEN_REQUEST_TOKEN\"];\n // A laptop, or another CI. In a workflow, `id-token: write` gives both, so a workflow without them\n // is a mistake to show, not a normal run.\n if (!requestUrl || !requestToken) {\n return (\n process.env[\"GITHUB_ACTIONS\"] === \"true\"\n ? Effect.logWarning(`${label}: this workflow needs the permission id-token: write.`)\n : Effect.logInfo(`${label}: this run has no GitHub OIDC token.`)\n ).pipe(Effect.as(off));\n }\n return request(readOidcToken(requestUrl, requestToken));\n};\n\n/** The client after a read on the hub, or undefined when the hub says that the client is gone. */\nconst renew = (saved: SharedHubClientAttributes) =>\n Effect.gen(function* () {\n const { status } = yield* send(\n \"The identity hub\",\n saved.registrationClientUri,\n Redacted.value(saved.registrationAccessToken),\n { method: \"GET\" },\n );\n switch (status) {\n case 200:\n return { ...saved, status: \"on\" as const };\n case 401:\n return undefined;\n case 403:\n yield* Effect.logWarning(\n `Convex.SharedHubClient: the hub suspended the client of ${saved.redirectUri}. It keeps its values, and nobody can sign in with it.`,\n );\n return { ...saved, status: \"suspended\" as const };\n default:\n return yield* new SharedHubClientFailed({\n reason: `The identity hub answered HTTP ${status}`,\n });\n }\n }).pipe(\n Effect.catchTag(\"SharedHubClientFailed\", (error) =>\n Effect.logWarning(\n `Convex.SharedHubClient: ${saved.redirectUri} keeps the saved client: ${error.reason}.`,\n ).pipe(Effect.as(saved)),\n ),\n );\n\n/** A saved row of this resource, whose `attr` `savedAttributes` reads. */\nconst SavedRow = Schema.Struct({\n resourceType: Schema.Literal(\"IdentityHub.SharedClient\"),\n attr: Schema.Unknown,\n});\n\n/**\n * The attributes of the client `id` in another stage of this stack, such as\n * `read(\"HubClient\", { stage: \"prod\" })` in the stage of a laptop, as Outputs: the\n * `initialAccessToken` and the `repository` of the production client. Without that row, the off\n * attributes, with `deploymentType: \"production\"`.\n *\n * `SharedHubClient.ref` is not enough: Alchemy fails the plan with `InvalidReferenceError` when the\n * row is missing, and a laptop before the first deploy to main has none. This read runs when the\n * plan resolves it, with the State service of the running stack and its `get`, so it never creates\n * or upgrades a store. The store revives each secret as `Redacted`, as it does for every read.\n */\nconst read = (id: string, options: { readonly stage: string }) =>\n Output.fromEffect(\n Effect.gen(function* () {\n const stack = yield* Stack;\n const state = yield* yield* State;\n const row = yield* state\n .get({ stack: stack.name, stage: options.stage, fqn: id })\n .pipe(Effect.orDie);\n if (row === undefined) return offAttributes(\"production\");\n const { attr } = yield* Schema.decodeUnknownEffect(SavedRow)(row).pipe(\n Effect.catchCause(() =>\n Effect.die(\n new SharedHubClientFailed({\n reason: `the row ${id} of stage ${options.stage} is not a Convex.SharedHubClient`,\n }),\n ),\n ),\n );\n const saved = yield* savedAttributes(attr);\n if (saved === undefined) {\n return yield* Effect.die(\n new SharedHubClientFailed({\n reason: `the row ${id} of stage ${options.stage} holds attributes that this version cannot read`,\n }),\n );\n }\n return saved;\n }),\n );\n\n/**\n * The three values that the app's deployment gets, such as `HUB_ISSUER`, `HUB_CLIENT_ID`, and\n * `HUB_CLIENT_SECRET`, as Outputs: the client's values when `status` is `on`, else the off values,\n * so that a suspended client gives guest sign-in and keeps its values in state.\n */\nconst variables = (client: SharedHubClient) =>\n Output.map(Output.of(client), (attributes) =>\n attributes.status === \"on\"\n ? {\n issuer: attributes.issuer,\n clientId: attributes.clientId,\n clientSecret: attributes.clientSecret,\n }\n : {\n issuer: OFF_VALUES.issuer,\n clientId: OFF_VALUES.clientId,\n clientSecret: Redacted.make(OFF_VALUES.clientSecret),\n },\n );\n\nexport type SharedHubClient = Resource<\n \"IdentityHub.SharedClient\",\n SharedHubClientProps,\n SharedHubClientAttributes,\n never,\n Providers\n>;\nexport const SharedHubClient = Resource<SharedHubClient>(\"IdentityHub.SharedClient\")({\n read,\n variables,\n});\n\nexport const SharedHubClientProvider = () =>\n Provider.succeed(SharedHubClient, {\n // Always an update, so that each deploy reaches the hub. No attribute is stable, so a push\n // reads the values that this run ended with. The same values cause no other push.\n diff: ({ news }) =>\n Effect.succeed(isResolved(news) ? ({ action: \"update\" } as const) : undefined),\n\n read: ({ output }) => Effect.succeed(output),\n\n // Only a client of the same return address and type is renewed. A saved row without this\n // version's shape, such as one that 0.26 or earlier saved, is no client: the run asks for a new\n // one, which replaces the saved client, and for a production client also replaces the app's\n // initial access token.\n reconcile: Effect.fn(function* ({ news, output }) {\n const saved =\n output === undefined || output.status === \"off\"\n ? undefined\n : yield* savedAttributes(output);\n if (output !== undefined && output.status !== \"off\" && saved === undefined) {\n yield* Effect.logWarning(\n `Convex.SharedHubClient: the saved attributes of ${news.app} on ${news.redirectUri} cannot be read by this version, so this run registers a new client, which replaces the saved one.`,\n );\n }\n const renewed =\n saved?.redirectUri === news.redirectUri && saved.deploymentType === news.deploymentType\n ? yield* renew(saved)\n : undefined;\n return renewed ?? (yield* newClient(news));\n }),\n\n // A failed delete does not stop a destroy: the removal date of a preview or development client\n // cleans it up. A destroy can leave a production deployment running, so its client stays.\n delete: ({ output }) =>\n output.deploymentType === \"production\" || output.status === \"off\"\n ? Effect.void\n : Effect.gen(function* () {\n const { status } = yield* send(\n \"The identity hub\",\n output.registrationClientUri,\n Redacted.value(output.registrationAccessToken),\n { method: \"DELETE\" },\n );\n // 401: the client is gone already.\n if (status !== 204 && status !== 401) {\n return yield* new SharedHubClientFailed({\n reason: `The identity hub answered HTTP ${status}`,\n });\n }\n }).pipe(\n Effect.catchTag(\"SharedHubClientFailed\", (error) =>\n Effect.logWarning(\n `Convex.SharedHubClient: the client of ${output.redirectUri} stays on the hub until its removal date: ${error.reason}.`,\n ),\n ),\n ),\n });\n","// The provider collection users merge into a stack:\n// providers: Layer.mergeAll(Cloudflare.providers(), Convex.providers())\nimport * as Provider from \"alchemy/Provider\";\nimport * as Layer from \"effect/Layer\";\nimport { type Credentials, fromConfig } from \"./Credentials.ts\";\nimport { DeploymentProvider, DeploymentResource } from \"./Deployment.ts\";\nimport { HubClient, HubClientProvider } from \"./HubClient.ts\";\nimport { ManagementApiLive } from \"./ManagementApi.ts\";\nimport { Project, ProjectProvider } from \"./Project.ts\";\nimport { SharedHubClient, SharedHubClientProvider } from \"./SharedHubClient.ts\";\n\nexport class Providers extends Provider.ProviderCollection<Providers>()(\"Convex\") {}\n\n/**\n * The Convex resource providers. Pass a credentials layer to override the\n * default lookup (`CONVEX_ACCESS_TOKEN`, then the Convex CLI login, and\n * `CONVEX_DEPLOY_KEY`).\n */\nexport const providers = (credentials: Layer.Layer<Credentials> = fromConfig()) =>\n Layer.effect(\n Providers,\n Provider.collection([Project, DeploymentResource, HubClient, SharedHubClient]),\n ).pipe(\n Layer.provide(\n Layer.mergeAll(\n ProjectProvider(),\n DeploymentProvider(),\n HubClientProvider(),\n SharedHubClientProvider(),\n ),\n ),\n Layer.provide(ManagementApiLive()),\n Layer.provide(credentials),\n Layer.orDie,\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,iBAAiB,YAK5B,OAAO,IAAI,aAAa;CACtB,IAAI,QAAQ,cAAc,IACxB,OAAO,OAAO,OAAO,oBAAI,IAAI,MAAM,8BAA8B,CAAC;CAEpE,MAAM,YAAY,OAAO,QAAQ,SAAS;CAC1C,MAAM,MAAM,oBAAoB,KAAK,UAAU,SAAS;CAExD,MAAM,YAAW,OADI,MAAA,CACE,SAAS,QAAQ,WAAW,IAAI,EAAE,MAAM,YAAY,QAAQ,QAAQ,GAAG;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kBAAkB,GAClB,wBAAwB,CAC1B,CACF,GACA,MAAM,QAAQ,kBAAkB,CAAC,GACjC,MAAM,QAAQ,WAAW,GACzB,MAAM,KACR"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/Component.ts","../src/LocalDeployment.ts","../src/SharedHubClient.ts","../src/Providers.ts"],"sourcesContent":["import { toPath } from \"alchemy/FQN\";\nimport type { NamespaceNode } from \"alchemy/Namespace\";\nimport { Stack } from \"alchemy/Stack\";\nimport * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport type { Deployment } from \"./Deployment.ts\";\n\n/** A component's resources occupy this namespace in the deployment's Alchemy stack and stage. */\nexport interface ComponentBinding {\n readonly type: \"component\";\n readonly path: string;\n readonly namespace: readonly string[];\n}\n\n/**\n * Associate a native namespace with an installed component. `component` is the\n * installed name from the app's `convex.config.ts`; a nested install joins the\n * names with slashes, such as `\"workspace/mail\"`. An undefined namespace\n * associates the stack root. This records display metadata; it does not install\n * the component, set its environment, or change removal policies.\n */\nexport const bindComponent = (options: {\n deployment: Deployment;\n component: string;\n namespace: NamespaceNode | undefined;\n}) =>\n Effect.gen(function* () {\n if (options.component === \"\") {\n return yield* Effect.die(new Error(\"The component name is empty.\"));\n }\n const namespace = toPath(options.namespace);\n const sid = `convex.component:${JSON.stringify(namespace)}`;\n const stack = yield* Stack;\n const previous = stack.bindings[options.deployment.FQN]?.find((binding) => binding.sid === sid);\n // Alchemy keeps the last binding with a given sid. Reject conflicting owners before that happens.\n if (previous !== undefined) {\n const existing = Schema.decodeUnknownSync(Schema.Struct({ path: Schema.String }))(\n previous.data,\n );\n if (existing.path !== options.component) {\n return yield* Effect.die(\n new Error(\n `Alchemy namespace ${JSON.stringify(namespace)} is already bound to ${existing.path}.`,\n ),\n );\n }\n return;\n }\n yield* options.deployment.bind(sid, {\n type: \"component\",\n path: options.component,\n namespace,\n });\n });\n","// Convex.LocalDeployment: the logged-in local deployment of one folder, which\n// `npx convex deployment create <team>:<project>:local --select` makes and `npx convex dev` runs on\n// this machine. Each folder, such as each git worktree, has its own, with its own data.\n//\n// The resource writes its `env` and nothing else. The running `convex dev` owns the backend and\n// pushes the functions, so the stage of a laptop runs after `convex dev` has started, and the\n// first push of a new local deployment takes the variables that the project's default variables\n// for development gave it. The resource reads the deployment from\n// `.convex/local/default/config.json`, where the Convex CLI keeps its name, ports, and admin key,\n// and writes with that admin key through the same call as for a cloud deployment.\n//\n// A destroy changes nothing: the folder's deployment and its variables stay with the folder.\nimport { Resource } from \"alchemy\";\nimport { isResolved } from \"alchemy/Diff\";\nimport * as Provider from \"alchemy/Provider\";\nimport * as Effect from \"effect/Effect\";\nimport * as ChildProcessSpawner from \"effect/process/ChildProcessSpawner\";\nimport * as Schema from \"effect/Schema\";\nimport { readLocalDeployment } from \"./ManagementApi.ts\";\nimport type { Providers } from \"./Providers.ts\";\nimport { type EnvValue, push } from \"./Push.ts\";\n\n/** The folder has no logged-in local deployment. */\nexport class LocalDeploymentNotFound extends Schema.TaggedError<LocalDeploymentNotFound>()(\n \"LocalDeploymentNotFound\",\n { rootDir: Schema.String },\n) {\n override get message() {\n return `Convex.LocalDeployment: ${this.rootDir} has no logged-in local deployment. Run \\`npx convex deployment create <team>:<project>:local --select\\` there, then \\`npx convex dev\\`.`;\n }\n}\n\n/**\n * The folder's logged-in local deployment, read when the stack's program runs, so that a client\n * can take its `siteUrl`. Fails with `LocalDeploymentNotFound` when the folder has none.\n */\nconst of = (rootDir = \".\") => {\n const info = readLocalDeployment(rootDir);\n if (info === undefined) throw new LocalDeploymentNotFound({ rootDir });\n return { name: info.name, url: info.url, siteUrl: info.siteUrl };\n};\n\nexport interface LocalDeploymentProps {\n /** The folder of the Convex app, where `.convex/local/default` is. The working directory without it. */\n readonly rootDir?: string;\n /** The variables of the deployment. A name that leaves `env` is removed. */\n readonly env: Readonly<Record<string, EnvValue>>;\n}\n\nexport interface LocalDeploymentAttributes {\n readonly name: string;\n readonly url: string;\n readonly siteUrl: string;\n /** The names that this resource set, so a name that leaves `env` is removed. */\n readonly envNames: readonly string[];\n}\n\nexport type LocalDeployment = Resource<\n \"Convex.LocalDeployment\",\n LocalDeploymentProps,\n LocalDeploymentAttributes,\n never,\n Providers\n>;\nexport const LocalDeployment = Resource<LocalDeployment>(\"Convex.LocalDeployment\")({ of });\n\nexport const LocalDeploymentProvider = () =>\n Provider.effect(\n LocalDeployment,\n Effect.gen(function* () {\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n return {\n // Always an update: the variables are read and only changed values are written.\n diff: ({ news }) =>\n Effect.succeed(isResolved(news) ? ({ action: \"update\" } as const) : undefined),\n\n read: ({ output }) => Effect.succeed(output),\n\n reconcile: Effect.fn(function* ({ news, output }) {\n const rootDir = news.rootDir ?? \".\";\n const info = readLocalDeployment(rootDir);\n if (info === undefined) return yield* new LocalDeploymentNotFound({ rootDir });\n // Without `source`, a push only sets the variables and removes the names that left `env`.\n yield* push(spawner, info.adminKey, {\n deployment: info.name,\n url: info.url,\n rootDir,\n source: undefined,\n env: news.env,\n previousEnvNames: output?.name === info.name ? output.envNames : [],\n adopt: true,\n previewName: undefined,\n });\n return {\n name: info.name,\n url: info.url,\n siteUrl: info.siteUrl,\n envNames: Object.keys(news.env).sort(),\n };\n }),\n\n delete: () => Effect.void,\n };\n }),\n );\n","// Convex.SharedHubClient: one deployment of an app as a client of the central identity hub, for an\n// app that deploys in its own GitHub Actions run, on any host, and on a laptop as a stage of the same\n// stack.\n//\n// A run in GitHub Actions asks the hub for a new client with a GitHub OIDC token, so the stack needs\n// no key and no Samebase account. The token names the repository. The hub reads\n// `/samebase-verification.json` at the origin of the return address, which must name the same\n// repository, and registers the client on that address. The answer holds the client's own\n// registration access token (RFC 7591), and each later deploy reads the client on the hub with that\n// token (RFC 7592). The hub keeps only hashes, so the state is the only record of the secret and the\n// token.\n//\n// The answer to a production registration also holds the app's initial access token (RFC 7591\n// section 1.2) and the repository id. The state of stage `prod` keeps them. A laptop runs the stack\n// as a stage `dev-<name>`: it reads them with `SharedHubClient.read`, and a client with\n// `deploymentType: \"development\"` asks the hub with the token in place of the GitHub token (RFC 133).\n//\n// A push removes a variable that a deploy stops passing, so a failure here must not drop working\n// variables or stop the deploy. A renewal that fails keeps the saved values. Only a client that\n// cannot work asks for a new one: it is gone, or it has another return address or type. If that\n// request fails, the run gives the off values, so the app has guest sign-in and not a broken button.\n// The off values are the `no-hub` variables of a checkout without a hub: Convex needs the variables,\n// and the app hides the button for this client ID.\n//\n// No text in this file quotes an answer or a fetch error, so no log line can hold a secret.\nimport { Resource } from \"alchemy\";\nimport { isResolved } from \"alchemy/Diff\";\nimport * as Output from \"alchemy/Output\";\nimport * as Provider from \"alchemy/Provider\";\nimport { Stack } from \"alchemy/Stack\";\nimport { State } from \"alchemy/State\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Schema from \"effect/Schema\";\nimport type { Providers } from \"./Providers.ts\";\n\n/** A hung service must not hold a deploy: the time limit of one request. */\nconst REQUEST_TIMEOUT_MS = 30_000;\n\n/** The variables of a deployment without a hub client, as the starter writes them. */\nconst OFF_VALUES = { issuer: \"http://127.0.0.1:1\", clientId: \"no-hub\", clientSecret: \"no-hub\" };\n\ninterface CommonProps {\n /** The stable name of the app, set once in the stack. */\n readonly app: string;\n /**\n * The return address of the hub's sign-ins, such as `${site.siteUrl}/auth/hub/callback`: an https\n * URL whose origin serves `/samebase-verification.json` with the numeric GitHub id of this\n * repository, `{ \"repository\": \"123\" }`. It can come from a resource that this run creates. A\n * development client can also have http on a loopback host, which needs no file.\n */\n readonly redirectUri: string;\n /** Recorded on the hub's client, such as the commit. The hub records \"unknown\" without it. */\n readonly softwareVersion?: string;\n /**\n * The run fails unless the hub confirms the client in this run: it fails when the hub refuses or\n * does not answer a registration or a renewal, and when it suspended the client. Without it, such\n * a run gives the off values or keeps the saved client, so the app deploys anyway. Set it where\n * sign-in is the product. A failed run saves nothing, so the next run asks the hub again.\n */\n readonly required?: boolean;\n}\n\n/**\n * A production or preview client asks with the GitHub OIDC token of the run. A development client\n * asks with the app's initial access token, which `SharedHubClient.read` gives from stage `prod`.\n */\nexport type SharedHubClientProps =\n | (CommonProps & {\n readonly deploymentType: \"production\" | \"preview\";\n readonly initialAccessToken?: never;\n })\n | (CommonProps & {\n readonly deploymentType: \"development\";\n /** Empty before the first production registration: the client gets the off values. */\n readonly initialAccessToken: Redacted.Redacted<string>;\n });\n\nconst DeploymentType = Schema.Literals([\"production\", \"preview\", \"development\"]);\n\nconst Attributes = Schema.Struct({\n /** `off`: no client, and the values below are the off values. */\n status: Schema.Literals([\"on\", \"off\", \"suspended\"]),\n /** The issuer of the hub, which the deployment names to sign in. */\n issuer: Schema.String,\n clientId: Schema.String,\n /** Returned only at registration. */\n clientSecret: Schema.Redacted(Schema.String),\n /** Returned only at registration. It reads and deletes this client on the hub, and nothing else. */\n registrationAccessToken: Schema.Redacted(Schema.String),\n registrationClientUri: Schema.String,\n deploymentType: DeploymentType,\n /** The return address that the client serves. Empty for the off values. */\n redirectUri: Schema.String,\n /**\n * Returned only at a production registration (RFC 7591 section 1.2). It registers development\n * clients of this app. Empty for a preview, for a development client, and for the off values.\n */\n initialAccessToken: Schema.Redacted(Schema.String),\n /** The numeric GitHub id of the repository, with the initial access token. Empty without it. */\n repository: Schema.String,\n});\n\n/**\n * The attributes keep the real values of a suspended client, so that an unblock needs no new client.\n * `SharedHubClient.variables` gives the values that the app gets.\n */\nexport interface SharedHubClientAttributes extends Schema.Schema.Type<typeof Attributes> {}\n\n/**\n * The attributes of a saved row, or undefined when the row does not have this version's shape, such\n * as a row that 0.26 or earlier saved without the token fields. Only a schema issue gives undefined;\n * any other failure of the decoder stops the run with a fixed message. The text of a schema issue\n * can quote a value of the row, so it is never kept.\n */\nconst savedAttributes = (value: unknown) =>\n Schema.decodeUnknownEffect(Attributes)(value).pipe(\n Effect.map((attributes): SharedHubClientAttributes | undefined => attributes),\n Effect.catch(() => Effect.succeed(undefined)),\n Effect.catchDefect(() =>\n Effect.die(\n new SharedHubClientFailed({\n reason: \"the state holds attributes of Convex.SharedHubClient that it cannot read\",\n }),\n ),\n ),\n );\n\n/** The attributes of no client. */\nconst offAttributes = (\n deploymentType: SharedHubClientAttributes[\"deploymentType\"],\n): SharedHubClientAttributes => ({\n status: \"off\",\n issuer: OFF_VALUES.issuer,\n clientId: OFF_VALUES.clientId,\n clientSecret: Redacted.make(OFF_VALUES.clientSecret),\n registrationAccessToken: Redacted.make(\"\"),\n registrationClientUri: \"\",\n deploymentType,\n redirectUri: \"\",\n initialAccessToken: Redacted.make(\"\"),\n repository: \"\",\n});\n\n/** One request gave no usable answer. The reason holds no secret. */\nclass SharedHubClientFailed extends Schema.TaggedError<SharedHubClientFailed>()(\n \"SharedHubClientFailed\",\n { reason: Schema.String },\n) {\n override get message() {\n return `Convex.SharedHubClient: ${this.reason}.`;\n }\n}\n\nconst OidcToken = Schema.Struct({ value: Schema.NonEmptyString });\n\n/** The 201 answer of `POST /hub-clients`. */\nconst NewClient = Schema.Struct({\n issuer: Schema.NonEmptyString,\n client_id: Schema.NonEmptyString,\n client_secret: Schema.NonEmptyString,\n registration_access_token: Schema.NonEmptyString,\n registration_client_uri: Schema.NonEmptyString,\n redirect_uri: Schema.NonEmptyString,\n /**\n * The terms of the shared sign-in service, which the log shows once, for the new client. Exactly\n * this page: the log line must not print a value that the answer chose.\n */\n terms: Schema.Literal(\"https://samebase.com/terms\"),\n /** Only in the answer to a production registration with the GitHub token. */\n initial_access_token: Schema.optionalKey(Schema.NonEmptyString),\n repository: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^\\d+$/))),\n});\n\n/** The other answers of `POST /hub-clients`, by status. */\nconst REFUSALS: Readonly<Record<number, string>> = {\n 400: \"the identity hub refused the request: the return address must be https on a DNS name, and the app name at most 64 characters\",\n 401: \"the identity hub refused the GitHub OIDC token\",\n 403: \"the identity hub does not allow this repository or return address\",\n 404: \"the identity hub has no /hub-clients\",\n 429: \"the identity hub limits new clients\",\n 502: \"GitHub's keys are not available to the identity hub\",\n};\n\n/** The reasons of a 403 that a log line shows. Any other text of the answer is never logged. */\nconst NOT_ALLOWED = new Map([\n [\"paused\", \"the identity hub pauses new clients of third-party apps\"],\n [\"run_not_allowed\", \"the identity hub gives clients only to runs of main and of pull requests\"],\n [\"blocked\", \"Samebase blocked this repository or its owner\"],\n [\"suspended\", \"the identity hub suspended this repository\"],\n [\"too_many_apps\", \"the repository has as many apps on the identity hub as it may\"],\n [\"too_many_clients\", \"the app has as many clients on the identity hub as it may\"],\n [\"app_taken\", \"the app's name belongs to another app on the identity hub\"],\n [\"host_unreachable\", \"the identity hub could not reach the host of the return address\"],\n [\n \"verification_file_missing\",\n \"the host of the return address does not serve /samebase-verification.json\",\n ],\n [\"verification_file_invalid\", \"/samebase-verification.json on the host holds no repository id\"],\n [\"repository_mismatch\", \"/samebase-verification.json on the host names another repository\"],\n [\"app_mismatch\", \"the initial access token belongs to another app on the identity hub\"],\n]);\n\n/** The windows of a 429, by the name that the answer gives. */\nconst RATE_LIMITED = new Map([\n [\"repository\", \"the identity hub gives one repository at most 30 new clients an hour\"],\n [\"owner\", \"the identity hub gives one owner at most 100 new clients an hour\"],\n [\"new_owners\", \"the identity hub takes at most 50 new owners an hour\"],\n]);\n\nconst Refusal = Schema.Struct({ reason: Schema.String });\nconst RateLimited = Schema.Struct({ window: Schema.String });\n\n/** The text of a refusal: a known reason of a 403 or window of a 429, else the text of its status. */\nconst refusalOf = (status: number, body: unknown) => {\n const known =\n status === 403\n ? NOT_ALLOWED.get(\n Option.getOrUndefined(Schema.decodeUnknownOption(Refusal)(body))?.reason ?? \"\",\n )\n : status === 429\n ? RATE_LIMITED.get(\n Option.getOrUndefined(Schema.decodeUnknownOption(RateLimited)(body))?.window ?? \"\",\n )\n : undefined;\n return known ?? REFUSALS[status] ?? \"the identity hub refused the request\";\n};\n\nconst send = (who: string, url: string, token: string, init: { method: string; body?: string }) =>\n Effect.tryPromise({\n try: async () => {\n const response = await fetch(url, {\n ...init,\n headers: { Authorization: `Bearer ${token}`, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n const body: unknown = await response.json().catch(() => undefined);\n return { status: response.status, body };\n },\n catch: () => new SharedHubClientFailed({ reason: `${who} gave no answer` }),\n });\n\nconst decode =\n <S extends Schema.Codec<unknown, unknown>>(schema: S, who: string) =>\n (value: unknown) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.mapError(() => new SharedHubClientFailed({ reason: `${who} gave a bad answer` })),\n );\n\n/** The OIDC token of this run, read right before the call, because it lives for minutes only. */\nconst readOidcToken = (requestUrl: string, requestToken: string) =>\n Effect.gen(function* () {\n const { body, status } = yield* send(\n \"GitHub\",\n `${requestUrl}&audience=samebase`,\n requestToken,\n { method: \"GET\" },\n );\n if (status !== 200) {\n return yield* new SharedHubClientFailed({\n reason: `GitHub gave no OIDC token (HTTP ${status})`,\n });\n }\n return (yield* decode(OidcToken, \"GitHub\")(body)).value;\n });\n\n/** `POST /hub-clients` with `bearer`: the GitHub OIDC token, or the app's initial access token. */\nconst requestNewClient = (props: SharedHubClientProps, bearer: string) =>\n Effect.gen(function* () {\n const { body, status } = yield* send(\n \"The identity hub\",\n `${process.env[\"HUB_URL\"] ?? \"https://auth.samebase.com\"}/hub-clients`,\n bearer,\n {\n method: \"POST\",\n body: JSON.stringify({\n app: props.app,\n redirectUri: props.redirectUri,\n softwareVersion: props.softwareVersion ?? \"unknown\",\n }),\n },\n );\n if (status !== 201) {\n const reason =\n status === 401 && props.deploymentType === \"development\"\n ? \"the identity hub refused the initial access token\"\n : refusalOf(status, body);\n return yield* new SharedHubClientFailed({ reason: `${reason} (HTTP ${status})` });\n }\n const client = yield* decode(NewClient, \"The identity hub\")(body);\n // The hub registers the address that the request sent. The log names the request's, so no\n // value that the answer chose is printed.\n if (client.redirect_uri !== props.redirectUri) {\n return yield* new SharedHubClientFailed({ reason: \"The identity hub gave a bad answer\" });\n }\n yield* Effect.logInfo(\n `Convex.SharedHubClient: ${props.app} on ${props.redirectUri} has a new client of the identity hub. Its use is under ${client.terms}.`,\n );\n // Only a production registration gives the app's token (RFC 7591); any other answer's is dropped.\n const production = props.deploymentType === \"production\";\n return {\n status: \"on\" as const,\n issuer: client.issuer,\n clientId: client.client_id,\n clientSecret: Redacted.make(client.client_secret),\n registrationAccessToken: Redacted.make(client.registration_access_token),\n registrationClientUri: client.registration_client_uri,\n deploymentType: props.deploymentType,\n redirectUri: props.redirectUri,\n initialAccessToken: Redacted.make(production ? (client.initial_access_token ?? \"\") : \"\"),\n repository: production ? (client.repository ?? \"\") : \"\",\n };\n });\n\n/** A new client, or the off values. */\nconst newClient = (props: SharedHubClientProps) => {\n const label = `Convex.SharedHubClient: ${props.app} on ${props.redirectUri} deploys without the hub`;\n const off = offAttributes(props.deploymentType);\n const request = (bearer: Effect.Effect<string, SharedHubClientFailed>) =>\n bearer.pipe(\n Effect.flatMap((token) => requestNewClient(props, token)),\n Effect.catchTag(\"SharedHubClientFailed\", (error) =>\n Effect.logWarning(`${label}: ${error.reason}. The next deploy asks again.`).pipe(\n Effect.as(off),\n ),\n ),\n );\n\n if (props.deploymentType === \"development\") {\n const token = Redacted.value(props.initialAccessToken);\n return token === \"\"\n ? Effect.logInfo(\n \"Convex.SharedHubClient: deploy to main once for Google sign-in on this laptop.\",\n ).pipe(Effect.as(off))\n : request(Effect.succeed(token));\n }\n\n const requestUrl = process.env[\"ACTIONS_ID_TOKEN_REQUEST_URL\"];\n const requestToken = process.env[\"ACTIONS_ID_TOKEN_REQUEST_TOKEN\"];\n // A laptop, or another CI. In a workflow, `id-token: write` gives both, so a workflow without them\n // is a mistake to show, not a normal run.\n if (!requestUrl || !requestToken) {\n return (\n process.env[\"GITHUB_ACTIONS\"] === \"true\"\n ? Effect.logWarning(`${label}: this workflow needs the permission id-token: write.`)\n : Effect.logInfo(`${label}: this run has no GitHub OIDC token.`)\n ).pipe(Effect.as(off));\n }\n return request(readOidcToken(requestUrl, requestToken));\n};\n\n/**\n * The client after a read on the hub, or undefined when the hub says that the client is gone. A\n * read with no usable answer keeps the saved client, except for a required one: a required client\n * passes a run only when the hub confirms it in that run, so a suspension that an earlier run saw,\n * and did not save because that run failed, cannot pass a run that the hub does not answer.\n */\nconst renew = (saved: SharedHubClientAttributes, required: boolean) =>\n Effect.gen(function* () {\n const { status } = yield* send(\n \"The identity hub\",\n saved.registrationClientUri,\n Redacted.value(saved.registrationAccessToken),\n { method: \"GET\" },\n );\n switch (status) {\n case 200:\n return { ...saved, status: \"on\" as const };\n case 401:\n return undefined;\n case 403:\n yield* Effect.logWarning(\n `Convex.SharedHubClient: the hub suspended the client of ${saved.redirectUri}. It keeps its values, and nobody can sign in with it.`,\n );\n return { ...saved, status: \"suspended\" as const };\n default:\n return yield* new SharedHubClientFailed({\n reason: `The identity hub answered HTTP ${status}`,\n });\n }\n }).pipe(\n Effect.catchTag(\"SharedHubClientFailed\", (error) =>\n required\n ? Effect.fail(\n new SharedHubClientFailed({\n reason: `${saved.redirectUri} is required, and the hub did not confirm its client: ${error.reason}`,\n }),\n )\n : Effect.logWarning(\n `Convex.SharedHubClient: ${saved.redirectUri} keeps the saved client: ${error.reason}.`,\n ).pipe(Effect.as(saved)),\n ),\n );\n\n/** A saved row of this resource, whose `attr` `savedAttributes` reads. */\nconst SavedRow = Schema.Struct({\n resourceType: Schema.Literal(\"IdentityHub.SharedClient\"),\n attr: Schema.Unknown,\n});\n\n/**\n * The attributes of the client `id` in another stage of this stack, such as\n * `read(\"HubClient\", { stage: \"prod\" })` in the stage of a laptop, as Outputs: the\n * `initialAccessToken` and the `repository` of the production client. Without that row, the off\n * attributes, with `deploymentType: \"production\"`.\n *\n * `SharedHubClient.ref` is not enough: Alchemy fails the plan with `InvalidReferenceError` when the\n * row is missing, and a laptop before the first deploy to main has none. This read runs when the\n * plan resolves it, with the State service of the running stack and its `get`, so it never creates\n * or upgrades a store. The store revives each secret as `Redacted`, as it does for every read.\n */\nconst read = (id: string, options: { readonly stage: string }) =>\n Output.fromEffect(\n Effect.gen(function* () {\n const stack = yield* Stack;\n const state = yield* yield* State;\n const row = yield* state\n .get({ stack: stack.name, stage: options.stage, fqn: id })\n .pipe(Effect.orDie);\n if (row === undefined) return offAttributes(\"production\");\n const { attr } = yield* Schema.decodeUnknownEffect(SavedRow)(row).pipe(\n Effect.catchCause(() =>\n Effect.die(\n new SharedHubClientFailed({\n reason: `the row ${id} of stage ${options.stage} is not a Convex.SharedHubClient`,\n }),\n ),\n ),\n );\n const saved = yield* savedAttributes(attr);\n if (saved === undefined) {\n return yield* Effect.die(\n new SharedHubClientFailed({\n reason: `the row ${id} of stage ${options.stage} holds attributes that this version cannot read`,\n }),\n );\n }\n return saved;\n }),\n );\n\n/**\n * The three values that the app's deployment gets, such as `HUB_ISSUER`, `HUB_CLIENT_ID`, and\n * `HUB_CLIENT_SECRET`, as Outputs: the client's values when `status` is `on`, else the off values,\n * so that a suspended client gives guest sign-in and keeps its values in state.\n */\nconst variables = (client: SharedHubClient) =>\n Output.map(Output.of(client), (attributes) =>\n attributes.status === \"on\"\n ? {\n issuer: attributes.issuer,\n clientId: attributes.clientId,\n clientSecret: attributes.clientSecret,\n }\n : {\n issuer: OFF_VALUES.issuer,\n clientId: OFF_VALUES.clientId,\n clientSecret: Redacted.make(OFF_VALUES.clientSecret),\n },\n );\n\nexport type SharedHubClient = Resource<\n \"IdentityHub.SharedClient\",\n SharedHubClientProps,\n SharedHubClientAttributes,\n never,\n Providers\n>;\nexport const SharedHubClient = Resource<SharedHubClient>(\"IdentityHub.SharedClient\")({\n read,\n variables,\n});\n\nexport const SharedHubClientProvider = () =>\n Provider.succeed(SharedHubClient, {\n // Always an update, so that each deploy reaches the hub. No attribute is stable, so a push\n // reads the values that this run ended with. The same values cause no other push.\n diff: ({ news }) =>\n Effect.succeed(isResolved(news) ? ({ action: \"update\" } as const) : undefined),\n\n read: ({ output }) => Effect.succeed(output),\n\n // Only a client of the same return address and type is renewed. A saved row without this\n // version's shape, such as one that 0.26 or earlier saved, is no client: the run asks for a new\n // one, which replaces the saved client, and for a production client also replaces the app's\n // initial access token.\n reconcile: Effect.fn(function* ({ news, output }) {\n const saved =\n output === undefined || output.status === \"off\"\n ? undefined\n : yield* savedAttributes(output);\n if (output !== undefined && output.status !== \"off\" && saved === undefined) {\n yield* Effect.logWarning(\n `Convex.SharedHubClient: the saved attributes of ${news.app} on ${news.redirectUri} cannot be read by this version, so this run registers a new client, which replaces the saved one.`,\n );\n }\n const renewed =\n saved?.redirectUri === news.redirectUri && saved.deploymentType === news.deploymentType\n ? yield* renew(saved, news.required === true)\n : undefined;\n const client = renewed ?? (yield* newClient(news));\n if (news.required === true && client.status !== \"on\") {\n return yield* new SharedHubClientFailed({\n reason: `${news.app} on ${news.redirectUri} is required and has no working client (${client.status}). The warning above names the reason`,\n });\n }\n return client;\n }),\n\n // A failed delete does not stop a destroy: the removal date of a preview or development client\n // cleans it up. A destroy can leave a production deployment running, so its client stays.\n delete: ({ output }) =>\n output.deploymentType === \"production\" || output.status === \"off\"\n ? Effect.void\n : Effect.gen(function* () {\n const { status } = yield* send(\n \"The identity hub\",\n output.registrationClientUri,\n Redacted.value(output.registrationAccessToken),\n { method: \"DELETE\" },\n );\n // 401: the client is gone already.\n if (status !== 204 && status !== 401) {\n return yield* new SharedHubClientFailed({\n reason: `The identity hub answered HTTP ${status}`,\n });\n }\n }).pipe(\n Effect.catchTag(\"SharedHubClientFailed\", (error) =>\n Effect.logWarning(\n `Convex.SharedHubClient: the client of ${output.redirectUri} stays on the hub until its removal date: ${error.reason}.`,\n ),\n ),\n ),\n });\n","// The provider collection users merge into a stack:\n// providers: Layer.mergeAll(Cloudflare.providers(), Convex.providers())\nimport * as Provider from \"alchemy/Provider\";\nimport * as Layer from \"effect/Layer\";\nimport { type Credentials, fromConfig } from \"./Credentials.ts\";\nimport { DeploymentProvider, DeploymentResource } from \"./Deployment.ts\";\nimport { HubClient, HubClientProvider } from \"./HubClient.ts\";\nimport { LocalDeployment, LocalDeploymentProvider } from \"./LocalDeployment.ts\";\nimport { ManagementApiLive } from \"./ManagementApi.ts\";\nimport { Project, ProjectProvider } from \"./Project.ts\";\nimport { SharedHubClient, SharedHubClientProvider } from \"./SharedHubClient.ts\";\n\nexport class Providers extends Provider.ProviderCollection<Providers>()(\"Convex\") {}\n\n/**\n * The Convex resource providers. Pass a credentials layer to override the\n * default lookup (`CONVEX_ACCESS_TOKEN`, then the Convex CLI login, and\n * `CONVEX_DEPLOY_KEY`).\n */\nexport const providers = (credentials: Layer.Layer<Credentials> = fromConfig()) =>\n Layer.effect(\n Providers,\n Provider.collection([Project, DeploymentResource, LocalDeployment, HubClient, SharedHubClient]),\n ).pipe(\n Layer.provide(\n Layer.mergeAll(\n ProjectProvider(),\n DeploymentProvider(),\n LocalDeploymentProvider(),\n HubClientProvider(),\n SharedHubClientProvider(),\n ),\n ),\n Layer.provide(ManagementApiLive()),\n Layer.provide(credentials),\n Layer.orDie,\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,iBAAiB,YAK5B,OAAO,IAAI,aAAa;CACtB,IAAI,QAAQ,cAAc,IACxB,OAAO,OAAO,OAAO,oBAAI,IAAI,MAAM,8BAA8B,CAAC;CAEpE,MAAM,YAAY,OAAO,QAAQ,SAAS;CAC1C,MAAM,MAAM,oBAAoB,KAAK,UAAU,SAAS;CAExD,MAAM,YAAW,OADI,MAAA,CACE,SAAS,QAAQ,WAAW,IAAI,EAAE,MAAM,YAAY,QAAQ,QAAQ,GAAG;CAE9F,IAAI,aAAa,KAAA,GAAW;EAC1B,MAAM,WAAW,OAAO,kBAAkB,OAAO,OAAO,EAAE,MAAM,OAAO,OAAO,CAAC,CAAC,CAAC,CAC/E,SAAS,IACX;EACA,IAAI,SAAS,SAAS,QAAQ,WAC5B,OAAO,OAAO,OAAO,oBACnB,IAAI,MACF,qBAAqB,KAAK,UAAU,SAAS,EAAE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;CAAiB;CAAW;AAAe,CAAC,CAChG,CAAC,CAAC,KACA,MAAM,QACJ,MAAM,SACJ,gBAAgB,GAChB,mBAAmB,GACnB,wBAAwB,GACxB,kBAAkB,GAClB,wBAAwB,CAC1B,CACF,GACA,MAAM,QAAQ,kBAAkB,CAAC,GACjC,MAAM,QAAQ,WAAW,GACzB,MAAM,KACR"}
|
package/package.json
CHANGED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// Convex.LocalDeployment: the logged-in local deployment of one folder, which
|
|
2
|
+
// `npx convex deployment create <team>:<project>:local --select` makes and `npx convex dev` runs on
|
|
3
|
+
// this machine. Each folder, such as each git worktree, has its own, with its own data.
|
|
4
|
+
//
|
|
5
|
+
// The resource writes its `env` and nothing else. The running `convex dev` owns the backend and
|
|
6
|
+
// pushes the functions, so the stage of a laptop runs after `convex dev` has started, and the
|
|
7
|
+
// first push of a new local deployment takes the variables that the project's default variables
|
|
8
|
+
// for development gave it. The resource reads the deployment from
|
|
9
|
+
// `.convex/local/default/config.json`, where the Convex CLI keeps its name, ports, and admin key,
|
|
10
|
+
// and writes with that admin key through the same call as for a cloud deployment.
|
|
11
|
+
//
|
|
12
|
+
// A destroy changes nothing: the folder's deployment and its variables stay with the folder.
|
|
13
|
+
import { Resource } from "alchemy";
|
|
14
|
+
import { isResolved } from "alchemy/Diff";
|
|
15
|
+
import * as Provider from "alchemy/Provider";
|
|
16
|
+
import * as Effect from "effect/Effect";
|
|
17
|
+
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
|
|
18
|
+
import * as Schema from "effect/Schema";
|
|
19
|
+
import { readLocalDeployment } from "./ManagementApi.ts";
|
|
20
|
+
import type { Providers } from "./Providers.ts";
|
|
21
|
+
import { type EnvValue, push } from "./Push.ts";
|
|
22
|
+
|
|
23
|
+
/** The folder has no logged-in local deployment. */
|
|
24
|
+
export class LocalDeploymentNotFound extends Schema.TaggedError<LocalDeploymentNotFound>()(
|
|
25
|
+
"LocalDeploymentNotFound",
|
|
26
|
+
{ rootDir: Schema.String },
|
|
27
|
+
) {
|
|
28
|
+
override get message() {
|
|
29
|
+
return `Convex.LocalDeployment: ${this.rootDir} has no logged-in local deployment. Run \`npx convex deployment create <team>:<project>:local --select\` there, then \`npx convex dev\`.`;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The folder's logged-in local deployment, read when the stack's program runs, so that a client
|
|
35
|
+
* can take its `siteUrl`. Fails with `LocalDeploymentNotFound` when the folder has none.
|
|
36
|
+
*/
|
|
37
|
+
const of = (rootDir = ".") => {
|
|
38
|
+
const info = readLocalDeployment(rootDir);
|
|
39
|
+
if (info === undefined) throw new LocalDeploymentNotFound({ rootDir });
|
|
40
|
+
return { name: info.name, url: info.url, siteUrl: info.siteUrl };
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
export interface LocalDeploymentProps {
|
|
44
|
+
/** The folder of the Convex app, where `.convex/local/default` is. The working directory without it. */
|
|
45
|
+
readonly rootDir?: string;
|
|
46
|
+
/** The variables of the deployment. A name that leaves `env` is removed. */
|
|
47
|
+
readonly env: Readonly<Record<string, EnvValue>>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface LocalDeploymentAttributes {
|
|
51
|
+
readonly name: string;
|
|
52
|
+
readonly url: string;
|
|
53
|
+
readonly siteUrl: string;
|
|
54
|
+
/** The names that this resource set, so a name that leaves `env` is removed. */
|
|
55
|
+
readonly envNames: readonly string[];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export type LocalDeployment = Resource<
|
|
59
|
+
"Convex.LocalDeployment",
|
|
60
|
+
LocalDeploymentProps,
|
|
61
|
+
LocalDeploymentAttributes,
|
|
62
|
+
never,
|
|
63
|
+
Providers
|
|
64
|
+
>;
|
|
65
|
+
export const LocalDeployment = Resource<LocalDeployment>("Convex.LocalDeployment")({ of });
|
|
66
|
+
|
|
67
|
+
export const LocalDeploymentProvider = () =>
|
|
68
|
+
Provider.effect(
|
|
69
|
+
LocalDeployment,
|
|
70
|
+
Effect.gen(function* () {
|
|
71
|
+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
|
72
|
+
return {
|
|
73
|
+
// Always an update: the variables are read and only changed values are written.
|
|
74
|
+
diff: ({ news }) =>
|
|
75
|
+
Effect.succeed(isResolved(news) ? ({ action: "update" } as const) : undefined),
|
|
76
|
+
|
|
77
|
+
read: ({ output }) => Effect.succeed(output),
|
|
78
|
+
|
|
79
|
+
reconcile: Effect.fn(function* ({ news, output }) {
|
|
80
|
+
const rootDir = news.rootDir ?? ".";
|
|
81
|
+
const info = readLocalDeployment(rootDir);
|
|
82
|
+
if (info === undefined) return yield* new LocalDeploymentNotFound({ rootDir });
|
|
83
|
+
// Without `source`, a push only sets the variables and removes the names that left `env`.
|
|
84
|
+
yield* push(spawner, info.adminKey, {
|
|
85
|
+
deployment: info.name,
|
|
86
|
+
url: info.url,
|
|
87
|
+
rootDir,
|
|
88
|
+
source: undefined,
|
|
89
|
+
env: news.env,
|
|
90
|
+
previousEnvNames: output?.name === info.name ? output.envNames : [],
|
|
91
|
+
adopt: true,
|
|
92
|
+
previewName: undefined,
|
|
93
|
+
});
|
|
94
|
+
return {
|
|
95
|
+
name: info.name,
|
|
96
|
+
url: info.url,
|
|
97
|
+
siteUrl: info.siteUrl,
|
|
98
|
+
envNames: Object.keys(news.env).sort(),
|
|
99
|
+
};
|
|
100
|
+
}),
|
|
101
|
+
|
|
102
|
+
delete: () => Effect.void,
|
|
103
|
+
};
|
|
104
|
+
}),
|
|
105
|
+
);
|
package/src/ManagementApi.ts
CHANGED
|
@@ -4,10 +4,14 @@
|
|
|
4
4
|
// `{ data, error, response }`. This service turns that into an Effect with one
|
|
5
5
|
// typed error, resolves credentials lazily, and validates the fields the
|
|
6
6
|
// provider relies on at runtime.
|
|
7
|
+
import { readFileSync } from "node:fs";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { parseEnv } from "node:util";
|
|
7
10
|
import { createDeploymentClient, createManagementClient } from "@convex-dev/platform";
|
|
8
11
|
import * as Context from "effect/Context";
|
|
9
12
|
import * as Effect from "effect/Effect";
|
|
10
13
|
import * as Layer from "effect/Layer";
|
|
14
|
+
import * as Option from "effect/Option";
|
|
11
15
|
import * as Redacted from "effect/Redacted";
|
|
12
16
|
import * as Schedule from "effect/Schedule";
|
|
13
17
|
import * as Schema from "effect/Schema";
|
|
@@ -70,15 +74,19 @@ export interface ManagementApiService {
|
|
|
70
74
|
run: (client: DeploymentClient) => Promise<FetchResult<T>>,
|
|
71
75
|
) => Effect.Effect<T, ConvexApiError>;
|
|
72
76
|
/**
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
* Convex CLI
|
|
77
|
-
* the dashboard's team list, and nothing is an error.
|
|
77
|
+
* The team of the credential. A team access token and an OAuth token of a
|
|
78
|
+
* team name it (`GET /token_details`). The Convex CLI login answers 403
|
|
79
|
+
* there, so its team is the team of the project of the deployment that the
|
|
80
|
+
* Convex CLI selected (CONVEX_DEPLOYMENT). Read once for each service.
|
|
78
81
|
*/
|
|
79
|
-
readonly
|
|
80
|
-
|
|
81
|
-
|
|
82
|
+
readonly teamId: Effect.Effect<number, ConvexApiError>;
|
|
83
|
+
/**
|
|
84
|
+
* Team id for a numeric id or a slug, for Convex.HubClient, which names the
|
|
85
|
+
* team of the hub. With a team access token, a slug is checked against the
|
|
86
|
+
* `teamSlug` of the team's projects, so a token of another team fails; with
|
|
87
|
+
* the Convex CLI login, a slug goes to the dashboard's team list.
|
|
88
|
+
*/
|
|
89
|
+
readonly resolveTeamId: (team: string | number) => Effect.Effect<number, ConvexApiError>;
|
|
82
90
|
/**
|
|
83
91
|
* True when a deploy key that Convex returned carries the token of the
|
|
84
92
|
* Management API credential itself. With an OAuth token, create_deploy_key
|
|
@@ -199,6 +207,89 @@ const ProjectSlugRows = Schema.Struct({
|
|
|
199
207
|
items: Schema.Array(Schema.Struct({ teamSlug: Schema.String })),
|
|
200
208
|
});
|
|
201
209
|
|
|
210
|
+
/** GET /deployments/{name}: the project of the deployment. */
|
|
211
|
+
const DeploymentProject = Schema.Struct({ projectId: Schema.Number });
|
|
212
|
+
|
|
213
|
+
/** GET /projects/{id}: the team of the project. */
|
|
214
|
+
const ProjectTeam = Schema.Struct({ teamId: Schema.Number });
|
|
215
|
+
|
|
216
|
+
/** A folder's `.convex/local/default/config.json`, as the Convex CLI writes it. */
|
|
217
|
+
const LocalConfig = Schema.Struct({
|
|
218
|
+
deploymentName: Schema.String,
|
|
219
|
+
ports: Schema.Struct({ cloud: Schema.Number, site: Schema.Number }),
|
|
220
|
+
adminKey: Schema.String,
|
|
221
|
+
/** The project of a logged-in local deployment. An anonymous one has none. */
|
|
222
|
+
cloudProjectId: Schema.Number,
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
export interface LocalDeploymentInfo {
|
|
226
|
+
/** Such as `local-nicu-samebase_com-1`. */
|
|
227
|
+
readonly name: string;
|
|
228
|
+
/** The client URL, `http://127.0.0.1:<cloud port>`. */
|
|
229
|
+
readonly url: string;
|
|
230
|
+
/** The HTTP actions URL, `http://127.0.0.1:<site port>`, the local `CONVEX_SITE_URL`. */
|
|
231
|
+
readonly siteUrl: string;
|
|
232
|
+
/** The Convex project that the deployment belongs to. */
|
|
233
|
+
readonly projectId: number;
|
|
234
|
+
readonly adminKey: Redacted.Redacted<string>;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* The logged-in local deployment of `rootDir`, which `npx convex deployment create
|
|
239
|
+
* <team>:<project>:local` makes: undefined when the folder has none, or only an anonymous one, which
|
|
240
|
+
* belongs to no project.
|
|
241
|
+
*/
|
|
242
|
+
export const readLocalDeployment = (rootDir = "."): LocalDeploymentInfo | undefined => {
|
|
243
|
+
let raw: unknown;
|
|
244
|
+
try {
|
|
245
|
+
raw = JSON.parse(
|
|
246
|
+
readFileSync(join(rootDir, ".convex", "local", "default", "config.json"), "utf8"),
|
|
247
|
+
);
|
|
248
|
+
} catch {
|
|
249
|
+
return undefined;
|
|
250
|
+
}
|
|
251
|
+
const config = Option.getOrUndefined(Schema.decodeUnknownOption(LocalConfig)(raw));
|
|
252
|
+
if (config === undefined || !config.deploymentName.startsWith("local-")) return undefined;
|
|
253
|
+
return {
|
|
254
|
+
name: config.deploymentName,
|
|
255
|
+
url: `http://127.0.0.1:${config.ports.cloud}`,
|
|
256
|
+
siteUrl: `http://127.0.0.1:${config.ports.site}`,
|
|
257
|
+
projectId: config.cloudProjectId,
|
|
258
|
+
adminKey: Redacted.make(config.adminKey),
|
|
259
|
+
};
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* The deployment that the Convex CLI selected: CONVEX_DEPLOYMENT in the environment or in
|
|
264
|
+
* `.env.local` of the working directory, as `npx convex dev` writes it. A cloud deployment
|
|
265
|
+
* (`dev:happy-animal-123`) by its name; a logged-in local deployment (`local:local-team-app`) by the
|
|
266
|
+
* project in the working directory's `.convex/local/default`, when that is the selected one.
|
|
267
|
+
* Undefined when neither has it, and for an anonymous deployment, which is in no project.
|
|
268
|
+
*/
|
|
269
|
+
const selectedDeployment = ():
|
|
270
|
+
| { readonly kind: "cloud"; readonly name: string }
|
|
271
|
+
| { readonly kind: "local"; readonly projectId: number }
|
|
272
|
+
| undefined => {
|
|
273
|
+
const fromEnv = process.env["CONVEX_DEPLOYMENT"];
|
|
274
|
+
const value =
|
|
275
|
+
fromEnv !== undefined && fromEnv !== ""
|
|
276
|
+
? fromEnv
|
|
277
|
+
: (() => {
|
|
278
|
+
try {
|
|
279
|
+
return parseEnv(readFileSync(".env.local", "utf8"))["CONVEX_DEPLOYMENT"];
|
|
280
|
+
} catch {
|
|
281
|
+
return undefined;
|
|
282
|
+
}
|
|
283
|
+
})();
|
|
284
|
+
const localName = /^local:(local-[^:]+)$/.exec(value ?? "")?.[1];
|
|
285
|
+
if (localName !== undefined) {
|
|
286
|
+
const local = readLocalDeployment();
|
|
287
|
+
return local?.name === localName ? { kind: "local", projectId: local.projectId } : undefined;
|
|
288
|
+
}
|
|
289
|
+
const name = /^(?:(?:dev|prod|preview):)?([^:]+)$/.exec(value ?? "")?.[1];
|
|
290
|
+
return name === undefined || name.startsWith("anonymous-") ? undefined : { kind: "cloud", name };
|
|
291
|
+
};
|
|
292
|
+
|
|
202
293
|
/** GET /token_details: the team of a team token, or the project of a project token. */
|
|
203
294
|
const TokenDetails = Schema.Union([
|
|
204
295
|
Schema.Struct({ type: Schema.Literal("teamToken"), teamId: Schema.Number }),
|
|
@@ -263,16 +354,57 @@ const makeService = (source: Effect.Effect<ResolvedCredentials>): ManagementApiS
|
|
|
263
354
|
Effect.map((body) => Schema.decodeUnknownSync(ProjectSlugRows)(body).items[0]?.teamSlug),
|
|
264
355
|
);
|
|
265
356
|
|
|
357
|
+
const projectTokenError = (projectId: number) =>
|
|
358
|
+
new ConvexApiError({
|
|
359
|
+
operation: "resolve team",
|
|
360
|
+
status: 403,
|
|
361
|
+
message: `the access token belongs to project ${projectId}, and a project token cannot create projects. Use a team access token.`,
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
const teamId: ManagementApiService["teamId"] = Effect.runSync(
|
|
365
|
+
Effect.cached(
|
|
366
|
+
Effect.gen(function* () {
|
|
367
|
+
const details = yield* tokenDetails;
|
|
368
|
+
if (details?.type === "teamToken") return details.teamId;
|
|
369
|
+
if (details?.type === "projectToken") return yield* projectTokenError(details.projectId);
|
|
370
|
+
// The Convex CLI login names no team, but the deployment that `npx convex dev` selected
|
|
371
|
+
// belongs to a project, and the project to a team.
|
|
372
|
+
const selected = selectedDeployment();
|
|
373
|
+
if (selected === undefined) {
|
|
374
|
+
return yield* new ConvexApiError({
|
|
375
|
+
operation: "resolve team",
|
|
376
|
+
status: 0,
|
|
377
|
+
message:
|
|
378
|
+
"the Convex CLI login names no team, and no deployment of a project is selected. Run `npx convex dev` once with a cloud deployment, or create a local one with `npx convex deployment create <team>:<project>:local --select`.",
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
const projectId =
|
|
382
|
+
selected.kind === "local"
|
|
383
|
+
? selected.projectId
|
|
384
|
+
: Schema.decodeUnknownSync(DeploymentProject)(
|
|
385
|
+
yield* request("get deployment", (c) =>
|
|
386
|
+
c.GET("/deployments/{deployment_name}", {
|
|
387
|
+
params: { path: { deployment_name: selected.name } },
|
|
388
|
+
}),
|
|
389
|
+
),
|
|
390
|
+
).projectId;
|
|
391
|
+
const project = yield* request("get project", (c) =>
|
|
392
|
+
c.GET("/projects/{project_id}", { params: { path: { project_id: projectId } } }),
|
|
393
|
+
);
|
|
394
|
+
return Schema.decodeUnknownSync(ProjectTeam)(project).teamId;
|
|
395
|
+
}),
|
|
396
|
+
),
|
|
397
|
+
);
|
|
398
|
+
|
|
266
399
|
// The Management API addresses teams by numeric id. The only slug lookup
|
|
267
400
|
// it offers is per project, so a slug falls back to the dashboard's team
|
|
268
401
|
// list, which is unofficial. Pass the numeric team id to skip this.
|
|
269
402
|
const resolveTeamId: ManagementApiService["resolveTeamId"] = (team) =>
|
|
270
403
|
Effect.gen(function* () {
|
|
271
404
|
if (typeof team === "number") return team;
|
|
272
|
-
if (
|
|
405
|
+
if (/^\d+$/.test(team)) return Number(team);
|
|
273
406
|
const details = yield* tokenDetails;
|
|
274
407
|
if (details?.type === "teamToken") {
|
|
275
|
-
if (team === undefined) return details.teamId;
|
|
276
408
|
// The Management API has no team-by-id call, so the slug of the
|
|
277
409
|
// team comes from any of its projects. A team without a project
|
|
278
410
|
// cannot be checked: the numeric id, or no team, is the fix.
|
|
@@ -281,7 +413,7 @@ const makeService = (source: Effect.Effect<ResolvedCredentials>): ManagementApiS
|
|
|
281
413
|
return yield* new ConvexApiError({
|
|
282
414
|
operation: "resolve team",
|
|
283
415
|
status: 0,
|
|
284
|
-
message: `team "${team}" cannot be checked against the access token: team ${details.teamId} has no project yet. Set team to ${details.teamId}
|
|
416
|
+
message: `team "${team}" cannot be checked against the access token: team ${details.teamId} has no project yet. Set team to ${details.teamId}.`,
|
|
285
417
|
});
|
|
286
418
|
}
|
|
287
419
|
if (slug !== team) {
|
|
@@ -293,21 +425,7 @@ const makeService = (source: Effect.Effect<ResolvedCredentials>): ManagementApiS
|
|
|
293
425
|
}
|
|
294
426
|
return details.teamId;
|
|
295
427
|
}
|
|
296
|
-
if (details?.type === "projectToken")
|
|
297
|
-
return yield* new ConvexApiError({
|
|
298
|
-
operation: "resolve team",
|
|
299
|
-
status: 403,
|
|
300
|
-
message: `the access token belongs to project ${details.projectId}, and a project token cannot create projects. Use a team access token.`,
|
|
301
|
-
});
|
|
302
|
-
}
|
|
303
|
-
if (team === undefined) {
|
|
304
|
-
return yield* new ConvexApiError({
|
|
305
|
-
operation: "resolve team",
|
|
306
|
-
status: 0,
|
|
307
|
-
message:
|
|
308
|
-
"set team to the slug or the id of the Convex team: this access token does not name a team.",
|
|
309
|
-
});
|
|
310
|
-
}
|
|
428
|
+
if (details?.type === "projectToken") return yield* projectTokenError(details.projectId);
|
|
311
429
|
const resolved = yield* credentials;
|
|
312
430
|
const rows = yield* Effect.tryPromise({
|
|
313
431
|
try: async () => {
|
|
@@ -355,6 +473,7 @@ const makeService = (source: Effect.Effect<ResolvedCredentials>): ManagementApiS
|
|
|
355
473
|
request,
|
|
356
474
|
requestVoid,
|
|
357
475
|
deploymentRequest,
|
|
476
|
+
teamId,
|
|
358
477
|
resolveTeamId,
|
|
359
478
|
isCredentialToken,
|
|
360
479
|
isOAuthCredential,
|