GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(server): scheduled tasks can run on a webhook by juliusmarminge · Pull Request #15085 · pingdotgg/t3code

feat(server): scheduled tasks can run on a webhook #15085

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.

Sign up for GitHub

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
juliusmarminge merged 14 commits into main from t3code/webhooks-server
Oct 5, 2026
+2,079 −53
Merged

feat(server): scheduled tasks can run on a webhook #15085

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
699ab02
feat(server): scheduled tasks can run on a webhook
juliusmarminge Oct 3, 2026
7f0a7a2
chore(server): keep webhook helpers module-private
juliusmarminge Oct 3, 2026
ce3c5a7
fix(web,mobile): label webhook tasks until their editors land
juliusmarminge Oct 3, 2026
fdfc501
fix(server): harden the webhook route against floods and races
juliusmarminge Oct 3, 2026
3dd09ab
test(server): drop an unused type directive
juliusmarminge Oct 3, 2026
595eb9e
fix(server): delivery log keeps the newest requests on timestamp ties
juliusmarminge Oct 3, 2026
f9cb655
fix(server): webhook delivery log stays private and bounded
juliusmarminge Oct 3, 2026
75e516b
fix(web): webhook tasks hide run-now and explain unopened deep links
juliusmarminge Oct 3, 2026
2c3ab46
fix(server): webhook saves and dispatch hold up under concurrency
juliusmarminge Oct 3, 2026
90fedc7
fix(web): thread automations panel disables run-now for webhook tasks
juliusmarminge Oct 3, 2026
c230d88
fix(server): rotation and the delivery cap respect recreated tasks
juliusmarminge Oct 3, 2026
d63ef44
fix(server): queue counts are per task generation
juliusmarminge Oct 3, 2026
c8cf017
refactor(server): the webhook route is part of the environment HttpApi
juliusmarminge Oct 3, 2026
08df570
fix(server): queued webhook deliveries skip tasks switched off the we…
juliusmarminge Oct 5, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view
Prev Previous commit
Next Next commit
refactor(server): the webhook route is part of the environment HttpApi
Declare /api/hooks/:hookId/:token as raw endpoints in EnvironmentHttpApi
instead of a hand-wired HttpRouter route. Path params are decoded by the
api, so the manual path slicing and URI decoding go away; the handler
still reads the raw body so signatures are checked over the exact bytes.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
  • Loading branch information

Uh oh!

There was an error while loading. Please reload this page.

@juliusmarminge
juliusmarminge committed Oct 5, 2026
commit c8cf0171e04bbb05034a370e0dc63a289afcf2da

There are no files selected for viewing

25 changes: 22 additions & 3 deletions 25 apps/server/src/scheduledTasks/webhookRoute.test.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,24 +1,43 @@
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Etag from "effect/http/Etag";
import * as HttpPlatform from "effect/http/HttpPlatform";
import * as HttpRouter from "effect/http/HttpRouter";
import * as HttpApi from "effect/http-api/HttpApi";
import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";

import { ScheduledTaskWebhookDeliveryId, ScheduledTaskError } from "@t3tools/contracts";
import {
EnvironmentHttpApi,
ScheduledTaskWebhookDeliveryId,
ScheduledTaskError,
} from "@t3tools/contracts";
import {
ScheduledTaskService,
type WebhookTriggerRequest,
type WebhookTriggerResult,
} from "./ScheduledTaskService.ts";
import { WEBHOOK_MAX_BODY_BYTES, webhookRouteLayer } from "./webhookRoute.ts";
import { WEBHOOK_MAX_BODY_BYTES, webhookHttpApiLayer } from "./webhookRoute.ts";

class WebhookTestApi extends HttpApi.make("environment").add(EnvironmentHttpApi.groups.webhooks) {}

const handlerFor = (
trigger: (
request: WebhookTriggerRequest,
) => Effect.Effect<WebhookTriggerResult, ScheduledTaskError>,
) =>
HttpRouter.toWebHandler(
webhookRouteLayer.pipe(
HttpApiBuilder.layer(WebhookTestApi).pipe(
Layer.provide(webhookHttpApiLayer),
Layer.provide(Layer.mock(ScheduledTaskService)({ triggerWebhook: trigger })),
Layer.provide(
HttpPlatform.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(Etag.layerWeak),
),
),
Layer.provide(NodeServices.layer),
),
{ disableLogger: true },
);
Expand Down
166 changes: 82 additions & 84 deletions 166 apps/server/src/scheduledTasks/webhookRoute.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { EnvironmentHttpApi } from "@t3tools/contracts";
import * as ByteSize from "effect/ByteSize";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage";
import * as HttpRouter from "effect/http/HttpRouter";
import * as HttpServerRequest from "effect/http/HttpServerRequest";
import type * as HttpServerRequest from "effect/http/HttpServerRequest";
import * as HttpServerResponse from "effect/http/HttpServerResponse";
import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";

import * as ScheduledTaskService from "./ScheduledTaskService.ts";

Comment thread
macroscopeapp[bot] marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

Expand All @@ -16,93 +16,91 @@ const json = (status: number, body: Record<string, string>) =>
HttpServerResponse.jsonUnsafe(body, { status });

/**
* Public entry point for webhook tasks: `/api/hooks/:hookId/:token`. It is
* unauthenticated by design; the token in the URL (and an optional signature)
* is the credential, and the service checks both. It is reachable directly,
* over the managed tunnel, or through the relay's stable `/v1/hooks/...` URL.
* Handles `/api/hooks/:hookId/:token` for every accepted method. The endpoint
* is raw so the signature is checked over the exact body bytes; the service
* checks the token and signature. It is reachable directly, over the managed
* tunnel, or through the relay's stable `/v1/hooks/...` URL.
*/
const handleWebhook = (scheduledTasks: ScheduledTaskService.ScheduledTaskService["Service"]) =>
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const url = HttpServerRequest.toURL(request);
if (Option.isNone(url)) return json(400, { error: "bad_request" });

const [hookId, token, ...rest] = url.value.pathname
.slice(`${ScheduledTaskService.WEBHOOK_ROUTE_PREFIX}/`.length)
.split("/");
if (!hookId || !token || rest.length > 0) return json(404, { error: "hook_not_found" });
let taskId: string;
try {
taskId = decodeURIComponent(hookId);
} catch {
return json(404, { error: "hook_not_found" });
}

const contentLength = Number(request.headers["content-length"] ?? "0");
if (!Number.isFinite(contentLength) || contentLength > WEBHOOK_MAX_BODY_BYTES) {
return json(413, { error: "body_too_large" });
}
// Chunked requests carry no content-length, so the reader itself is capped.
const body = yield* request.arrayBuffer.pipe(
Effect.map((buffer) => new Uint8Array(buffer)),
Effect.provideService(
HttpIncomingMessage.MaxBodySize,
ByteSize.bytes(WEBHOOK_MAX_BODY_BYTES),
),
Effect.option,
);
if (Option.isNone(body)) return json(413, { error: "body_too_large_or_unreadable" });
if (body.value.byteLength > WEBHOOK_MAX_BODY_BYTES)
return json(413, { error: "body_too_large" });
const handleWebhook =
(scheduledTasks: ScheduledTaskService.ScheduledTaskService["Service"]) =>
({
params,
request,
}: {
readonly params: { readonly hookId: string; readonly token: string };
readonly request: HttpServerRequest.HttpServerRequest;
}) =>
Effect.gen(function* () {
const contentLength = Number(request.headers["content-length"] ?? "0");
if (!Number.isFinite(contentLength) || contentLength > WEBHOOK_MAX_BODY_BYTES) {
return json(413, { error: "body_too_large" });
}
// Chunked requests carry no content-length, so the reader itself is capped.
const body = yield* request.arrayBuffer.pipe(
Effect.map((buffer) => new Uint8Array(buffer)),
Effect.provideService(
HttpIncomingMessage.MaxBodySize,
ByteSize.bytes(WEBHOOK_MAX_BODY_BYTES),
),
Effect.option,
);
if (Option.isNone(body)) return json(413, { error: "body_too_large_or_unreadable" });
if (body.value.byteLength > WEBHOOK_MAX_BODY_BYTES) {
return json(413, { error: "body_too_large" });
}

const headers: Record<string, string> = {};
for (const [name, value] of Object.entries(request.headers)) {
if (typeof value === "string") headers[name.toLowerCase()] = value;
}
const headers: Record<string, string> = {};
for (const [name, value] of Object.entries(request.headers)) {
if (typeof value === "string") headers[name.toLowerCase()] = value;
}
const queryIndex = request.url.indexOf("?");

const result = yield* scheduledTasks
.triggerWebhook({
hookId: taskId,
token,
method: request.method,
path: `${ScheduledTaskService.WEBHOOK_ROUTE_PREFIX}/${hookId}`,
query: url.value.search.replace(/^\?/, ""),
headers,
body: body.value,
bodyText: new TextDecoder().decode(body.value),
})
.pipe(
Effect.catch((cause) =>
Effect.logWarning("Webhook delivery failed").pipe(
Effect.annotateLogs({ hookId: taskId }),
Effect.andThen(Effect.logDebug("Webhook delivery failure cause", { cause })),
Effect.as({ _tag: "error" as const }),
const result = yield* scheduledTasks
.triggerWebhook({
hookId: params.hookId,
token: params.token,
method: request.method,
path: `${ScheduledTaskService.WEBHOOK_ROUTE_PREFIX}/${encodeURIComponent(params.hookId)}`,
query: queryIndex === -1 ? "" : request.url.slice(queryIndex + 1),
headers,
body: body.value,
bodyText: new TextDecoder().decode(body.value),
})
.pipe(
Effect.catch((cause) =>
Effect.logWarning("Webhook delivery failed").pipe(
Effect.annotateLogs({ hookId: params.hookId }),
Effect.andThen(Effect.logDebug("Webhook delivery failure cause", { cause })),
Effect.as({ _tag: "error" as const }),
),
),
),
);
);

switch (result._tag) {
case "accepted":
return json(202, { deliveryId: result.deliveryId });
case "not_found":
return json(404, { error: "hook_not_found" });
case "rejected_signature":
return json(401, { error: "invalid_signature" });
case "disabled":
return json(409, { error: "hook_disabled" });
case "rate_limited":
return json(429, { error: "rate_limited" });
case "error":
return json(500, { error: "internal_error" });
}
});
switch (result._tag) {
case "accepted":
return json(202, { deliveryId: result.deliveryId });
case "not_found":
return json(404, { error: "hook_not_found" });
case "rejected_signature":
return json(401, { error: "invalid_signature" });
case "disabled":
return json(409, { error: "hook_disabled" });
case "rate_limited":
return json(429, { error: "rate_limited" });
case "error":
return json(500, { error: "internal_error" });
}
});

export const webhookRouteLayer = Layer.effectDiscard(
Effect.gen(function* () {
const router = yield* HttpRouter.HttpRouter;
export const webhookHttpApiLayer = HttpApiBuilder.group(
EnvironmentHttpApi,
"webhooks",
Effect.fnUntraced(function* (handlers) {
const handler = handleWebhook(yield* ScheduledTaskService.ScheduledTaskService);
for (const method of ["POST", "PUT", "PATCH", "GET"] as const) {
yield* router.add(method, `${ScheduledTaskService.WEBHOOK_ROUTE_PREFIX}/*`, handler);
}
return handlers
.handleRaw("webhookPost", handler)
.handleRaw("webhookPut", handler)
.handleRaw("webhookPatch", handler)
.handleRaw("webhookGet", handler);
}),
);
4 changes: 2 additions & 2 deletions 4 apps/server/src/server.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts";
import * as ReplayMarkers from "./auth/replayMarkers.ts";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import { webhookRouteLayer } from "./scheduledTasks/webhookRoute.ts";
import { webhookHttpApiLayer } from "./scheduledTasks/webhookRoute.ts";
import { ScheduledTaskWebhookOrigin } from "./scheduledTasks/ScheduledTaskService.ts";
import { CLOUD_ENDPOINT_RUNTIME_CONFIG, RELAY_URL_SECRET } from "./cloud/config.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
Expand Down Expand Up @@ -672,12 +672,12 @@ const makeRoutesLayer = Layer.mergeAll(
Layer.provide(pullRequestHttpApiLayer),
Layer.provide(projectHttpApiLayer),
Layer.provide(serverEnvironmentHttpApiLayer),
Layer.provide(webhookHttpApiLayer),
Layer.provide(environmentAuthenticatedAuthLayer),
),
otlpTracesProxyRouteLayer,
assetRouteLayer,
attachmentUploadRouteLayer,
webhookRouteLayer,
deviceHubProxyRouteLayer,
staticAndDevRouteLayer,
websocketRpcRouteLayer,
Expand Down
28 changes: 27 additions & 1 deletion 28 packages/contracts/src/environmentHttp.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import * as HttpApi from "effect/http-api/HttpApi";
import * as HttpApiEndpoint from "effect/http-api/HttpApiEndpoint";
import * as HttpApiGroup from "effect/http-api/HttpApiGroup";
import * as HttpApiMiddleware from "effect/http-api/HttpApiMiddleware";
import * as HttpApiSchema from "effect/http-api/HttpApiSchema";
import * as HttpServerRespondable from "effect/http/HttpServerRespondable";
import * as HttpServerResponse from "effect/http/HttpServerResponse";

Expand Down Expand Up @@ -651,10 +652,35 @@ class EnvironmentConnectHttpApi extends HttpApiGroup.make("connect")
}),
) {}

/**
* Public entry point for webhook tasks. Unauthenticated by design: the token
* in the path, and an optional body signature, are the credential. The handler
* reads the raw body itself so a signature is checked over the exact bytes.
*/
const WebhookParams = Schema.Struct({
hookId: TrimmedNonEmptyString,
token: TrimmedNonEmptyString,
});
const WebhookAccepted = Schema.Struct({ deliveryId: TrimmedNonEmptyString }).pipe(
HttpApiSchema.status(202),
);
const webhookEndpoint = {
params: WebhookParams,
success: WebhookAccepted,
} as const;
const WEBHOOK_PATH = "/api/hooks/:hookId/:token";

class EnvironmentWebhooksHttpApi extends HttpApiGroup.make("webhooks")
.add(HttpApiEndpoint.post("webhookPost", WEBHOOK_PATH, webhookEndpoint))
.add(HttpApiEndpoint.put("webhookPut", WEBHOOK_PATH, webhookEndpoint))
.add(HttpApiEndpoint.patch("webhookPatch", WEBHOOK_PATH, webhookEndpoint))
.add(HttpApiEndpoint.get("webhookGet", WEBHOOK_PATH, webhookEndpoint)) {}

export class EnvironmentHttpApi extends HttpApi.make("environment")
.add(EnvironmentMetadataHttpApi)
.add(EnvironmentAuthHttpApi)
.add(EnvironmentOrchestrationHttpApi)
.add(EnvironmentPullRequestsHttpApi)
.add(EnvironmentProjectsHttpApi)
.add(EnvironmentConnectHttpApi) {}
.add(EnvironmentConnectHttpApi)
.add(EnvironmentWebhooksHttpApi) {}
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.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.