Compare commits

...
19 changed files with 365 additions and 32 deletions

No files matched your search

@@ -7,14 +7,23 @@ import type {
import { useLanguage } from "@/runtime/i18n/language"
import { usePlatform } from "@/runtime/platform/platform"
import { useServerSDK } from "@/runtime/server/client"
import { formatServerError } from "@/runtime/server/errors"
import { useData } from "@/runtime/server/current"
import { createEffect, createMemo, on, onCleanup } from "solid-js"
import { createStore, produce } from "solid-js/store"
export type ProviderConnectMethod = Extract<IntegrationMethod, { type: "key" | "oauth" }>
export type ProviderConnectMethod = Extract<IntegrationMethod, { type: "key" | "oauth" | "external" }>
type Authorization = IntegrationOauthConnectOutput["data"]
type Polling = {
generation: number
timer?: ReturnType<typeof setTimeout>
disposed: boolean
// An attempt the server still considers open; cancelled when the dialog goes away.
attempt?: Authorization
}
// OpenCode Go and OpenCode Zen both bill through the OpenCode Console, so the
// Console sign-in is the connection method for both providers.
export const CONSOLE_INTEGRATION = "opencode"
@@ -35,7 +44,7 @@ export function providerFormDefaults(fields: ProviderConnectMethod["form"]) {
if (actual === undefined) return false
const equal = Array.isArray(actual)
? typeof condition.value === "string" && actual.includes(condition.value)
? actual.some((item) => item === condition.value)
: actual === condition.value
return condition.op === "eq" ? equal : !equal
@@ -43,7 +52,7 @@ export function providerFormDefaults(fields: ProviderConnectMethod["form"]) {
if (!active) return answer
return { ...answer, [field.key]: field.default }
return Object.assign(answer, { [field.key]: field.default })
}, {})
}
@@ -74,9 +83,8 @@ export function createProviderConnectionController(options: {
// Not createResource: the dialog is owned by whichever page opened it, so reading a pending
// resource here would suspend that page's <Suspense> and blank the screen behind the dialog.
const [integration, setIntegration] = createStore({
const [integration, setIntegration] = createStore<{ loading: boolean; latest?: IntegrationInfo }>({
loading: true,
latest: undefined as IntegrationInfo | undefined,
})
createEffect(
@@ -100,7 +108,8 @@ export function createProviderConnectionController(options: {
const methods = createMemo<ProviderConnectMethod[]>(() => {
const values = integration.latest?.methods.filter(
(method): method is ProviderConnectMethod => method.type === "key" || method.type === "oauth",
(method): method is ProviderConnectMethod =>
method.type === "key" || method.type === "oauth" || method.type === "external",
)
if (values?.length) return [...values]
@@ -108,14 +117,19 @@ export function createProviderConnectionController(options: {
return [{ type: "key", label: language.t("provider.connect.method.apiKey") }]
})
const [store, setStore] = createStore({
methodIndex: undefined as number | undefined,
authorization: undefined as Authorization | undefined,
formAnswer: undefined as FormAnswer | undefined,
const [store, setStore] = createStore<{
methodIndex?: number
authorization?: Authorization
formAnswer?: FormAnswer
// Nothing is in flight until a method is selected; `busy()` reads this, so a truthy initial
// value would keep multi-method providers on the spinner instead of the method list.
state: undefined as "pending" | "waiting" | "refreshing" | "ready" | "error" | "form" | undefined,
error: undefined as string | undefined,
state?: "pending" | "waiting" | "refreshing" | "ready" | "error" | "form"
error?: string
auto: boolean
connected: boolean
browserFailed: boolean
statusFailed: boolean
}>({
auto: false,
// The credential is stored; a retry only needs to reload the catalogs.
connected: false,
@@ -124,12 +138,9 @@ export function createProviderConnectionController(options: {
statusFailed: false,
})
const polling = {
const polling: Polling = {
generation: 0,
timer: undefined as ReturnType<typeof setTimeout> | undefined,
disposed: false,
// An attempt the server still considers open; cancelled when the dialog goes away.
attempt: undefined as Authorization | undefined,
}
const currentMethod = createMemo(() =>
@@ -206,8 +217,6 @@ export function createProviderConnectionController(options: {
)
}
const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error))
const cancelAttempt = () => {
const attempt = polling.attempt
polling.attempt = undefined
@@ -276,7 +285,9 @@ export function createProviderConnectionController(options: {
setStore("statusFailed", true)
dispatch({
type: "auth.error",
error: isConsole() ? language.t("provider.connect.console.statusFailed") : errorMessage(result.error),
error: isConsole()
? language.t("provider.connect.console.statusFailed")
: formatServerError(result.error, language.t),
})
return
@@ -358,8 +369,6 @@ export function createProviderConnectionController(options: {
return
}
if (selected.type !== "oauth") return
if (selected.form?.some((field) => field.type !== "string")) {
dispatch({ type: "auth.error", error: language.t("provider.connect.error.unsupportedFields") })
@@ -368,11 +377,35 @@ export function createProviderConnectionController(options: {
dispatch({ type: "auth.pending" })
if (selected.type === "external") {
const saved = await serverSDK.api.integration.connect
.external({
integrationID: options.provider(),
methodID: selected.id,
answer: Object.keys(merged).length ? merged : undefined,
location: location(),
})
.then(() => ({ ok: true as const }))
.catch((error) => ({ ok: false as const, error }))
if (polling.disposed || generation !== polling.generation) return
if (!saved.ok) {
dispatch({ type: "auth.error", error: formatServerError(saved.error, language.t) })
return
}
await finish()
return
}
const result = await serverSDK.api.integration.oauth
.connect({
integrationID: options.provider(),
methodID: selected.id,
...(Object.keys(merged).length ? { answer: merged } : {}),
answer: Object.keys(merged).length ? merged : undefined,
location: location(),
})
.then((response) => {
@@ -404,7 +437,9 @@ export function createProviderConnectionController(options: {
if (!result.ok) {
dispatch({
type: "auth.error",
error: isConsole() ? language.t("provider.connect.console.startFailed") : errorMessage(result.error),
error: isConsole()
? language.t("provider.connect.console.startFailed")
: formatServerError(result.error, language.t),
})
return
@@ -448,7 +483,7 @@ export function createProviderConnectionController(options: {
integrationID: options.keyProvider?.() ?? options.provider(),
location: location(),
key,
...(store.formAnswer ? { answer: store.formAnswer } : {}),
answer: store.formAnswer,
})
await finish()
}
@@ -468,7 +503,8 @@ export function createProviderConnectionController(options: {
.then(() => ({ ok: true as const }))
.catch((error) => ({ ok: false as const, error }))
if (!result.ok) return errorMessage(result.error) || language.t("provider.connect.oauth.code.invalid")
if (!result.ok)
return formatServerError(result.error, language.t, language.t("provider.connect.oauth.code.invalid"))
await finish()
return undefined
@@ -496,11 +532,13 @@ export function createProviderConnectionController(options: {
authorization: () => store.authorization,
browserFailed: () => store.browserFailed,
// True while nothing useful can be shown yet: the integration is loading, a method is
// about to be picked automatically, or the authorization request is in flight.
// about to be picked automatically, the authorization request is in flight, or an external
// method, which has no view of its own, is refreshing the catalogs after saving.
busy: () =>
integration.loading ||
(store.methodIndex === undefined && !store.auto && autoIndex() !== undefined) ||
store.state === "pending",
store.state === "pending" ||
(store.state === "refreshing" && currentMethod()?.type === "external"),
auth: {
state: () => store.state,
error: () => store.error,
@@ -127,9 +127,29 @@ const authenticate = Effect.fn("cli.auth.login.authenticate")(function* (
) {
if (method.type === "key") return yield* keyLogin(client, integration, method, answer)
if (method.type === "command") return yield* commandLogin(client, integration, method)
if (method.type === "external") return yield* externalLogin(client, integration, method, answer)
return yield* oauthLogin(client, integration, method, answer)
})
const externalLogin = Effect.fn("cli.auth.login.external")(function* (
client: OpenCodeClient,
integration: IntegrationInfo,
method: Extract<ConnectMethod, { type: "external" }>,
answer?: FormAnswer,
) {
const progress = spinner()
progress.start("Saving credential...")
yield* request((signal) =>
client.integration.connect.external(
{ integrationID: integration.id, methodID: method.id, answer, location },
{ signal },
),
).pipe(
Effect.tap(() => Effect.sync(() => progress.stop(`Connected to ${integration.name}`))),
Effect.tapCause(() => Effect.sync(() => progress.stop("Authentication failed", 1))),
)
})
const keyLogin = Effect.fn("cli.auth.login.key")(function* (
client: OpenCodeClient,
integration: IntegrationInfo,
+16 -1
View File
@@ -1597,6 +1597,18 @@ export type IntegrationConnectKeyOperation<E = never> = (
input: IntegrationConnectKeyInput,
) => Effect.Effect<IntegrationConnectKeyOutput, E>
export type IntegrationConnectExternalInput = {
readonly integrationID: Integration.ID
readonly location?: { readonly directory?: string | undefined } | undefined
readonly methodID: Integration.MethodID
readonly answer?: Form.Answer | undefined
readonly label?: string | undefined
}
export type IntegrationConnectExternalOutput = void
export type IntegrationConnectExternalOperation<E = never> = (
input: IntegrationConnectExternalInput,
) => Effect.Effect<IntegrationConnectExternalOutput, E>
export type IntegrationOauthConnectInput = {
readonly integrationID: Integration.ID
readonly location?: { readonly directory?: string | undefined } | undefined
@@ -1687,7 +1699,10 @@ export interface IntegrationApi<E = never> {
readonly list: IntegrationListOperation<E>
readonly get: IntegrationGetOperation<E>
readonly wellknown: { readonly add: IntegrationWellknownAddOperation<E> }
readonly connect: { readonly key: IntegrationConnectKeyOperation<E> }
readonly connect: {
readonly key: IntegrationConnectKeyOperation<E>
readonly external: IntegrationConnectExternalOperation<E>
}
readonly oauth: {
readonly connect: IntegrationOauthConnectOperation<E>
readonly status: IntegrationOauthStatusOperation<E>
+13 -1
View File
@@ -127,6 +127,8 @@ import type {
IntegrationWellknownAddOutput,
IntegrationConnectKeyInput,
IntegrationConnectKeyOutput,
IntegrationConnectExternalInput,
IntegrationConnectExternalOutput,
IntegrationOauthConnectInput,
IntegrationOauthConnectOutput,
IntegrationOauthStatusInput,
@@ -897,6 +899,16 @@ const EndpointIntegrationConnectKey = (raw: RawClient["server.integration"]) =>
}).pipe(Effect.mapError(mapClientError)),
)
const EndpointIntegrationConnectExternal =
(raw: RawClient["server.integration"]) => (input: IntegrationConnectExternalInput) =>
preserveEffect<IntegrationConnectExternalOutput>()(
raw["integration.connect.external"]({
params: { integrationID: input["integrationID"] },
query: { location: input["location"] },
payload: { methodID: input["methodID"], answer: input["answer"], label: input["label"] },
}).pipe(Effect.mapError(mapClientError)),
)
const EndpointIntegrationOauthConnect =
(raw: RawClient["server.integration"]) => (input: IntegrationOauthConnectInput) =>
preserveEffect<IntegrationOauthConnectOutput>()(
@@ -965,7 +977,7 @@ const adaptGroupIntegration = (raw: RawClient["server.integration"]) => ({
list: EndpointIntegrationList(raw),
get: EndpointIntegrationGet(raw),
wellknown: { add: EndpointIntegrationWellknownAdd(raw) },
connect: { key: EndpointIntegrationConnectKey(raw) },
connect: { key: EndpointIntegrationConnectKey(raw), external: EndpointIntegrationConnectExternal(raw) },
oauth: {
connect: EndpointIntegrationOauthConnect(raw),
status: EndpointIntegrationOauthStatus(raw),
@@ -121,6 +121,8 @@ import type {
IntegrationWellknownAddOutput,
IntegrationConnectKeyInput,
IntegrationConnectKeyOutput,
IntegrationConnectExternalInput,
IntegrationConnectExternalOutput,
IntegrationOauthConnectInput,
IntegrationOauthConnectOutput,
IntegrationOauthStatusInput,
@@ -1228,6 +1230,19 @@ export function make(options: ClientOptions) {
},
requestOptions,
),
external: (input: IntegrationConnectExternalInput, requestOptions?: RequestOptions) =>
request<IntegrationConnectExternalOutput>(
{
method: "POST",
path: `/api/integration/${encodeURIComponent(input.integrationID)}/connect/external`,
query: { location: input["location"] },
body: { methodID: input["methodID"], answer: input["answer"], label: input["label"] },
successStatus: 204,
declaredStatuses: [400, 401, 404],
empty: true,
},
requestOptions,
),
},
oauth: {
connect: (input: IntegrationOauthConnectInput, requestOptions?: RequestOptions) =>
@@ -2314,6 +2314,8 @@ export type IntegrationOAuthMethod = { id: string; type: "oauth"; label: string;
export type IntegrationKeyMethod = { type: "key"; label?: string; form?: FormFields }
export type IntegrationExternalMethod = { id: string; type: "external"; label: string; form?: FormFields }
export type CredentialEntry = {
id: string
integrationID: string
@@ -2351,6 +2353,7 @@ export type IntegrationMethod =
| IntegrationOAuthMethod
| IntegrationCommandMethod
| IntegrationKeyMethod
| IntegrationExternalMethod
| IntegrationEnvMethod
export type FormCreated = {
@@ -5688,6 +5691,28 @@ export type IntegrationConnectKeyInput = {
export type IntegrationConnectKeyOutput = void
export type IntegrationConnectExternalInput = {
readonly integrationID: { readonly integrationID: string }["integrationID"]
readonly location?: { readonly location?: { readonly directory?: string | undefined } | undefined }["location"]
readonly methodID: {
readonly methodID: string
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly label?: string | undefined
}["methodID"]
readonly answer?: {
readonly methodID: string
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly label?: string | undefined
}["answer"]
readonly label?: {
readonly methodID: string
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly label?: string | undefined
}["label"]
}
export type IntegrationConnectExternalOutput = void
export type IntegrationOauthConnectInput = {
readonly integrationID: { readonly integrationID: string }["integrationID"]
readonly location?: { readonly location?: { readonly directory?: string | undefined } | undefined }["location"]
+53 -1
View File
@@ -45,6 +45,9 @@ export type CommandMethod = Integration.CommandMethod
export const KeyMethod = Integration.KeyMethod
export type KeyMethod = Integration.KeyMethod
export const ExternalMethod = Integration.ExternalMethod
export type ExternalMethod = Integration.ExternalMethod
export const EnvMethod = Integration.EnvMethod
export type EnvMethod = Integration.EnvMethod
@@ -82,6 +85,11 @@ export interface KeyImplementation {
readonly method: KeyMethod
}
export interface ExternalImplementation {
readonly integrationID: ID
readonly method: ExternalMethod
}
export interface CommandImplementation {
readonly integrationID: ID
readonly method: CommandMethod
@@ -92,7 +100,12 @@ export interface EnvImplementation {
readonly method: EnvMethod
}
export type Implementation = OAuthImplementation | CommandImplementation | KeyImplementation | EnvImplementation
export type Implementation =
| OAuthImplementation
| CommandImplementation
| KeyImplementation
| ExternalImplementation
| EnvImplementation
export const Attempt = Integration.Attempt
export type Attempt = Integration.Attempt
@@ -180,6 +193,17 @@ export interface Interface extends State.Transformable<Editor> {
/** User-facing label for the stored credential. */
readonly label?: string
}) => Effect.Effect<void, AuthorizationError>
/** Runs an external method and stores a reference configured by its form answers. */
readonly external: (input: {
/** Integration receiving the credential. */
readonly integrationID: ID
/** External method that defines the form and credential source. */
readonly methodID: MethodID
/** Values collected from the method's form fields. */
readonly answer?: Form.Answer
/** User-facing label for the stored credential. */
readonly label?: string
}) => Effect.Effect<void, AuthorizationError>
/** Selects a stored credential as the active integration connection. */
readonly activate: (credentialID: Credential.ID) => Effect.Effect<void>
/** Updates a stored credential exposed as a connection. */
@@ -327,6 +351,8 @@ const layer = Layer.effect(
return method.id === implementation.method.id
if (method.type === "command" && implementation.method.type === "command")
return method.id === implementation.method.id
if (method.type === "external" && implementation.method.type === "external")
return method.id === implementation.method.id
return true
})
if (index === -1) current.methods.push(implementation.method as Types.DeepMutable<Method>)
@@ -345,6 +371,7 @@ const layer = Layer.effect(
if (candidate.type !== method.type) return false
if (candidate.type === "oauth" && method.type === "oauth") return candidate.id === method.id
if (candidate.type === "command" && method.type === "command") return candidate.id === method.id
if (candidate.type === "external" && method.type === "external") return candidate.id === method.id
return true
})
if (index !== -1) current.methods.splice(index, 1)
@@ -736,6 +763,31 @@ const layer = Layer.effect(
}),
})
}),
external: Effect.fn("Integration.connection.external")(function* (input) {
const method = state
.get()
.integrations.get(input.integrationID)
?.methods.find((method) => method.type === "external" && method.id === input.methodID)
if (method?.type !== "external")
return yield* new AuthorizationError({ cause: new Error(`External method not found: ${input.methodID}`) })
const answer = input.answer ?? {}
if (method.form) {
const invalid = Form.validateFields(method.form) ?? Form.validateAnswer(method.form, answer)
if (invalid) return yield* new AuthorizationError({ cause: new Error(invalid) })
}
if (!method.form && Object.keys(answer).length > 0) {
return yield* new AuthorizationError({ cause: new Error("External method does not accept a form answer") })
}
yield* createCredential({
integrationID: input.integrationID,
label: input.label,
value: Credential.External.make({
type: "external",
methodID: method.id,
...(Object.keys(answer).length > 0 ? { metadata: answer } : {}),
}),
})
}),
activate: Effect.fn("Integration.connection.activate")((credentialID) => credentials.activate(credentialID)),
update: Effect.fn("Integration.connection.update")((credentialID, updates) =>
credentials.update(credentialID, updates),
+13
View File
@@ -286,6 +286,13 @@ export const make = Effect.fn("PluginHost.make")(function* (
answer: input.answer,
label: input.label,
}),
external: (input) =>
integration.connection.external({
integrationID: Integration.ID.make(input.integrationID),
methodID: Integration.MethodID.make(input.methodID),
answer: input.answer,
label: input.label,
}),
},
oauth: {
connect: (input) =>
@@ -665,6 +672,12 @@ function methodImplementation(input: IntegrationMethodRegistration): Integration
method: { ...input.method, id: Integration.MethodID.make(input.method.id) },
}
}
if (input.method.type === "external") {
return {
integrationID: Integration.ID.make(input.integrationID),
method: { ...input.method, id: Integration.MethodID.make(input.method.id) },
}
}
return {
integrationID: Integration.ID.make(input.integrationID),
method: input.method,
+1
View File
@@ -32,6 +32,7 @@ const integrations = Layer.mock(Integration.Service, {
active: () => Effect.undefined,
resolve: () => Effect.die("unused"),
key: () => Effect.die("unused"),
external: () => Effect.die("unused"),
activate: () => Effect.die("unused"),
update: () => Effect.die("unused"),
remove: () => Effect.die("unused"),
+1
View File
@@ -330,6 +330,7 @@ function resourceMcpLayer(
active: unusedIntegration,
resolve: unusedIntegration,
key: unusedIntegration,
external: unusedIntegration,
activate: unusedIntegration,
update: unusedIntegration,
remove: unusedIntegration,
@@ -372,6 +372,7 @@ describe("ModelResolver", () => {
},
resolve: () => Effect.die("unused"),
key: () => Effect.die("unused"),
external: () => Effect.die("unused"),
activate: () => Effect.die("unused"),
update: () => Effect.die("unused"),
remove: () => Effect.die("unused"),
+13 -1
View File
@@ -78,6 +78,7 @@ export function host(overrides: Overrides = {}): Plugin.Context {
get: () => Effect.die("unused integration.get"),
connect: {
key: () => Effect.die("unused integration.connect.key"),
external: () => Effect.die("unused integration.connect.external"),
},
oauth: {
connect: () => Effect.die("unused integration.oauth.connect"),
@@ -297,6 +298,7 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
get: () => Effect.die("unused integration.get"),
connect: {
key: () => Effect.die("unused integration.connect.key"),
external: () => Effect.die("unused integration.connect.external"),
},
oauth: {
connect: () => Effect.die("unused integration.oauth.connect"),
@@ -409,6 +411,16 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
})
return
}
if (input.method.type === "external") {
editor.method.update({
integrationID: Integration.ID.make(input.integrationID),
method: {
...input.method,
id: Integration.MethodID.make(input.method.id),
},
})
return
}
editor.method.update({
integrationID: Integration.ID.make(input.integrationID),
method: input.method,
@@ -459,7 +471,7 @@ export function webSearchHost(websearch: WebSearch.Interface): Plugin.Context["w
}
function internalMethod(value: IntegrationMethod): Integration.Method {
if (value.type === "oauth" || value.type === "command") {
if (value.type === "oauth" || value.type === "command" || value.type === "external") {
return { ...value, id: Integration.MethodID.make(value.id) }
}
return value
+12
View File
@@ -28,6 +28,13 @@ export interface IntegrationKeyMethod {
readonly form?: Form.Fields
}
export interface IntegrationExternalMethod {
readonly id: string
readonly type: "external"
readonly label: string
readonly form?: Form.Fields
}
export interface IntegrationEnvMethod {
readonly type: "env"
readonly names: ReadonlyArray<string>
@@ -37,6 +44,7 @@ export type IntegrationMethod =
| IntegrationOAuthMethod
| IntegrationCommandMethod
| IntegrationKeyMethod
| IntegrationExternalMethod
| IntegrationEnvMethod
export type IntegrationOAuthAuthorization = {
@@ -70,6 +78,10 @@ export type IntegrationMethodRegistration =
readonly integrationID: string
readonly method: IntegrationKeyMethod
}
| {
readonly integrationID: string
readonly method: IntegrationExternalMethod
}
| {
readonly integrationID: string
readonly method: IntegrationEnvMethod
+4
View File
@@ -356,6 +356,10 @@ export function fromPromise(plugin: Plugin) {
get: adaptApiMethod(IntegrationEndpoints["integration.get"], host.integration.get),
connect: {
key: adaptApiMethod(IntegrationEndpoints["integration.connect.key"], host.integration.connect.key),
external: adaptApiMethod(
IntegrationEndpoints["integration.connect.external"],
host.integration.connect.external,
),
},
oauth: {
connect: adaptApiMethod(
@@ -27,6 +27,13 @@ export interface IntegrationKeyMethod {
readonly form?: Form.Fields
}
export interface IntegrationExternalMethod {
readonly id: string
readonly type: "external"
readonly label: string
readonly form?: Form.Fields
}
export interface IntegrationEnvMethod {
readonly type: "env"
readonly names: ReadonlyArray<string>
@@ -36,6 +43,7 @@ export type IntegrationMethod =
| IntegrationOAuthMethod
| IntegrationCommandMethod
| IntegrationKeyMethod
| IntegrationExternalMethod
| IntegrationEnvMethod
export type IntegrationOAuthAuthorization = {
@@ -68,6 +76,7 @@ export type IntegrationMethodRegistration =
readonly integrationID: string
readonly method: IntegrationKeyMethod
}
| { readonly integrationID: string; readonly method: IntegrationExternalMethod }
| { readonly integrationID: string; readonly method: IntegrationEnvMethod }
export interface IntegrationEditor {
@@ -79,6 +79,27 @@ export const IntegrationGroup = HttpApiGroup.make("server.integration")
}),
),
)
.add(
HttpApiEndpoint.post("integration.connect.external", "/api/integration/:integrationID/connect/external", {
params: { integrationID: Integration.ID },
query: LocationQuery,
payload: Schema.Struct({
methodID: Integration.MethodID,
answer: Schema.optional(Form.Answer),
label: Schema.optional(Schema.String),
}),
success: HttpApiSchema.NoContent,
error: [IntegrationNotFoundError, InvalidRequestError],
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(
OpenApi.annotations({
identifier: "integration.connect.external",
summary: "Connect with external credentials",
description: "Run an external authentication method and store a reference to its credential source.",
}),
),
)
.add(
HttpApiEndpoint.post("integration.oauth.connect", "/api/integration/:integrationID/connect/oauth", {
params: { integrationID: Integration.ID },
+10 -1
View File
@@ -38,13 +38,22 @@ export const KeyMethod = Schema.Struct({
form: optional(Form.Fields),
}).annotate({ identifier: "Integration.KeyMethod" })
/** Saves a reference to credentials managed outside opencode, configured by the form answers. */
export interface ExternalMethod extends Schema.Schema.Type<typeof ExternalMethod> {}
export const ExternalMethod = Schema.Struct({
id: MethodID,
type: Schema.Literal("external"),
label: Schema.String,
form: optional(Form.Fields),
}).annotate({ identifier: "Integration.ExternalMethod" })
export interface EnvMethod extends Schema.Schema.Type<typeof EnvMethod> {}
export const EnvMethod = Schema.Struct({
type: Schema.Literal("env"),
names: Schema.Array(Schema.String),
}).annotate({ identifier: "Integration.EnvMethod" })
export const Method = Schema.Union([OAuthMethod, CommandMethod, KeyMethod, EnvMethod])
export const Method = Schema.Union([OAuthMethod, CommandMethod, KeyMethod, ExternalMethod, EnvMethod])
.pipe(Schema.toTaggedUnion("type"))
.annotate({ identifier: "Integration.Method" })
export type Method = typeof Method.Type
@@ -84,6 +84,26 @@ export const IntegrationHandler = HttpApiBuilder.group(Api, "server.integration"
return HttpApiSchema.NoContent.make()
}),
)
.handle(
"integration.connect.external",
Effect.fn(function* (ctx) {
const service = yield* Integration.Service
if (!(yield* service.get(ctx.params.integrationID)))
return yield* new IntegrationNotFoundError({
integrationID: ctx.params.integrationID,
message: `Integration not found: ${ctx.params.integrationID}`,
})
yield* authorize(
service.connection.external({
integrationID: ctx.params.integrationID,
methodID: ctx.payload.methodID,
answer: ctx.payload.answer,
label: ctx.payload.label,
}),
)
return HttpApiSchema.NoContent.make()
}),
)
.handle(
"integration.oauth.connect",
Effect.fn(function* (ctx) {
@@ -309,9 +309,62 @@ function openMethod(
))
return
}
if (method.type === "external") {
void beginExternal(integration, method, location, dialog, onConnected)
return
}
void beginOAuth(integration, method, location, dialog, onConnected)
}
async function beginExternal(
integration: IntegrationInfo,
method: Extract<ConnectMethod, { type: "external" }>,
location: LocationRef,
dialog: ReturnType<typeof useDialog>,
onConnected?: OnIntegrationConnected,
) {
const answer = method.form ? await formAnswer(dialog, method.label, method.form) : undefined
if (answer === null) return
dialog.replace(() => (
<ExternalStarting
integration={integration}
method={method}
location={location}
answer={answer}
onConnected={onConnected}
/>
))
}
function ExternalStarting(props: {
integration: IntegrationInfo
method: Extract<ConnectMethod, { type: "external" }>
location: LocationRef
answer?: FormAnswer
onConnected?: OnIntegrationConnected
}) {
const data = useData()
const dialog = useDialog()
const client = useClient()
const toast = useToast()
onMount(() => {
void client.api.integration.connect
.external({
integrationID: props.integration.id,
location: locationQuery(props.location),
methodID: props.method.id,
...(props.answer ? { answer: props.answer } : {}),
})
.then(() => connected(props.integration, props.location, data, dialog, toast, props.onConnected))
.catch((cause) => {
toast.show({ variant: "error", message: errorMessage(cause) })
dialog.clear()
})
})
return <OAuthView title={props.method.label} message="Connecting…" />
}
async function beginKey(
integration: IntegrationInfo,
method: Extract<ConnectMethod, { type: "key" }>,