@mynthio/sdk 0.0.39 → 0.0.41
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 +49 -9
- package/dist/convex/index.d.ts +39 -90
- package/dist/convex/index.js +41 -2
- package/dist/handler.d.ts +28 -0
- package/dist/handler.js +121 -0
- package/dist/index.d.ts +675 -328
- package/dist/index.js +1469 -2
- package/dist/next/index.d.ts +14 -22
- package/dist/next/index.js +25 -2
- package/dist/tanstack-start/index.d.ts +18 -21
- package/dist/tanstack-start/index.js +11 -2
- package/dist/types.d.ts +610 -592
- package/package.json +16 -21
- package/dist/client.d.ts +0 -41
- package/dist/client.d.ts.map +0 -1
- package/dist/constants.d.ts +0 -94
- package/dist/constants.d.ts.map +0 -1
- package/dist/convex/index.d.ts.map +0 -1
- package/dist/convex/utils.d.ts +0 -2
- package/dist/convex/utils.d.ts.map +0 -1
- package/dist/image-alt-result.d.ts +0 -22
- package/dist/image-alt-result.d.ts.map +0 -1
- package/dist/image-generation-result.d.ts +0 -58
- package/dist/image-generation-result.d.ts.map +0 -1
- package/dist/image-rate-result.d.ts +0 -24
- package/dist/image-rate-result.d.ts.map +0 -1
- package/dist/image-review-result.d.ts +0 -31
- package/dist/image-review-result.d.ts.map +0 -1
- package/dist/index-apss16tr.js +0 -3
- package/dist/index-pjgsme75.js +0 -3
- package/dist/index.d.ts.map +0 -1
- package/dist/next/index.d.ts.map +0 -1
- package/dist/tanstack-start/index.d.ts.map +0 -1
- package/dist/task-async.d.ts +0 -95
- package/dist/task-async.d.ts.map +0 -1
- package/dist/types.d.ts.map +0 -1
- package/dist/uploads.d.ts +0 -31
- package/dist/uploads.d.ts.map +0 -1
- package/dist/video-generation-result.d.ts +0 -46
- package/dist/video-generation-result.d.ts.map +0 -1
- package/dist/webhooks/utils.d.ts +0 -5
- package/dist/webhooks/utils.d.ts.map +0 -1
package/README.md
CHANGED
|
@@ -290,8 +290,7 @@ inputs: [
|
|
|
290
290
|
String URLs are a shorthand for image inputs. Structured inputs use `type` and `source`.
|
|
291
291
|
|
|
292
292
|
Structured inputs can declare a role with `as` to guide the model. Valid values are
|
|
293
|
-
`"auto"` (default), `"
|
|
294
|
-
Most models auto-detect the kind from the image. Unified models such as Luma UNI-1 split
|
|
293
|
+
`"auto"` (default), `"source"`, and `"reference"`. Unified models such as Luma UNI-1 split
|
|
295
294
|
inputs by the declared role: `"source"` is the image being transformed or edited, and
|
|
296
295
|
`"reference"` is guidance only (style, character, composition). A request where every
|
|
297
296
|
input is `"reference"` runs as text-to-image guided by those references; any `"source"`
|
|
@@ -422,6 +421,43 @@ const result = await taskAsync.wait();
|
|
|
422
421
|
console.log(result.summary);
|
|
423
422
|
```
|
|
424
423
|
|
|
424
|
+
## Remove Background
|
|
425
|
+
|
|
426
|
+
Remove the background from an existing image. Mynth picks the model, so there is no `model` field:
|
|
427
|
+
|
|
428
|
+
```ts
|
|
429
|
+
const result = await mynth.image.removeBackground({
|
|
430
|
+
url: "https://example.com/product.jpg",
|
|
431
|
+
});
|
|
432
|
+
|
|
433
|
+
console.log(result.image.url); // transparent image
|
|
434
|
+
console.log(result.image.format); // "png" | "webp"
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
The result keeps the format the provider returned. Set `output.format` to always get `png` or `webp`.
|
|
438
|
+
`removeBackground()` also takes a local `file`, plus `destination`, `webhook`, and `metadata` like `generate()`:
|
|
439
|
+
|
|
440
|
+
```ts
|
|
441
|
+
const result = await mynth.image.removeBackground({
|
|
442
|
+
file,
|
|
443
|
+
output: { format: "webp" },
|
|
444
|
+
destination: "bunny-prod",
|
|
445
|
+
metadata: { productId: "sku_1" },
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
console.log(result.metadata.productId);
|
|
449
|
+
```
|
|
450
|
+
|
|
451
|
+
Use `removeBackgroundAsync()` to create the task without waiting. It returns a public access token, like `generateAsync()`:
|
|
452
|
+
|
|
453
|
+
```ts
|
|
454
|
+
const taskAsync = await mynth.image.removeBackgroundAsync({
|
|
455
|
+
url: "https://example.com/product.jpg",
|
|
456
|
+
});
|
|
457
|
+
|
|
458
|
+
return { id: taskAsync.id, access: taskAsync.access };
|
|
459
|
+
```
|
|
460
|
+
|
|
425
461
|
## Working With Image Results
|
|
426
462
|
|
|
427
463
|
Completed generation tasks expose a few helpful accessors:
|
|
@@ -509,11 +545,9 @@ Current model IDs include:
|
|
|
509
545
|
- `black-forest-labs/flux.2-flex`
|
|
510
546
|
- `black-forest-labs/flux.2-max`
|
|
511
547
|
- `black-forest-labs/flux.2-klein-4b`
|
|
512
|
-
- `black-forest-labs/flux-virtual-try-on`
|
|
513
548
|
- `google/gemini-3.1-flash-lite-image`
|
|
514
549
|
- `google/gemini-3.1-flash-image`
|
|
515
550
|
- `google/gemini-3-pro-image-preview`
|
|
516
|
-
- `ideogram/remove-background`
|
|
517
551
|
- `imagineart/imagineart-1.5-pro`
|
|
518
552
|
- `imagineart/imagineart-2.0`
|
|
519
553
|
- `john6666/bismuth-illustrious-mix`
|
|
@@ -525,7 +559,6 @@ Current model IDs include:
|
|
|
525
559
|
- `luma/uni-1-max`
|
|
526
560
|
- `meta/muse-image`
|
|
527
561
|
- `openai/gpt-image-2`
|
|
528
|
-
- `prunaai/p-image-try-on`
|
|
529
562
|
- `purplesmartai/pony-diffusion-v6-xl`
|
|
530
563
|
- `recraft/recraft-v4`
|
|
531
564
|
- `recraft/recraft-v4-pro`
|
|
@@ -709,9 +742,9 @@ export const POST = mynthWebhookHandler({
|
|
|
709
742
|
});
|
|
710
743
|
```
|
|
711
744
|
|
|
712
|
-
The helper reads the raw body, verifies `X-Mynth-Signature`, rejects signatures older than five minutes, and checks `X-Mynth-Event` before calling a typed handler. The last handler argument contains the original `request
|
|
745
|
+
The helper reads the raw body, verifies `X-Mynth-Signature`, rejects signatures older than five minutes, and checks `X-Mynth-Event` before calling a typed handler. The last handler argument contains the original `request` and `deliveryId`, the `X-Mynth-Delivery` value that every retry repeats.
|
|
713
746
|
|
|
714
|
-
The route must be publicly reachable, so exclude it from authentication middleware. Make callback side effects idempotent
|
|
747
|
+
The route must be publicly reachable, so exclude it from authentication middleware. Make callback side effects idempotent by storing `deliveryId` and skipping IDs you have already handled, and enqueue slow work before returning. Callback errors are propagated so Mynth can retry the delivery.
|
|
715
748
|
|
|
716
749
|
Pass `{ webhookSecret: "wbs_..." }` as the second argument only when the application does not use `MYNTH_WEBHOOK_SECRET`. This helper accepts signed, registered webhooks; per-request custom webhooks are not signed.
|
|
717
750
|
|
|
@@ -742,7 +775,7 @@ export const Route = createFileRoute("/api/webhooks/mynth")({
|
|
|
742
775
|
});
|
|
743
776
|
```
|
|
744
777
|
|
|
745
|
-
Set `MYNTH_WEBHOOK_SECRET` in the server environment, or pass `webhookSecret` as the second argument. Event callbacks receive the original request, route params,
|
|
778
|
+
Set `MYNTH_WEBHOOK_SECRET` in the server environment, or pass `webhookSecret` as the second argument. Event callbacks receive the original request, route params, TanStack Start middleware context, and `deliveryId`.
|
|
746
779
|
|
|
747
780
|
## Convex Integration
|
|
748
781
|
|
|
@@ -780,6 +813,13 @@ export const mynthWebhook = mynthWebhookAction({
|
|
|
780
813
|
imageReviewTaskFailed: async (payload) => {
|
|
781
814
|
console.error("Mynth review task failed:", payload.task.id);
|
|
782
815
|
},
|
|
816
|
+
imageRemoveBackgroundTaskCompleted: async (payload) => {
|
|
817
|
+
console.log("Completed remove background task:", payload.task.id);
|
|
818
|
+
console.log(payload.result.image.url);
|
|
819
|
+
},
|
|
820
|
+
imageRemoveBackgroundTaskFailed: async (payload) => {
|
|
821
|
+
console.error("Mynth remove background task failed:", payload.task.id);
|
|
822
|
+
},
|
|
783
823
|
videoTaskCompleted: async (payload) => {
|
|
784
824
|
console.log("Completed video task:", payload.task.id);
|
|
785
825
|
console.log(payload.result.videos);
|
|
@@ -794,7 +834,7 @@ Set `MYNTH_WEBHOOK_SECRET` in your environment, or pass `webhookSecret` explicit
|
|
|
794
834
|
|
|
795
835
|
## Error Handling
|
|
796
836
|
|
|
797
|
-
`upload()`, `generate()`, `generateAsync()`, `rate()`, `rateAsync()`, `alt()`, `altAsync()`, `review()`, `reviewAsync()`, `models.list()`, and the `video` equivalents (`video.generate()`, `video.generateAsync()`, `video.upload()`, `video.estimate()`) may throw `MynthAPIError` if the request fails. Polling can also throw task-specific errors:
|
|
837
|
+
`upload()`, `generate()`, `generateAsync()`, `rate()`, `rateAsync()`, `alt()`, `altAsync()`, `review()`, `reviewAsync()`, `removeBackground()`, `removeBackgroundAsync()`, `models.list()`, and the `video` equivalents (`video.generate()`, `video.generateAsync()`, `video.upload()`, `video.estimate()`) may throw `MynthAPIError` if the request fails. Polling can also throw task-specific errors:
|
|
798
838
|
|
|
799
839
|
While polling, transient failures (404, 5xx, dropped connections) are retried: a created task is owed an answer, so a cold cache or a brief outage does not lose you the result. Polling gives up after 20 consecutive failures (~100s) with `TaskAsyncFetchError` or `TaskAsyncTaskFetchError`, and immediately on a 401 or 403 with `TaskAsyncUnauthorizedError`. Image waits time out after 30 minutes, video waits after an hour.
|
|
800
840
|
|
package/dist/convex/index.d.ts
CHANGED
|
@@ -1,105 +1,54 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
1
|
+
import { n as WebhookHandlerOptions, t as WebhookEventHandlers } from "../handler.js";
|
|
2
|
+
import { GenericActionCtx, PublicHttpAction } from "convex/server";
|
|
3
|
+
//#region src/convex/index.d.ts
|
|
4
|
+
type AnyActionCtx = GenericActionCtx<any>;
|
|
5
|
+
export type MynthWebhookActionContext<T extends AnyActionCtx = AnyActionCtx> = {
|
|
6
|
+
/** The Convex action context, for `runQuery`, `runMutation`, and `scheduler`. */
|
|
7
|
+
context: T;
|
|
8
|
+
/** The request received by the Convex HTTP action. Its body has already been read. */
|
|
9
|
+
request: Request;
|
|
10
|
+
/**
|
|
11
|
+
* The `X-Mynth-Delivery` ID. Every retry of a delivery repeats it, so store
|
|
12
|
+
* it and skip IDs you have already handled.
|
|
13
|
+
*/
|
|
14
|
+
deliveryId: string;
|
|
15
|
+
};
|
|
3
16
|
/**
|
|
4
17
|
* Event handlers for Mynth webhook events.
|
|
5
18
|
*/
|
|
6
|
-
export type EventHandlers<T extends
|
|
7
|
-
/** Called when an image generation task completes successfully */
|
|
8
|
-
imageTaskCompleted?: (payload: MynthSDKTypes.WebhookTaskImageCompletedPayload, context: {
|
|
9
|
-
context: T;
|
|
10
|
-
request: Request;
|
|
11
|
-
}) => Promise<void>;
|
|
12
|
-
/** Called when an image generation task fails */
|
|
13
|
-
imageTaskFailed?: (payload: MynthSDKTypes.WebhookTaskImageFailedPayload, context: {
|
|
14
|
-
context: T;
|
|
15
|
-
request: Request;
|
|
16
|
-
}) => Promise<void>;
|
|
17
|
-
/** Called when an image rating task completes successfully */
|
|
18
|
-
imageRateTaskCompleted?: (payload: MynthSDKTypes.WebhookTaskImageRateCompletedPayload, context: {
|
|
19
|
-
context: T;
|
|
20
|
-
request: Request;
|
|
21
|
-
}) => Promise<void>;
|
|
22
|
-
/** Called when an image rating task fails */
|
|
23
|
-
imageRateTaskFailed?: (payload: MynthSDKTypes.WebhookTaskImageRateFailedPayload, context: {
|
|
24
|
-
context: T;
|
|
25
|
-
request: Request;
|
|
26
|
-
}) => Promise<void>;
|
|
27
|
-
/** Called when an image alt text task completes successfully */
|
|
28
|
-
imageAltTaskCompleted?: (payload: MynthSDKTypes.WebhookTaskImageAltCompletedPayload, context: {
|
|
29
|
-
context: T;
|
|
30
|
-
request: Request;
|
|
31
|
-
}) => Promise<void>;
|
|
32
|
-
/** Called when an image alt text task fails */
|
|
33
|
-
imageAltTaskFailed?: (payload: MynthSDKTypes.WebhookTaskImageAltFailedPayload, context: {
|
|
34
|
-
context: T;
|
|
35
|
-
request: Request;
|
|
36
|
-
}) => Promise<void>;
|
|
37
|
-
/** Called when an image review task completes successfully */
|
|
38
|
-
imageReviewTaskCompleted?: (payload: MynthSDKTypes.WebhookTaskImageReviewCompletedPayload, context: {
|
|
39
|
-
context: T;
|
|
40
|
-
request: Request;
|
|
41
|
-
}) => Promise<void>;
|
|
42
|
-
/** Called when an image review task fails */
|
|
43
|
-
imageReviewTaskFailed?: (payload: MynthSDKTypes.WebhookTaskImageReviewFailedPayload, context: {
|
|
44
|
-
context: T;
|
|
45
|
-
request: Request;
|
|
46
|
-
}) => Promise<void>;
|
|
47
|
-
/** Called when a video generation task completes successfully */
|
|
48
|
-
videoTaskCompleted?: (payload: MynthSDKTypes.WebhookTaskVideoCompletedPayload, context: {
|
|
49
|
-
context: T;
|
|
50
|
-
request: Request;
|
|
51
|
-
}) => Promise<void>;
|
|
52
|
-
/** Called when a video generation task fails */
|
|
53
|
-
videoTaskFailed?: (payload: MynthSDKTypes.WebhookTaskVideoFailedPayload, context: {
|
|
54
|
-
context: T;
|
|
55
|
-
request: Request;
|
|
56
|
-
}) => Promise<void>;
|
|
57
|
-
};
|
|
19
|
+
export type EventHandlers<T extends AnyActionCtx = AnyActionCtx> = WebhookEventHandlers<MynthWebhookActionContext<T>>;
|
|
58
20
|
/**
|
|
59
21
|
* Options for configuring the webhook action.
|
|
60
22
|
*/
|
|
61
|
-
export type MynthWebhookActionOptions =
|
|
62
|
-
/** Webhook secret for signature verification. Defaults to MYNTH_WEBHOOK_SECRET env var. */
|
|
63
|
-
webhookSecret?: string;
|
|
64
|
-
};
|
|
23
|
+
export type MynthWebhookActionOptions = WebhookHandlerOptions;
|
|
65
24
|
/**
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
* @param eventHandlers - Handlers for different webhook events
|
|
69
|
-
* @param options - Configuration options
|
|
70
|
-
* @returns A Convex HTTP action handler
|
|
25
|
+
* Create a Convex HTTP action for signed Mynth webhooks.
|
|
71
26
|
*
|
|
72
27
|
* @example
|
|
73
28
|
* ```typescript
|
|
74
|
-
* //
|
|
29
|
+
* // convex/http.ts
|
|
30
|
+
* import { httpRouter } from "convex/server";
|
|
75
31
|
* import { mynthWebhookAction } from "@mynthio/sdk/convex";
|
|
76
32
|
*
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
*
|
|
92
|
-
* });
|
|
93
|
-
* },
|
|
94
|
-
* imageAltTaskCompleted: async (payload, { context }) => {
|
|
95
|
-
* await context.runMutation(internal.images.saveAltText, {
|
|
96
|
-
* taskId: payload.task.id,
|
|
97
|
-
* url: payload.result.url,
|
|
98
|
-
* alt: payload.result.alt,
|
|
99
|
-
* });
|
|
100
|
-
* },
|
|
33
|
+
* import { internal } from "./_generated/api";
|
|
34
|
+
*
|
|
35
|
+
* const http = httpRouter();
|
|
36
|
+
*
|
|
37
|
+
* http.route({
|
|
38
|
+
* path: "/mynth-webhook",
|
|
39
|
+
* method: "POST",
|
|
40
|
+
* handler: mynthWebhookAction({
|
|
41
|
+
* imageTaskCompleted: async (payload, { context }) => {
|
|
42
|
+
* await context.runMutation(internal.images.save, {
|
|
43
|
+
* taskId: payload.task.id,
|
|
44
|
+
* images: payload.result.images,
|
|
45
|
+
* });
|
|
46
|
+
* },
|
|
47
|
+
* }),
|
|
101
48
|
* });
|
|
49
|
+
*
|
|
50
|
+
* export default http;
|
|
102
51
|
* ```
|
|
103
52
|
*/
|
|
104
|
-
export declare
|
|
105
|
-
//#
|
|
53
|
+
export declare function mynthWebhookAction(eventHandlers: EventHandlers, options?: MynthWebhookActionOptions): PublicHttpAction;
|
|
54
|
+
//#endregion
|
package/dist/convex/index.js
CHANGED
|
@@ -1,2 +1,41 @@
|
|
|
1
|
-
|
|
2
|
-
import
|
|
1
|
+
import { t as handleWebhookRequest } from "../handler.js";
|
|
2
|
+
import { httpActionGeneric } from "convex/server";
|
|
3
|
+
//#region src/convex/index.ts
|
|
4
|
+
/**
|
|
5
|
+
* Create a Convex HTTP action for signed Mynth webhooks.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* // convex/http.ts
|
|
10
|
+
* import { httpRouter } from "convex/server";
|
|
11
|
+
* import { mynthWebhookAction } from "@mynthio/sdk/convex";
|
|
12
|
+
*
|
|
13
|
+
* import { internal } from "./_generated/api";
|
|
14
|
+
*
|
|
15
|
+
* const http = httpRouter();
|
|
16
|
+
*
|
|
17
|
+
* http.route({
|
|
18
|
+
* path: "/mynth-webhook",
|
|
19
|
+
* method: "POST",
|
|
20
|
+
* handler: mynthWebhookAction({
|
|
21
|
+
* imageTaskCompleted: async (payload, { context }) => {
|
|
22
|
+
* await context.runMutation(internal.images.save, {
|
|
23
|
+
* taskId: payload.task.id,
|
|
24
|
+
* images: payload.result.images,
|
|
25
|
+
* });
|
|
26
|
+
* },
|
|
27
|
+
* }),
|
|
28
|
+
* });
|
|
29
|
+
*
|
|
30
|
+
* export default http;
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
function mynthWebhookAction(eventHandlers, options = {}) {
|
|
34
|
+
return httpActionGeneric((context, request) => handleWebhookRequest(request, eventHandlers, (deliveryId) => ({
|
|
35
|
+
context,
|
|
36
|
+
request,
|
|
37
|
+
deliveryId
|
|
38
|
+
}), options));
|
|
39
|
+
}
|
|
40
|
+
//#endregion
|
|
41
|
+
export { mynthWebhookAction };
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { t as MynthSDKTypes } from "./types.js";
|
|
2
|
+
//#region src/webhooks/handler.d.ts
|
|
3
|
+
/** Maps every webhook event to the callback name the framework helpers accept. */
|
|
4
|
+
declare const EVENT_HANDLER_NAMES: {
|
|
5
|
+
readonly "task.image.generate.completed": "imageTaskCompleted";
|
|
6
|
+
readonly "task.image.generate.failed": "imageTaskFailed";
|
|
7
|
+
readonly "task.image.rate.completed": "imageRateTaskCompleted";
|
|
8
|
+
readonly "task.image.rate.failed": "imageRateTaskFailed";
|
|
9
|
+
readonly "task.image.alt.completed": "imageAltTaskCompleted";
|
|
10
|
+
readonly "task.image.alt.failed": "imageAltTaskFailed";
|
|
11
|
+
readonly "task.image.review.completed": "imageReviewTaskCompleted";
|
|
12
|
+
readonly "task.image.review.failed": "imageReviewTaskFailed";
|
|
13
|
+
readonly "task.image.remove_background.completed": "imageRemoveBackgroundTaskCompleted";
|
|
14
|
+
readonly "task.image.remove_background.failed": "imageRemoveBackgroundTaskFailed";
|
|
15
|
+
readonly "task.video.generate.completed": "videoTaskCompleted";
|
|
16
|
+
readonly "task.video.generate.failed": "videoTaskFailed";
|
|
17
|
+
};
|
|
18
|
+
type WebhookEvent = MynthSDKTypes.WebhookPayload["event"];
|
|
19
|
+
/** Event callbacks shared by every framework helper, keyed by handler name. */
|
|
20
|
+
type WebhookEventHandlers<TContext> = { [TEvent in WebhookEvent as (typeof EVENT_HANDLER_NAMES)[TEvent]]?: (payload: Extract<MynthSDKTypes.WebhookPayload, {
|
|
21
|
+
event: TEvent;
|
|
22
|
+
}>, context: TContext) => void | Promise<void>; };
|
|
23
|
+
type WebhookHandlerOptions = {
|
|
24
|
+
/** Defaults to MYNTH_WEBHOOK_SECRET, read when each request arrives. */
|
|
25
|
+
webhookSecret?: string;
|
|
26
|
+
};
|
|
27
|
+
//#endregion
|
|
28
|
+
export { WebhookHandlerOptions as n, WebhookEventHandlers as t };
|
package/dist/handler.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
//#region src/webhooks/utils.ts
|
|
2
|
+
/** Environment variable used when no webhook secret is passed explicitly. */
|
|
3
|
+
const WEBHOOK_SECRET_ENV_VAR = "MYNTH_WEBHOOK_SECRET";
|
|
4
|
+
/** Hex-encoded HMAC-SHA256 digests are always 32 bytes. */
|
|
5
|
+
const SIGNATURE_PATTERN = /^[0-9a-f]{64}$/i;
|
|
6
|
+
const TIMESTAMP_PATTERN = /^\d{1,15}$/;
|
|
7
|
+
const encoder = new TextEncoder();
|
|
8
|
+
/** Read the webhook secret without assuming a Node.js runtime. */
|
|
9
|
+
function getWebhookSecretFromEnv() {
|
|
10
|
+
if (typeof process !== "undefined" && process.env) return process.env[WEBHOOK_SECRET_ENV_VAR];
|
|
11
|
+
}
|
|
12
|
+
function parseSignatureHeader(signatureHeader) {
|
|
13
|
+
let timestamp;
|
|
14
|
+
const signatures = [];
|
|
15
|
+
for (const part of signatureHeader.split(",")) {
|
|
16
|
+
const separator = part.indexOf("=");
|
|
17
|
+
if (separator === -1) continue;
|
|
18
|
+
const key = part.slice(0, separator).trim();
|
|
19
|
+
const value = part.slice(separator + 1).trim();
|
|
20
|
+
if (key === "t" && TIMESTAMP_PATTERN.test(value)) timestamp = value;
|
|
21
|
+
else if (key === "v1" && SIGNATURE_PATTERN.test(value)) signatures.push(hexToBytes(value));
|
|
22
|
+
}
|
|
23
|
+
if (timestamp === void 0 || signatures.length === 0) return null;
|
|
24
|
+
return {
|
|
25
|
+
timestamp,
|
|
26
|
+
signatures
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Verify a Mynth HMAC-SHA256 signature against the raw request body.
|
|
31
|
+
*
|
|
32
|
+
* Rejects timestamps more than five minutes from `now` to limit replays. The
|
|
33
|
+
* comparison runs inside Web Crypto, so it does not leak timing information.
|
|
34
|
+
*/
|
|
35
|
+
async function verifySignature(body, signatureHeader, secret, now = Date.now()) {
|
|
36
|
+
const parsed = parseSignatureHeader(signatureHeader);
|
|
37
|
+
if (!parsed) return false;
|
|
38
|
+
const ageSeconds = Math.floor(now / 1e3) - Number(parsed.timestamp);
|
|
39
|
+
if (Math.abs(ageSeconds) > 300) return false;
|
|
40
|
+
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
41
|
+
name: "HMAC",
|
|
42
|
+
hash: "SHA-256"
|
|
43
|
+
}, false, ["verify"]);
|
|
44
|
+
const message = concatBytes(encoder.encode(`${parsed.timestamp}.`), body);
|
|
45
|
+
for (const signature of parsed.signatures) if (await crypto.subtle.verify("HMAC", key, signature, message)) return true;
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
function hexToBytes(hex) {
|
|
49
|
+
const bytes = new Uint8Array(hex.length / 2);
|
|
50
|
+
for (let i = 0; i < bytes.length; i++) bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
51
|
+
return bytes;
|
|
52
|
+
}
|
|
53
|
+
function concatBytes(a, b) {
|
|
54
|
+
const bytes = new Uint8Array(a.length + b.length);
|
|
55
|
+
bytes.set(a);
|
|
56
|
+
bytes.set(b, a.length);
|
|
57
|
+
return bytes;
|
|
58
|
+
}
|
|
59
|
+
//#endregion
|
|
60
|
+
//#region src/webhooks/handler.ts
|
|
61
|
+
const WEBHOOK_EVENT_HEADER = "X-Mynth-Event";
|
|
62
|
+
const WEBHOOK_DELIVERY_HEADER = "X-Mynth-Delivery";
|
|
63
|
+
const WEBHOOK_SIGNATURE_HEADER = "X-Mynth-Signature";
|
|
64
|
+
/** Maps every webhook event to the callback name the framework helpers accept. */
|
|
65
|
+
const EVENT_HANDLER_NAMES = {
|
|
66
|
+
"task.image.generate.completed": "imageTaskCompleted",
|
|
67
|
+
"task.image.generate.failed": "imageTaskFailed",
|
|
68
|
+
"task.image.rate.completed": "imageRateTaskCompleted",
|
|
69
|
+
"task.image.rate.failed": "imageRateTaskFailed",
|
|
70
|
+
"task.image.alt.completed": "imageAltTaskCompleted",
|
|
71
|
+
"task.image.alt.failed": "imageAltTaskFailed",
|
|
72
|
+
"task.image.review.completed": "imageReviewTaskCompleted",
|
|
73
|
+
"task.image.review.failed": "imageReviewTaskFailed",
|
|
74
|
+
"task.image.remove_background.completed": "imageRemoveBackgroundTaskCompleted",
|
|
75
|
+
"task.image.remove_background.failed": "imageRemoveBackgroundTaskFailed",
|
|
76
|
+
"task.video.generate.completed": "videoTaskCompleted",
|
|
77
|
+
"task.video.generate.failed": "videoTaskFailed"
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* Verify a signed Mynth webhook request and dispatch it to the matching callback.
|
|
81
|
+
*
|
|
82
|
+
* Answers `400` for a missing delivery ID, a missing or invalid signature, a
|
|
83
|
+
* stale timestamp, a malformed body, or an `X-Mynth-Event` header that does
|
|
84
|
+
* not match the body.
|
|
85
|
+
* Answers `200` for signed events without a callback. Callback errors
|
|
86
|
+
* propagate, so the framework answers `5xx` and Mynth retries the delivery.
|
|
87
|
+
*/
|
|
88
|
+
async function handleWebhookRequest(request, eventHandlers, createContext, options) {
|
|
89
|
+
const webhookSecret = options.webhookSecret ?? getWebhookSecretFromEnv();
|
|
90
|
+
if (!webhookSecret) throw new Error("MYNTH_WEBHOOK_SECRET is required. Either pass it as an option or set the environment variable.");
|
|
91
|
+
const event = request.headers.get(WEBHOOK_EVENT_HEADER);
|
|
92
|
+
const deliveryId = request.headers.get(WEBHOOK_DELIVERY_HEADER);
|
|
93
|
+
const signature = request.headers.get(WEBHOOK_SIGNATURE_HEADER);
|
|
94
|
+
if (!event || !deliveryId || !signature) return badRequest();
|
|
95
|
+
const body = new Uint8Array(await request.arrayBuffer());
|
|
96
|
+
if (!await verifySignature(body, signature, webhookSecret)) return badRequest();
|
|
97
|
+
const payload = parsePayload(body);
|
|
98
|
+
if (!payload || payload.event !== event) return badRequest();
|
|
99
|
+
if (!Object.hasOwn(EVENT_HANDLER_NAMES, payload.event)) return ok();
|
|
100
|
+
const handler = eventHandlers[EVENT_HANDLER_NAMES[payload.event]];
|
|
101
|
+
await handler?.(payload, createContext(deliveryId));
|
|
102
|
+
return ok();
|
|
103
|
+
}
|
|
104
|
+
function parsePayload(body) {
|
|
105
|
+
let payload;
|
|
106
|
+
try {
|
|
107
|
+
payload = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
|
|
108
|
+
} catch {
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
if (typeof payload !== "object" || payload === null || !("event" in payload) || typeof payload.event !== "string" || !("task" in payload) || typeof payload.task !== "object" || payload.task === null || !("id" in payload.task) || typeof payload.task.id !== "string") return null;
|
|
112
|
+
return payload;
|
|
113
|
+
}
|
|
114
|
+
function ok() {
|
|
115
|
+
return new Response("OK", { status: 200 });
|
|
116
|
+
}
|
|
117
|
+
function badRequest() {
|
|
118
|
+
return new Response("Bad Request", { status: 400 });
|
|
119
|
+
}
|
|
120
|
+
//#endregion
|
|
121
|
+
export { handleWebhookRequest as t };
|