Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,20 @@ SLACK_SIGNING_SECRET=
# OPTIONAL: OAuth redirect URL. Defaults to <API_URL>/slack/oauth/callback.
SLACK_OAUTH_REDIRECT_URL=

# [[DISCORD]]
# Discord app credentials. Create a bot at discord.com/developers/applications
# (Application -> Bot -> Reset Token; General Information -> Public Key). The
# OAuth redirect URL must be registered under OAuth2 -> Redirects.
# Leave empty to disable the Discord integration.
DISCORD_CLIENT_ID=
DISCORD_CLIENT_SECRET=
# Application-wide bot token (the same token serves every guild install).
DISCORD_BOT_TOKEN=
# Interaction public key (64 hex chars) used to verify request signatures.
DISCORD_PUBLIC_KEY=
# OPTIONAL: OAuth redirect URL. Defaults to <API_URL>/discord/oauth/callback.
DISCORD_OAUTH_REDIRECT_URL=

# [[BILLING]]
# OPTIONAL: Enables Polar checkout, customer portal, and signed webhooks when
# both credentials are configured. Use sandbox while testing.
Expand Down
4 changes: 2 additions & 2 deletions CONTEXT.md
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).
1 change: 1 addition & 0 deletions apps/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"@feeblo/domain": "workspace:*",
"@feeblo/id": "workspace:*",
"@feeblo/integration-core": "workspace:*",
"@feeblo/integration-discord": "workspace:*",
"@feeblo/integration-webhook": "workspace:*",
"@feeblo/transactional": "workspace:*",
"@feeblo/utils": "workspace:*",
Expand Down
194 changes: 194 additions & 0 deletions apps/server/src/discord.ts
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)
)
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
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);
30 changes: 28 additions & 2 deletions apps/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ import { EntitlementPolicy } from "@feeblo/domain/entitlement/policies";
import { Api } from "@feeblo/domain/http/api";
import { HttpRoute } from "@feeblo/domain/http/router";
import { WebhookIntegrationConfig } from "@feeblo/domain/integration/config";
import {
DiscordFeedbackServiceLive,
DiscordInboundServiceLive,
DiscordIntegrationConfig,
DiscordManagementServiceLive,
DiscordUserServiceLive,
} from "@feeblo/domain/integration/discord";
import {
SlackFeedbackServiceLive,
SlackInboundServiceLive,
Expand Down Expand Up @@ -61,6 +68,7 @@ import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import * as HttpApiScalar from "effect/unstable/httpapi/HttpApiScalar";
import * as RateLimiter from "effect/unstable/persistence/RateLimiter";
import { ServerConfig } from "./config";
import { makeDiscordRouters } from "./discord";
import { e2eRoadmapSeedRouter } from "./e2e-roadmap-seed";
import { e2eSetPlanRouter } from "./e2e-set-plan";
import { makeIntegrationLayers } from "./integrations";
Expand Down Expand Up @@ -195,6 +203,7 @@ const program = Effect.gen(function* () {
Effect.provideService(ServerConfig, config)
);
const SlackRouters = makeSlackRouters(integrationRuntime.registry);
const DiscordRouters = makeDiscordRouters(integrationRuntime.registry);
const ServiceLayers = Layer.mergeAll(
WorkFlowLayer,
SiteRepository.layer,
Expand All @@ -219,6 +228,21 @@ const program = Effect.gen(function* () {
Layer.provide(PostSubscriptionRepository.layer),
Layer.provide(Database.DatabaseContextLive)
),
DiscordManagementServiceLive.pipe(
Layer.provide(DiscordIntegrationConfig.layer),
Layer.provide(Database.DatabaseContextLive)
),
DiscordInboundServiceLive.pipe(
Layer.provide(DiscordUserServiceLive),
Layer.provide(DiscordFeedbackServiceLive),
Layer.provide(BoardRepository.layer),
Layer.provide(EmailOutboxConfig.layer),
Layer.provide(IntegrationEventRecorderLive),
Layer.provide(PostRepository.layer),
Layer.provide(PostStatusRepository.layer),
Layer.provide(PostSubscriptionRepository.layer),
Layer.provide(Database.DatabaseContextLive)
),
EntitlementPolicy.layer.pipe(Layer.provide(WorkspaceRepository.layer))
).pipe(Layer.provideMerge(Database.DatabaseContextLive));
const RootRouterLive: Layer.Layer<never, never, HttpRouter.HttpRouter> =
Expand Down Expand Up @@ -285,7 +309,8 @@ const program = Effect.gen(function* () {
HttpRoute,
BetterAuthRouterLive,
DocsRoute,
SlackRouters
SlackRouters,
DiscordRouters
);
const AllRoutes = MergedRoutes.pipe(
Layer.provide(
Expand Down Expand Up @@ -339,7 +364,8 @@ program.pipe(
ServerConfig.layer,
Database.DatabaseContextLive,
WebhookIntegrationConfig.layer,
SlackIntegrationConfig.layer
SlackIntegrationConfig.layer,
DiscordIntegrationConfig.layer
)
),
NodeRuntime.runMain
Expand Down
24 changes: 21 additions & 3 deletions apps/server/src/integrations.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { currentDb, type Database, schema } from "@feeblo/db";
import { WebhookIntegrationConfig } from "@feeblo/domain/integration/config";
import { DiscordIntegrationConfig } from "@feeblo/domain/integration/discord/config";
import { SlackIntegrationConfig } from "@feeblo/domain/integration/slack/config";
import { WebhookManagementServiceLive } from "@feeblo/domain/integration/webhook-management-live";
import type { WebhookManagementService } from "@feeblo/domain/integration/webhook-management-service";
Expand All @@ -16,6 +17,10 @@ import {
makeIntegrationProviderRegistry,
runIntegrationDeliveryWorker,
} from "@feeblo/integration-core";
import {
makeDiscordCredentialResolver,
makeDiscordProviderRegistration,
} from "@feeblo/integration-discord";
import {
makeSlackCredentialResolver,
makeSlackProviderRegistration,
Expand Down Expand Up @@ -59,6 +64,7 @@ export const makeIntegrationLayers: Effect.Effect<
| Database.Database
| WebhookIntegrationConfig
| SlackIntegrationConfig
| DiscordIntegrationConfig
> = Effect.gen(function* () {
const config = yield* ServerConfig;
const db = yield* currentDb;
Expand Down Expand Up @@ -148,12 +154,24 @@ export const makeIntegrationLayers: Effect.Effect<
credentialResolver: slackCredentialResolver,
signingSecret,
});
// The Slack provider is only exposed when its OAuth client id, client
// secret, and request signing secret are all configured; otherwise the
// server runs webhook-only.
const {
botToken: discordBotToken,
configured: discordConfigured,
publicKey: discordPublicKey,
} = yield* DiscordIntegrationConfig;
const discordCredentialResolver = makeDiscordCredentialResolver({
botToken: discordBotToken,
});
const discordRegistration = makeDiscordProviderRegistration({
credentialResolver: discordCredentialResolver,
publicKey: discordPublicKey,
});
// Providers are only exposed when their credentials are configured;
// otherwise the server runs with the remaining providers only.
const registry = yield* makeIntegrationProviderRegistry([
registration,
...(slackConfigured ? [slackRegistration] : []),
...(discordConfigured ? [discordRegistration] : []),
]);

// Deliveries are claimed only for capability keys the startup-validated
Expand Down
Loading
Loading