@braille-ai/webhook-send 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,161 @@
1
+ /**
2
+ * One signed multipart POST to a Braille webhook endpoint.
3
+ *
4
+ * The body is encoded once, signed byte for byte, and that same buffer is sent, because the signature covers the
5
+ * raw bytes and a re-encoded body would not verify. The secret is used and never surfaces in a result, an error or
6
+ * a log line.
7
+ */
8
+ /** The media types Braille accepts, by file extension. Anything else is `415 UNSUPPORTED_FILE_TYPE`. */
9
+ declare const CONTENT_TYPES: Readonly<Record<string, string>>;
10
+ type WebhookFile = {
11
+ /** The document's bytes. */
12
+ data: Uint8Array | ArrayBuffer | Blob;
13
+ /** The name the document lands with, extension included. Decides the media type when `contentType` is omitted. */
14
+ filename: string;
15
+ /** Normally inferred from the filename's extension. */
16
+ contentType?: string;
17
+ /** The multipart field name. Defaults to `file`. `surfaceId` and `surfaceModality` are reserved. */
18
+ field?: string;
19
+ };
20
+ type WebhookAccepted = {
21
+ ok: true;
22
+ /** 200 when every file stored, 207 when some did not; see `files`. */
23
+ status: number;
24
+ eventId: string;
25
+ /** True on a 207. Do not retry a 207 with the same event id: send the failed files as a new event. */
26
+ partial: boolean;
27
+ workspaceDocumentId: string | null;
28
+ files: Array<{
29
+ fileName: string;
30
+ disposition: string;
31
+ }>;
32
+ };
33
+ type WebhookRefused = {
34
+ ok: false;
35
+ status: number;
36
+ eventId: string;
37
+ /** A stable code from the guide's table, or `UNEXPECTED_RESPONSE` when the answer was not Braille's JSON. */
38
+ code: string;
39
+ /** Customer-facing copy. Branch on `code`, never on this. */
40
+ message: string;
41
+ /** True for 429 and every 5xx: retry later **with the same `eventId`**. False means fix the cause first. */
42
+ retryable: boolean;
43
+ /** From the `Retry-After` header on a 429, in seconds. */
44
+ retryAfterSeconds: number | null;
45
+ };
46
+ type WebhookResult = WebhookAccepted | WebhookRefused;
47
+ type WebhookSenderOptions = {
48
+ /** The delivery URL `braille webhooks create` printed. */
49
+ url: string;
50
+ /** The endpoint's signing secret. */
51
+ secret: string;
52
+ /** An alternative `fetch`, for a proxy or a test. Defaults to the global one. */
53
+ fetch?: typeof globalThis.fetch;
54
+ /**
55
+ * How long one delivery may take before it is abandoned and `WebhookUnreachableError` is thrown. Defaults to
56
+ * 120 seconds, which covers a large scan on a slow link. A `signal` passed to `send` adds to this; it does not
57
+ * replace it.
58
+ */
59
+ timeoutMs?: number;
60
+ };
61
+ type SendOptions = {
62
+ /** Reuse an id only to retry the same document. Defaults to a fresh UUID. */
63
+ eventId?: string;
64
+ /** Abort the delivery early, for a shutdown or the caller's own deadline. */
65
+ signal?: AbortSignal;
66
+ };
67
+ declare const DEFAULT_TIMEOUT_MS = 120000;
68
+ type WebhookSender = {
69
+ readonly url: string;
70
+ /**
71
+ * Send one document, or several files as one document. Resolves with the server's answer, accepted or refused.
72
+ * Throws `WebhookConfigError` for a bad call (nothing sent) and `WebhookUnreachableError` when no answer came
73
+ * back (retry with the `eventId` the error carries).
74
+ */
75
+ send(files: WebhookFile | WebhookFile[], options?: SendOptions): Promise<WebhookResult>;
76
+ };
77
+ /** A `WebhookFile` read from disk, media type inferred from the extension. */
78
+ declare function fileFromPath(path: string, options?: {
79
+ field?: string;
80
+ contentType?: string;
81
+ }): WebhookFile;
82
+ /** A sender bound to one endpoint: its URL and its secret. Make one per endpoint and keep it. */
83
+ declare function createWebhookSender(options: WebhookSenderOptions): WebhookSender;
84
+
85
+ /**
86
+ * Configuration from the environment: the two values an administrator hands over, and nothing else.
87
+ *
88
+ * The secret can be the value itself or the path of a file holding it, which is how `braille webhooks create
89
+ * --secret-file` wrote it. When both are set the file wins, because a file is the deliberate choice.
90
+ */
91
+ declare const ENV: {
92
+ readonly url: "BRAILLE_WEBHOOK_URL";
93
+ readonly secret: "BRAILLE_WEBHOOK_SECRET";
94
+ readonly secretFile: "BRAILLE_WEBHOOK_SECRET_FILE";
95
+ };
96
+ type EnvSource = Record<string, string | undefined>;
97
+ /**
98
+ * Parse a `.env` file: `KEY=value` lines, an optional `export ` prefix, single or double quotes, `#` comments and
99
+ * blank lines. Nothing is interpolated. Deliberately small so there is no dependency to audit.
100
+ */
101
+ declare function parseEnvFile(text: string): Record<string, string>;
102
+ /** Read and parse a `.env` file. Throws `WebhookConfigError` when it cannot be read. */
103
+ declare function readEnvFile(path: string): Record<string, string>;
104
+ /**
105
+ * Sender options from `BRAILLE_WEBHOOK_URL` and `BRAILLE_WEBHOOK_SECRET` or `BRAILLE_WEBHOOK_SECRET_FILE`.
106
+ *
107
+ * Defaults to `process.env`. Pass a merged object to layer a `.env` file beneath it; the command does exactly that.
108
+ * Throws `WebhookConfigError` naming what is missing. The secret value is never part of any message.
109
+ */
110
+ declare function optionsFromEnv(env?: EnvSource): WebhookSenderOptions;
111
+
112
+ /** A problem with how the sender was configured or called. Nothing was sent. */
113
+ declare class WebhookConfigError extends Error {
114
+ readonly name = "WebhookConfigError";
115
+ }
116
+ /**
117
+ * The endpoint could not be reached, or did not answer in time. Nothing is known about whether the server saw the
118
+ * request, so the correct action is to retry **with the same `eventId`**, which is carried here for that purpose.
119
+ */
120
+ declare class WebhookUnreachableError extends Error {
121
+ readonly name = "WebhookUnreachableError";
122
+ readonly eventId: string;
123
+ readonly url: string;
124
+ constructor(url: string, eventId: string, cause: unknown);
125
+ }
126
+
127
+ /**
128
+ * The signing contract from `guides/customer-webhooks.md`, and nothing else.
129
+ *
130
+ * Two headers go on every request. `Braille-Event-Id` is a UUID or a ULID the sender mints per document.
131
+ * `Braille-Signature` is `t=<unix seconds>,v1=<hex>` where `v1` is HMAC-SHA256, keyed on the endpoint secret, over
132
+ * the bytes `{t}.{eventId}.{raw body}`. The event id is inside the signed string on purpose: it arrives in a
133
+ * header, not in the body, so without it a captured request could be replayed under a fresh id inside the
134
+ * timestamp window.
135
+ */
136
+ declare const EVENT_ID_HEADER = "Braille-Event-Id";
137
+ declare const SIGNATURE_HEADER = "Braille-Signature";
138
+ /** The server accepts `t` within this many seconds of its own clock, either way. */
139
+ declare const TIMESTAMP_TOLERANCE_SECONDS = 300;
140
+ /** A UUID of any version, or a ULID. Anything else is refused by the server with `400 INVALID_REQUEST`. */
141
+ declare function isEventId(value: string): boolean;
142
+ /** A fresh event id. One per document; reuse it only to retry that same document. */
143
+ declare function newEventId(): string;
144
+ /** Whole Unix seconds, as the header carries them. */
145
+ declare function unixSeconds(now?: Date): number;
146
+ /**
147
+ * The exact bytes the server verifies: `{t}.{eventId}.` as UTF-8, then the raw body. `t` is the token that goes in
148
+ * the header, as a string, so what is hashed is what is sent.
149
+ */
150
+ declare function signedPayload(timestamp: number | string, eventId: string, body: Uint8Array): Buffer;
151
+ type SignatureInput = {
152
+ secret: string;
153
+ timestamp: number | string;
154
+ eventId: string;
155
+ body: Uint8Array;
156
+ };
157
+ /** The value of the `Braille-Signature` header. */
158
+ declare function signatureHeader({ secret, timestamp, eventId, body }: SignatureInput): string;
159
+
160
+ export { CONTENT_TYPES, DEFAULT_TIMEOUT_MS, ENV, EVENT_ID_HEADER, SIGNATURE_HEADER, TIMESTAMP_TOLERANCE_SECONDS, WebhookConfigError, WebhookUnreachableError, createWebhookSender, fileFromPath, isEventId, newEventId, optionsFromEnv, parseEnvFile, readEnvFile, signatureHeader, signedPayload, unixSeconds };
161
+ export type { EnvSource, SendOptions, SignatureInput, WebhookAccepted, WebhookFile, WebhookRefused, WebhookResult, WebhookSender, WebhookSenderOptions };
@@ -0,0 +1,161 @@
1
+ /**
2
+ * One signed multipart POST to a Braille webhook endpoint.
3
+ *
4
+ * The body is encoded once, signed byte for byte, and that same buffer is sent, because the signature covers the
5
+ * raw bytes and a re-encoded body would not verify. The secret is used and never surfaces in a result, an error or
6
+ * a log line.
7
+ */
8
+ /** The media types Braille accepts, by file extension. Anything else is `415 UNSUPPORTED_FILE_TYPE`. */
9
+ declare const CONTENT_TYPES: Readonly<Record<string, string>>;
10
+ type WebhookFile = {
11
+ /** The document's bytes. */
12
+ data: Uint8Array | ArrayBuffer | Blob;
13
+ /** The name the document lands with, extension included. Decides the media type when `contentType` is omitted. */
14
+ filename: string;
15
+ /** Normally inferred from the filename's extension. */
16
+ contentType?: string;
17
+ /** The multipart field name. Defaults to `file`. `surfaceId` and `surfaceModality` are reserved. */
18
+ field?: string;
19
+ };
20
+ type WebhookAccepted = {
21
+ ok: true;
22
+ /** 200 when every file stored, 207 when some did not; see `files`. */
23
+ status: number;
24
+ eventId: string;
25
+ /** True on a 207. Do not retry a 207 with the same event id: send the failed files as a new event. */
26
+ partial: boolean;
27
+ workspaceDocumentId: string | null;
28
+ files: Array<{
29
+ fileName: string;
30
+ disposition: string;
31
+ }>;
32
+ };
33
+ type WebhookRefused = {
34
+ ok: false;
35
+ status: number;
36
+ eventId: string;
37
+ /** A stable code from the guide's table, or `UNEXPECTED_RESPONSE` when the answer was not Braille's JSON. */
38
+ code: string;
39
+ /** Customer-facing copy. Branch on `code`, never on this. */
40
+ message: string;
41
+ /** True for 429 and every 5xx: retry later **with the same `eventId`**. False means fix the cause first. */
42
+ retryable: boolean;
43
+ /** From the `Retry-After` header on a 429, in seconds. */
44
+ retryAfterSeconds: number | null;
45
+ };
46
+ type WebhookResult = WebhookAccepted | WebhookRefused;
47
+ type WebhookSenderOptions = {
48
+ /** The delivery URL `braille webhooks create` printed. */
49
+ url: string;
50
+ /** The endpoint's signing secret. */
51
+ secret: string;
52
+ /** An alternative `fetch`, for a proxy or a test. Defaults to the global one. */
53
+ fetch?: typeof globalThis.fetch;
54
+ /**
55
+ * How long one delivery may take before it is abandoned and `WebhookUnreachableError` is thrown. Defaults to
56
+ * 120 seconds, which covers a large scan on a slow link. A `signal` passed to `send` adds to this; it does not
57
+ * replace it.
58
+ */
59
+ timeoutMs?: number;
60
+ };
61
+ type SendOptions = {
62
+ /** Reuse an id only to retry the same document. Defaults to a fresh UUID. */
63
+ eventId?: string;
64
+ /** Abort the delivery early, for a shutdown or the caller's own deadline. */
65
+ signal?: AbortSignal;
66
+ };
67
+ declare const DEFAULT_TIMEOUT_MS = 120000;
68
+ type WebhookSender = {
69
+ readonly url: string;
70
+ /**
71
+ * Send one document, or several files as one document. Resolves with the server's answer, accepted or refused.
72
+ * Throws `WebhookConfigError` for a bad call (nothing sent) and `WebhookUnreachableError` when no answer came
73
+ * back (retry with the `eventId` the error carries).
74
+ */
75
+ send(files: WebhookFile | WebhookFile[], options?: SendOptions): Promise<WebhookResult>;
76
+ };
77
+ /** A `WebhookFile` read from disk, media type inferred from the extension. */
78
+ declare function fileFromPath(path: string, options?: {
79
+ field?: string;
80
+ contentType?: string;
81
+ }): WebhookFile;
82
+ /** A sender bound to one endpoint: its URL and its secret. Make one per endpoint and keep it. */
83
+ declare function createWebhookSender(options: WebhookSenderOptions): WebhookSender;
84
+
85
+ /**
86
+ * Configuration from the environment: the two values an administrator hands over, and nothing else.
87
+ *
88
+ * The secret can be the value itself or the path of a file holding it, which is how `braille webhooks create
89
+ * --secret-file` wrote it. When both are set the file wins, because a file is the deliberate choice.
90
+ */
91
+ declare const ENV: {
92
+ readonly url: "BRAILLE_WEBHOOK_URL";
93
+ readonly secret: "BRAILLE_WEBHOOK_SECRET";
94
+ readonly secretFile: "BRAILLE_WEBHOOK_SECRET_FILE";
95
+ };
96
+ type EnvSource = Record<string, string | undefined>;
97
+ /**
98
+ * Parse a `.env` file: `KEY=value` lines, an optional `export ` prefix, single or double quotes, `#` comments and
99
+ * blank lines. Nothing is interpolated. Deliberately small so there is no dependency to audit.
100
+ */
101
+ declare function parseEnvFile(text: string): Record<string, string>;
102
+ /** Read and parse a `.env` file. Throws `WebhookConfigError` when it cannot be read. */
103
+ declare function readEnvFile(path: string): Record<string, string>;
104
+ /**
105
+ * Sender options from `BRAILLE_WEBHOOK_URL` and `BRAILLE_WEBHOOK_SECRET` or `BRAILLE_WEBHOOK_SECRET_FILE`.
106
+ *
107
+ * Defaults to `process.env`. Pass a merged object to layer a `.env` file beneath it; the command does exactly that.
108
+ * Throws `WebhookConfigError` naming what is missing. The secret value is never part of any message.
109
+ */
110
+ declare function optionsFromEnv(env?: EnvSource): WebhookSenderOptions;
111
+
112
+ /** A problem with how the sender was configured or called. Nothing was sent. */
113
+ declare class WebhookConfigError extends Error {
114
+ readonly name = "WebhookConfigError";
115
+ }
116
+ /**
117
+ * The endpoint could not be reached, or did not answer in time. Nothing is known about whether the server saw the
118
+ * request, so the correct action is to retry **with the same `eventId`**, which is carried here for that purpose.
119
+ */
120
+ declare class WebhookUnreachableError extends Error {
121
+ readonly name = "WebhookUnreachableError";
122
+ readonly eventId: string;
123
+ readonly url: string;
124
+ constructor(url: string, eventId: string, cause: unknown);
125
+ }
126
+
127
+ /**
128
+ * The signing contract from `guides/customer-webhooks.md`, and nothing else.
129
+ *
130
+ * Two headers go on every request. `Braille-Event-Id` is a UUID or a ULID the sender mints per document.
131
+ * `Braille-Signature` is `t=<unix seconds>,v1=<hex>` where `v1` is HMAC-SHA256, keyed on the endpoint secret, over
132
+ * the bytes `{t}.{eventId}.{raw body}`. The event id is inside the signed string on purpose: it arrives in a
133
+ * header, not in the body, so without it a captured request could be replayed under a fresh id inside the
134
+ * timestamp window.
135
+ */
136
+ declare const EVENT_ID_HEADER = "Braille-Event-Id";
137
+ declare const SIGNATURE_HEADER = "Braille-Signature";
138
+ /** The server accepts `t` within this many seconds of its own clock, either way. */
139
+ declare const TIMESTAMP_TOLERANCE_SECONDS = 300;
140
+ /** A UUID of any version, or a ULID. Anything else is refused by the server with `400 INVALID_REQUEST`. */
141
+ declare function isEventId(value: string): boolean;
142
+ /** A fresh event id. One per document; reuse it only to retry that same document. */
143
+ declare function newEventId(): string;
144
+ /** Whole Unix seconds, as the header carries them. */
145
+ declare function unixSeconds(now?: Date): number;
146
+ /**
147
+ * The exact bytes the server verifies: `{t}.{eventId}.` as UTF-8, then the raw body. `t` is the token that goes in
148
+ * the header, as a string, so what is hashed is what is sent.
149
+ */
150
+ declare function signedPayload(timestamp: number | string, eventId: string, body: Uint8Array): Buffer;
151
+ type SignatureInput = {
152
+ secret: string;
153
+ timestamp: number | string;
154
+ eventId: string;
155
+ body: Uint8Array;
156
+ };
157
+ /** The value of the `Braille-Signature` header. */
158
+ declare function signatureHeader({ secret, timestamp, eventId, body }: SignatureInput): string;
159
+
160
+ export { CONTENT_TYPES, DEFAULT_TIMEOUT_MS, ENV, EVENT_ID_HEADER, SIGNATURE_HEADER, TIMESTAMP_TOLERANCE_SECONDS, WebhookConfigError, WebhookUnreachableError, createWebhookSender, fileFromPath, isEventId, newEventId, optionsFromEnv, parseEnvFile, readEnvFile, signatureHeader, signedPayload, unixSeconds };
161
+ export type { EnvSource, SendOptions, SignatureInput, WebhookAccepted, WebhookFile, WebhookRefused, WebhookResult, WebhookSender, WebhookSenderOptions };
package/dist/index.js ADDED
@@ -0,0 +1,266 @@
1
+ // src/send.ts
2
+ import { readFileSync } from "fs";
3
+ import { basename, extname } from "path";
4
+
5
+ // src/errors.ts
6
+ var WebhookConfigError = class extends Error {
7
+ name = "WebhookConfigError";
8
+ };
9
+ function describe(cause) {
10
+ const error = cause;
11
+ if (error?.name === "TimeoutError") return "no answer within the timeout";
12
+ if (error?.name === "AbortError") return "aborted by the caller";
13
+ return error?.cause?.code ?? error?.cause?.errors?.[0]?.code ?? error?.cause?.message ?? error?.message ?? String(cause);
14
+ }
15
+ var WebhookUnreachableError = class extends Error {
16
+ name = "WebhookUnreachableError";
17
+ eventId;
18
+ url;
19
+ constructor(url, eventId, cause) {
20
+ super(`Could not reach ${url}: ${describe(cause)}`, { cause });
21
+ this.url = url;
22
+ this.eventId = eventId;
23
+ }
24
+ };
25
+
26
+ // src/sign.ts
27
+ import { createHmac, randomUUID } from "crypto";
28
+ var EVENT_ID_HEADER = "Braille-Event-Id";
29
+ var SIGNATURE_HEADER = "Braille-Signature";
30
+ var TIMESTAMP_TOLERANCE_SECONDS = 300;
31
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
32
+ var ULID = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
33
+ function isEventId(value) {
34
+ return UUID.test(value) || ULID.test(value);
35
+ }
36
+ function newEventId() {
37
+ return randomUUID();
38
+ }
39
+ function unixSeconds(now = /* @__PURE__ */ new Date()) {
40
+ return Math.floor(now.getTime() / 1e3);
41
+ }
42
+ function signedPayload(timestamp, eventId, body) {
43
+ return Buffer.concat([Buffer.from(`${timestamp}.${eventId}.`, "utf8"), Buffer.from(body)]);
44
+ }
45
+ function signatureHeader({ secret, timestamp, eventId, body }) {
46
+ const v1 = createHmac("sha256", secret).update(signedPayload(timestamp, eventId, body)).digest("hex");
47
+ return `t=${timestamp},v1=${v1}`;
48
+ }
49
+
50
+ // src/send.ts
51
+ var CONTENT_TYPES = {
52
+ ".pdf": "application/pdf",
53
+ ".png": "image/png",
54
+ ".jpg": "image/jpeg",
55
+ ".jpeg": "image/jpeg",
56
+ ".gif": "image/gif",
57
+ ".webp": "image/webp",
58
+ ".zip": "application/zip"
59
+ };
60
+ var RESERVED_FIELDS = /* @__PURE__ */ new Set(["surfaceId", "surfaceModality"]);
61
+ var DEFAULT_TIMEOUT_MS = 12e4;
62
+ function fileFromPath(path, options = {}) {
63
+ let data;
64
+ try {
65
+ data = readFileSync(path);
66
+ } catch (error) {
67
+ const code = error.code ?? error.message;
68
+ throw new WebhookConfigError(`Could not read the document at ${path}: ${code}`);
69
+ }
70
+ return { data, filename: basename(path), ...options };
71
+ }
72
+ function contentTypeFor(file) {
73
+ if (file.contentType) return file.contentType;
74
+ const type = CONTENT_TYPES[extname(file.filename).toLowerCase()];
75
+ if (!type) {
76
+ throw new WebhookConfigError(
77
+ `${file.filename}: Braille accepts PDF, PNG, JPEG, GIF, WebP and ZIP. Pass contentType to send it anyway.`
78
+ );
79
+ }
80
+ return type;
81
+ }
82
+ function toBlob(file, type) {
83
+ if (file.data instanceof Blob) return file.data.type === type ? file.data : new Blob([file.data], { type });
84
+ return new Blob([file.data], { type });
85
+ }
86
+ async function encode(files) {
87
+ const form = new FormData();
88
+ for (const file of files) {
89
+ const field = file.field ?? "file";
90
+ if (RESERVED_FIELDS.has(field)) {
91
+ throw new WebhookConfigError(`"${field}" is a reserved field name; the endpoint decides the destination.`);
92
+ }
93
+ if (!file.filename) throw new WebhookConfigError("Every file needs a filename.");
94
+ form.append(field, toBlob(file, contentTypeFor(file)), file.filename);
95
+ }
96
+ const encoded = new Response(form);
97
+ const contentType = encoded.headers.get("content-type");
98
+ if (!contentType) throw new WebhookConfigError("The multipart body could not be encoded.");
99
+ return { body: Buffer.from(await encoded.arrayBuffer()), contentType };
100
+ }
101
+ function parseRetryAfter(value) {
102
+ if (!value) return null;
103
+ const seconds = Number(value);
104
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
105
+ }
106
+ function interpret(status, text, eventId, retryAfter) {
107
+ let json = null;
108
+ try {
109
+ const parsed = JSON.parse(text);
110
+ if (parsed && typeof parsed === "object") json = parsed;
111
+ } catch {
112
+ json = null;
113
+ }
114
+ if (status >= 200 && status < 300) {
115
+ const files = Array.isArray(json?.files) ? json.files.flatMap(
116
+ (row) => row && typeof row === "object" ? [
117
+ {
118
+ fileName: String(row.fileName ?? ""),
119
+ disposition: String(row.disposition ?? "")
120
+ }
121
+ ] : []
122
+ ) : [];
123
+ return {
124
+ ok: true,
125
+ status,
126
+ eventId: typeof json?.eventId === "string" ? json.eventId : eventId,
127
+ partial: status === 207,
128
+ workspaceDocumentId: typeof json?.workspaceDocumentId === "string" ? json.workspaceDocumentId : null,
129
+ files
130
+ };
131
+ }
132
+ const code = typeof json?.code === "string" ? json.code : "UNEXPECTED_RESPONSE";
133
+ const message = typeof json?.message === "string" ? json.message : `The endpoint answered ${status} without Braille's JSON body. Check the URL.`;
134
+ return {
135
+ ok: false,
136
+ status,
137
+ eventId,
138
+ code,
139
+ message,
140
+ retryable: status === 429 || status >= 500,
141
+ retryAfterSeconds: parseRetryAfter(retryAfter)
142
+ };
143
+ }
144
+ function createWebhookSender(options) {
145
+ const url = options.url?.trim();
146
+ let parsed;
147
+ try {
148
+ parsed = new URL(url);
149
+ } catch {
150
+ throw new WebhookConfigError(`"${url}" is not a URL. Use the delivery URL Braille printed for the endpoint.`);
151
+ }
152
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
153
+ throw new WebhookConfigError(`The delivery URL must be http or https, not ${parsed.protocol}`);
154
+ }
155
+ const secret = options.secret?.trim();
156
+ if (!secret) throw new WebhookConfigError("The signing secret is empty.");
157
+ const doFetch = options.fetch ?? globalThis.fetch;
158
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
159
+ if (!(timeoutMs > 0)) throw new WebhookConfigError("timeoutMs must be a positive number of milliseconds.");
160
+ return {
161
+ url,
162
+ async send(input, sendOptions = {}) {
163
+ const files = Array.isArray(input) ? input : [input];
164
+ if (files.length === 0) throw new WebhookConfigError("Nothing to send: pass at least one file.");
165
+ const eventId = sendOptions.eventId ?? newEventId();
166
+ if (!isEventId(eventId)) throw new WebhookConfigError(`"${eventId}" is not a UUID or a ULID.`);
167
+ const { body, contentType } = await encode(files);
168
+ const t = unixSeconds();
169
+ const headers = {
170
+ "content-type": contentType,
171
+ [EVENT_ID_HEADER]: eventId,
172
+ [SIGNATURE_HEADER]: signatureHeader({ secret, timestamp: t, eventId, body })
173
+ };
174
+ const timeout = AbortSignal.timeout(timeoutMs);
175
+ const signal = sendOptions.signal ? AbortSignal.any([sendOptions.signal, timeout]) : timeout;
176
+ let response;
177
+ try {
178
+ response = await doFetch(url, { method: "POST", headers, body, signal, redirect: "error" });
179
+ } catch (error) {
180
+ throw new WebhookUnreachableError(url, eventId, error);
181
+ }
182
+ return interpret(response.status, await response.text(), eventId, response.headers.get("retry-after"));
183
+ }
184
+ };
185
+ }
186
+
187
+ // src/env.ts
188
+ import { readFileSync as readFileSync2 } from "fs";
189
+ var ENV = {
190
+ url: "BRAILLE_WEBHOOK_URL",
191
+ secret: "BRAILLE_WEBHOOK_SECRET",
192
+ secretFile: "BRAILLE_WEBHOOK_SECRET_FILE"
193
+ };
194
+ function parseEnvFile(text) {
195
+ const values = {};
196
+ for (const rawLine of text.split(/\r?\n/)) {
197
+ const line = rawLine.trim();
198
+ if (!line || line.startsWith("#")) continue;
199
+ const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
200
+ if (!match) continue;
201
+ const key = match[1];
202
+ let value = (match[2] ?? "").trim();
203
+ const quote = value[0];
204
+ if ((quote === '"' || quote === "'") && value.length >= 2 && value.endsWith(quote)) {
205
+ value = value.slice(1, -1);
206
+ if (quote === '"') value = value.replace(/\\n/g, "\n");
207
+ } else {
208
+ value = value.replace(/\s+#.*$/, "");
209
+ }
210
+ values[key] = value;
211
+ }
212
+ return values;
213
+ }
214
+ function readEnvFile(path) {
215
+ let text;
216
+ try {
217
+ text = readFileSync2(path, "utf8");
218
+ } catch (error) {
219
+ const code = error.code ?? error.message;
220
+ throw new WebhookConfigError(`Could not read the env file at ${path}: ${code}`);
221
+ }
222
+ return parseEnvFile(text);
223
+ }
224
+ function optionsFromEnv(env = process.env) {
225
+ const url = env[ENV.url]?.trim();
226
+ if (!url) throw new WebhookConfigError(`${ENV.url} is not set. It is the delivery URL Braille printed for the endpoint.`);
227
+ const secretFile = env[ENV.secretFile]?.trim();
228
+ let secret;
229
+ if (secretFile) {
230
+ try {
231
+ secret = readFileSync2(secretFile, "utf8").trim();
232
+ } catch (error) {
233
+ const code = error.code ?? error.message;
234
+ throw new WebhookConfigError(`Could not read the secret file at ${secretFile}: ${code}`);
235
+ }
236
+ if (!secret) throw new WebhookConfigError(`The secret file at ${secretFile} is empty.`);
237
+ } else {
238
+ secret = env[ENV.secret]?.trim();
239
+ if (!secret) {
240
+ throw new WebhookConfigError(
241
+ `Neither ${ENV.secret} nor ${ENV.secretFile} is set. One of them must hold the endpoint's signing secret.`
242
+ );
243
+ }
244
+ }
245
+ return { url, secret };
246
+ }
247
+ export {
248
+ CONTENT_TYPES,
249
+ DEFAULT_TIMEOUT_MS,
250
+ ENV,
251
+ EVENT_ID_HEADER,
252
+ SIGNATURE_HEADER,
253
+ TIMESTAMP_TOLERANCE_SECONDS,
254
+ WebhookConfigError,
255
+ WebhookUnreachableError,
256
+ createWebhookSender,
257
+ fileFromPath,
258
+ isEventId,
259
+ newEventId,
260
+ optionsFromEnv,
261
+ parseEnvFile,
262
+ readEnvFile,
263
+ signatureHeader,
264
+ signedPayload,
265
+ unixSeconds
266
+ };
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@braille-ai/webhook-send",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Send documents to a Braille webhook endpoint: a signed multipart POST, as a library and as a command.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "dist/index.cjs",
8
+ "module": "dist/index.js",
9
+ "types": "dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "import": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "require": {
17
+ "types": "./dist/index.d.cts",
18
+ "default": "./dist/index.cjs"
19
+ }
20
+ }
21
+ },
22
+ "bin": {
23
+ "braille-webhook-send": "dist/bin.cjs"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "engines": {
31
+ "node": ">=20"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "scripts": {
37
+ "build": "tsup",
38
+ "dev": "tsup --watch",
39
+ "typecheck": "tsc -p tsconfig.json",
40
+ "lint": "echo 'no lint configured'",
41
+ "test": "echo 'no tests yet' && exit 0"
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "^24.2.1",
45
+ "tsup": "9.0.0",
46
+ "typescript": "^5.8.3"
47
+ }
48
+ }