@mynthio/sdk 0.0.40 → 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.
Files changed (44) hide show
  1. package/README.md +3 -3
  2. package/dist/convex/index.d.ts +39 -100
  3. package/dist/convex/index.js +41 -2
  4. package/dist/handler.d.ts +28 -0
  5. package/dist/handler.js +121 -0
  6. package/dist/index.d.ts +674 -360
  7. package/dist/index.js +1469 -2
  8. package/dist/next/index.d.ts +14 -24
  9. package/dist/next/index.js +25 -2
  10. package/dist/tanstack-start/index.d.ts +18 -23
  11. package/dist/tanstack-start/index.js +11 -2
  12. package/dist/types.d.ts +610 -660
  13. package/package.json +16 -21
  14. package/dist/client.d.ts +0 -41
  15. package/dist/client.d.ts.map +0 -1
  16. package/dist/constants.d.ts +0 -95
  17. package/dist/constants.d.ts.map +0 -1
  18. package/dist/convex/index.d.ts.map +0 -1
  19. package/dist/convex/utils.d.ts +0 -2
  20. package/dist/convex/utils.d.ts.map +0 -1
  21. package/dist/image-alt-result.d.ts +0 -19
  22. package/dist/image-alt-result.d.ts.map +0 -1
  23. package/dist/image-generation-result.d.ts +0 -58
  24. package/dist/image-generation-result.d.ts.map +0 -1
  25. package/dist/image-rate-result.d.ts +0 -21
  26. package/dist/image-rate-result.d.ts.map +0 -1
  27. package/dist/image-remove-background-result.d.ts +0 -24
  28. package/dist/image-remove-background-result.d.ts.map +0 -1
  29. package/dist/image-review-result.d.ts +0 -28
  30. package/dist/image-review-result.d.ts.map +0 -1
  31. package/dist/index-apss16tr.js +0 -3
  32. package/dist/index-ty295921.js +0 -3
  33. package/dist/index.d.ts.map +0 -1
  34. package/dist/next/index.d.ts.map +0 -1
  35. package/dist/tanstack-start/index.d.ts.map +0 -1
  36. package/dist/task-async.d.ts +0 -95
  37. package/dist/task-async.d.ts.map +0 -1
  38. package/dist/types.d.ts.map +0 -1
  39. package/dist/uploads.d.ts +0 -31
  40. package/dist/uploads.d.ts.map +0 -1
  41. package/dist/video-generation-result.d.ts +0 -46
  42. package/dist/video-generation-result.d.ts.map +0 -1
  43. package/dist/webhooks/utils.d.ts +0 -5
  44. package/dist/webhooks/utils.d.ts.map +0 -1
package/README.md CHANGED
@@ -742,9 +742,9 @@ export const POST = mynthWebhookHandler({
742
742
  });
743
743
  ```
744
744
 
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`.
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.
746
746
 
747
- The route must be publicly reachable, so exclude it from authentication middleware. Make callback side effects idempotent using the event name and task ID, and enqueue slow work before returning. Callback errors are propagated so Mynth can retry the delivery.
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.
748
748
 
749
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.
750
750
 
@@ -775,7 +775,7 @@ export const Route = createFileRoute("/api/webhooks/mynth")({
775
775
  });
776
776
  ```
777
777
 
778
- Set `MYNTH_WEBHOOK_SECRET` in the server environment, or pass `webhookSecret` as the second argument. Event callbacks receive the original request, route params, and TanStack Start middleware context.
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`.
779
779
 
780
780
  ## Convex Integration
781
781
 
@@ -1,115 +1,54 @@
1
- import type { GenericActionCtx } from "convex/server";
2
- import type { MynthSDKTypes } from "../types";
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 GenericActionCtx<any> = GenericActionCtx<any>> = {
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 an image remove background task completes successfully */
48
- imageRemoveBackgroundTaskCompleted?: (payload: MynthSDKTypes.WebhookTaskImageRemoveBackgroundCompletedPayload, context: {
49
- context: T;
50
- request: Request;
51
- }) => Promise<void>;
52
- /** Called when an image remove background task fails */
53
- imageRemoveBackgroundTaskFailed?: (payload: MynthSDKTypes.WebhookTaskImageRemoveBackgroundFailedPayload, context: {
54
- context: T;
55
- request: Request;
56
- }) => Promise<void>;
57
- /** Called when a video generation task completes successfully */
58
- videoTaskCompleted?: (payload: MynthSDKTypes.WebhookTaskVideoCompletedPayload, context: {
59
- context: T;
60
- request: Request;
61
- }) => Promise<void>;
62
- /** Called when a video generation task fails */
63
- videoTaskFailed?: (payload: MynthSDKTypes.WebhookTaskVideoFailedPayload, context: {
64
- context: T;
65
- request: Request;
66
- }) => Promise<void>;
67
- };
19
+ export type EventHandlers<T extends AnyActionCtx = AnyActionCtx> = WebhookEventHandlers<MynthWebhookActionContext<T>>;
68
20
  /**
69
21
  * Options for configuring the webhook action.
70
22
  */
71
- export type MynthWebhookActionOptions = {
72
- /** Webhook secret for signature verification. Defaults to MYNTH_WEBHOOK_SECRET env var. */
73
- webhookSecret?: string;
74
- };
23
+ export type MynthWebhookActionOptions = WebhookHandlerOptions;
75
24
  /**
76
- * Creates a Convex HTTP action handler for Mynth webhooks.
77
- *
78
- * @param eventHandlers - Handlers for different webhook events
79
- * @param options - Configuration options
80
- * @returns A Convex HTTP action handler
25
+ * Create a Convex HTTP action for signed Mynth webhooks.
81
26
  *
82
27
  * @example
83
28
  * ```typescript
84
- * // In convex/http.ts
29
+ * // convex/http.ts
30
+ * import { httpRouter } from "convex/server";
85
31
  * import { mynthWebhookAction } from "@mynthio/sdk/convex";
86
32
  *
87
- * export const mynthWebhook = mynthWebhookAction({
88
- * imageTaskCompleted: async (payload, { context }) => {
89
- * await context.runMutation(internal.images.save, {
90
- * taskId: payload.task.id,
91
- * images: payload.result.images,
92
- * });
93
- * },
94
- * imageTaskFailed: async (payload, { context }) => {
95
- * console.error("Task failed:", payload.task.id);
96
- * },
97
- * imageRateTaskCompleted: async (payload, { context }) => {
98
- * await context.runMutation(internal.images.saveRating, {
99
- * taskId: payload.task.id,
100
- * url: payload.result.url,
101
- * level: payload.result.level,
102
- * });
103
- * },
104
- * imageAltTaskCompleted: async (payload, { context }) => {
105
- * await context.runMutation(internal.images.saveAltText, {
106
- * taskId: payload.task.id,
107
- * url: payload.result.url,
108
- * alt: payload.result.alt,
109
- * });
110
- * },
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
+ * }),
111
48
  * });
49
+ *
50
+ * export default http;
112
51
  * ```
113
52
  */
114
- export declare const mynthWebhookAction: (eventHandlers: EventHandlers, options?: MynthWebhookActionOptions) => (ctx: GenericActionCtx<any>, request: Request) => Promise<Response>;
115
- //# sourceMappingURL=index.d.ts.map
53
+ export declare function mynthWebhookAction(eventHandlers: EventHandlers, options?: MynthWebhookActionOptions): PublicHttpAction;
54
+ //#endregion
@@ -1,2 +1,41 @@
1
- // @bun
2
- import{b as z,c as J}from"../index-apss16tr.js";var X="X-Mynth-Event",Y="X-Mynth-Signature",G=(F,Q)=>{let L=Q?.webhookSecret??z();if(!L)throw Error("MYNTH_WEBHOOK_SECRET is required. Either pass it as an option or set the environment variable.");return async(j,m)=>{let M=m.headers.get(Y);if(!M)return new Response("Unauthorized",{status:401});if(!m.headers.get(X))return new Response("Unauthorized",{status:401});let P=await m.text();if(!await J(P,M,L))return new Response("Unauthorized",{status:401});let f=JSON.parse(P);switch(f.event){case"task.image.generate.completed":await F.imageTaskCompleted?.(f,{context:j,request:m});break;case"task.image.generate.failed":await F.imageTaskFailed?.(f,{context:j,request:m});break;case"task.image.rate.completed":await F.imageRateTaskCompleted?.(f,{context:j,request:m});break;case"task.image.rate.failed":await F.imageRateTaskFailed?.(f,{context:j,request:m});break;case"task.image.alt.completed":await F.imageAltTaskCompleted?.(f,{context:j,request:m});break;case"task.image.alt.failed":await F.imageAltTaskFailed?.(f,{context:j,request:m});break;case"task.image.review.completed":await F.imageReviewTaskCompleted?.(f,{context:j,request:m});break;case"task.image.review.failed":await F.imageReviewTaskFailed?.(f,{context:j,request:m});break;case"task.image.remove_background.completed":await F.imageRemoveBackgroundTaskCompleted?.(f,{context:j,request:m});break;case"task.image.remove_background.failed":await F.imageRemoveBackgroundTaskFailed?.(f,{context:j,request:m});break;case"task.video.generate.completed":await F.videoTaskCompleted?.(f,{context:j,request:m});break;case"task.video.generate.failed":await F.videoTaskFailed?.(f,{context:j,request:m});break;default:return new Response("Unauthorized",{status:401})}return new Response(void 0,{status:200})}};export{G as mynthWebhookAction};
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 };
@@ -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 };