Repository navigation
feat: add Discord integration (mirrors Slack, shares provider plumbing in core) #51
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
8c9d80b
feat: add Discord integration, sharing provider plumbing with Slack
G3root 5021a77
Refine application behavior and UI implementation
G3root ab9a0b3
Harden Discord guild connections and channel validation
G3root c8c7fa1
Add metadata to integration notifications and Discord confirmations
G3root File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,10 +1,10 @@ | ||
| # Integration glossary | ||
|
|
||
| - **Provider**: an external integration family. V1 implements the `webhook` and `slack` providers. | ||
| - **Provider**: an external integration family. V1 implements the `webhook`, `slack`, and `discord` providers. | ||
| - **Connection**: an organization-owned provider account or endpoint. A V1 webhook endpoint is one connection. | ||
| - **Capability**: a provider feature, such as outbound event delivery. | ||
| - **Route**: a configured capability instance below a connection. For webhooks it selects V1 event types. | ||
| - **Integration Event**: an immutable, versioned fact recorded for external delivery. | ||
| - **Delivery**: one durable attemptable execution of an event for one route; its ID is stable across retries. | ||
| - **Inbox Event**: a future durable inbound provider event. It is not implemented for V1 webhooks. | ||
| - **Binding**: a future durable local-to-remote entity relationship used by bidirectional sync. It is not implemented for V1; Slack identities currently resolve through the user table (email match or stable synthetic email). | ||
| - **Binding**: a future durable local-to-remote entity relationship used by bidirectional sync. It is not implemented for V1; Slack and Discord identities currently resolve through the user table (email match where available, or stable synthetic email). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,194 @@ | ||
| import { Database } from "@feeblo/db"; | ||
| import { | ||
| DiscordInboundService, | ||
| DiscordIntegrationConfig, | ||
| DiscordManagementService, | ||
| parseDiscordOAuthCallbackUrl, | ||
| } from "@feeblo/domain/integration/discord"; | ||
| import type { IntegrationProviderRegistry } from "@feeblo/integration-core"; | ||
| import { DiscordOAuthState } from "@feeblo/integration-discord"; | ||
| import type { ParsedDiscordInboundRequest } from "@feeblo/integration-discord/inbound-schema"; | ||
| import { discordProviderKey } from "@feeblo/integration-discord/manifest"; | ||
| import * as Effect from "effect/Effect"; | ||
| import * as Exit from "effect/Exit"; | ||
| import * as Layer from "effect/Layer"; | ||
| import * as Option from "effect/Option"; | ||
| import * as Schema from "effect/Schema"; | ||
| import * as HttpHeaders from "effect/unstable/http/Headers"; | ||
| import * as HttpRouter from "effect/unstable/http/HttpRouter"; | ||
| import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest"; | ||
| import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse"; | ||
|
|
||
| /** | ||
| * Discord HTTP surface: the OAuth callback and the single interactions | ||
| * endpoint. Every interaction (ping, slash command, context menu, modal | ||
| * submit) arrives at `/discord/interactions`, is signature-verified by the | ||
| * Discord provider inbound handler before any domain work runs, and the | ||
| * domain service answers with the interaction callback JSON. | ||
| */ | ||
|
|
||
| const headerValue = ( | ||
| request: HttpServerRequest.HttpServerRequest, | ||
| name: string | ||
| ): string | undefined => | ||
| Option.getOrUndefined(HttpHeaders.get(request.headers, name)); | ||
|
|
||
| /** | ||
| * Cheap narrow back to the provider's parsed payload. The inbound handler has | ||
| * already signature-verified and fully decoded the body, so this guard only | ||
| * discriminates on the `kind` tag instead of re-running the full schema. | ||
| */ | ||
| const isParsedDiscordInboundRequest = ( | ||
| value: unknown | ||
| ): value is ParsedDiscordInboundRequest => | ||
| typeof value === "object" && | ||
| value !== null && | ||
| "kind" in value && | ||
| (value.kind === "ping" || | ||
| value.kind === "application_command" || | ||
| value.kind === "modal_submit" || | ||
| value.kind === "unknown"); | ||
|
|
||
| const handleInteraction = ( | ||
| request: HttpServerRequest.HttpServerRequest, | ||
| registry: IntegrationProviderRegistry | ||
| ) => | ||
| Effect.gen(function* () { | ||
| const inboundHandler = registry.getInboundHandler({ | ||
| capabilityKey: "interactions", | ||
| provider: discordProviderKey, | ||
| }); | ||
| if (inboundHandler === undefined) { | ||
| return HttpServerResponse.text("not found", { status: 404 }); | ||
| } | ||
| const rawBody = yield* request.text; | ||
| const response = yield* inboundHandler.handle({ | ||
| headers: { | ||
| "x-signature-ed25519": headerValue(request, "x-signature-ed25519"), | ||
| "x-signature-timestamp": headerValue(request, "x-signature-timestamp"), | ||
| }, | ||
| rawBody, | ||
| }); | ||
| if (response.status !== 200) { | ||
| return HttpServerResponse.text(String(response.body), { | ||
| status: response.status, | ||
| }); | ||
| } | ||
| // The inbound handler already signature-verified and decoded the payload; | ||
| // its 200 body is always a `ParsedDiscordInboundRequest` produced by this | ||
| // package. A tag-only guard restores the erased type without a second | ||
| // full decode; a malformed body is still a client error, not a crash. | ||
| if (!isParsedDiscordInboundRequest(response.body)) { | ||
| return HttpServerResponse.text("invalid inbound payload", { | ||
| status: 400, | ||
| }); | ||
| } | ||
| const inbound = yield* DiscordInboundService; | ||
| const result = yield* inbound.handleInteraction(response.body.payload); | ||
| return result.body === undefined | ||
| ? HttpServerResponse.empty({ status: result.status }) | ||
| : HttpServerResponse.jsonUnsafe(result.body, { status: result.status }); | ||
| }); | ||
|
|
||
| const settingsRedirect = ( | ||
| appUrl: string, | ||
| status: "connected" | "error", | ||
| message: string, | ||
| organizationId?: string | ||
| ) => { | ||
| const base = | ||
| organizationId === undefined | ||
| ? `${appUrl}/settings/integrations` | ||
| : `${appUrl}/${organizationId}/settings/integrations`; | ||
| return `${base}?discord=${status}&message=${encodeURIComponent(message)}`; | ||
| }; | ||
|
|
||
| const organizationIdFromOAuthState = (state: string | null) => | ||
| state === null | ||
| ? undefined | ||
| : Option.getOrUndefined( | ||
| Schema.decodeUnknownOption(Schema.fromJsonString(DiscordOAuthState))( | ||
| state | ||
| ).pipe(Option.map(({ organizationId }) => organizationId)) | ||
| ); | ||
|
|
||
| /** OAuth callback router; completes the install and redirects to the dashboard settings page. */ | ||
| export const makeDiscordOAuthCallbackRouter = () => | ||
| HttpRouter.use((router) => | ||
| router.add( | ||
| "GET", | ||
| "/discord/oauth/callback", | ||
| (request: HttpServerRequest.HttpServerRequest) => | ||
| Effect.gen(function* () { | ||
| const config = yield* DiscordIntegrationConfig; | ||
| // request.url is the relative path (e.g. | ||
| // /discord/oauth/callback?code=…); parse it without a base URL. | ||
| const { code, error, state } = parseDiscordOAuthCallbackUrl( | ||
| request.url | ||
| ); | ||
| if (error !== null) { | ||
| return HttpServerResponse.redirect( | ||
| settingsRedirect( | ||
| config.appUrl, | ||
| "error", | ||
| "Discord installation was cancelled or denied.", | ||
| organizationIdFromOAuthState(state) | ||
| ) | ||
| ); | ||
| } | ||
| if (code === null || state === null) { | ||
| return HttpServerResponse.redirect( | ||
| settingsRedirect( | ||
| config.appUrl, | ||
| "error", | ||
| "Discord installation failed.", | ||
| organizationIdFromOAuthState(state) | ||
| ) | ||
| ); | ||
| } | ||
| const management = yield* DiscordManagementService; | ||
| const completed = yield* Effect.exit( | ||
| management.connectComplete({ code, state }) | ||
| ); | ||
| if (Exit.isFailure(completed)) { | ||
| return HttpServerResponse.redirect( | ||
| settingsRedirect( | ||
| config.appUrl, | ||
| "error", | ||
| "Discord installation failed." | ||
| ) | ||
| ); | ||
| } | ||
| return HttpServerResponse.redirect( | ||
| settingsRedirect( | ||
| config.appUrl, | ||
| "connected", | ||
| "Feeblo is now connected to Discord.", | ||
| completed.value.organizationId | ||
| ) | ||
| ); | ||
| }).pipe(Effect.orDie) | ||
| ) | ||
| ).pipe(Layer.provide(Database.DatabaseContextLive), Layer.orDie); | ||
|
|
||
| /** Interactions router for every Discord interaction type. */ | ||
| const makeDiscordInteractionsRouter = (registry: IntegrationProviderRegistry) => | ||
| HttpRouter.use((router) => | ||
| router.add( | ||
| "POST", | ||
| "/discord/interactions", | ||
| (request: HttpServerRequest.HttpServerRequest) => | ||
| handleInteraction(request, registry).pipe(Effect.orDie) | ||
| ) | ||
| ); | ||
|
|
||
| /** | ||
| * Complete Discord HTTP surface. The routers provide their own service layers | ||
| * (management, inbound, repositories, database) so the composition root only | ||
| * has to hand over the provider registry. | ||
| */ | ||
| export const makeDiscordRouters = (registry: IntegrationProviderRegistry) => | ||
| Layer.mergeAll( | ||
| makeDiscordOAuthCallbackRouter(), | ||
| makeDiscordInteractionsRouter(registry) | ||
| ).pipe(Layer.orDie); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.