@supacloud/function-adapter 0.5.2 → 0.6.1
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 +63 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +173 -1
- package/dist/scheduled-worker.d.ts +12 -0
- package/dist/secret.d.ts +2 -0
- package/dist/worker-http.d.ts +29 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,6 +2,69 @@
|
|
|
2
2
|
|
|
3
3
|
Fetch-based adapters for SupaCloud Edge Functions.
|
|
4
4
|
|
|
5
|
+
The package also provides generic HTTP invocation adapters for application
|
|
6
|
+
workers. `createWorkerHttpHandler` handles POST validation, a shared-secret
|
|
7
|
+
header, bounded `batchSize` input, stable error responses, and no-store
|
|
8
|
+
responses. `createScheduledWorkerHttpHandler` handles POST validation and
|
|
9
|
+
either a service-role bearer or an application-provided verifier.
|
|
10
|
+
|
|
11
|
+
These adapters do not own queue claims, leases, retries, business
|
|
12
|
+
authorization, or domain state. Applications inject those concerns through
|
|
13
|
+
`runBatch`; FA can use them for its worker entry points while keeping FA task
|
|
14
|
+
decoding, membership authorization, provider authorization, and command
|
|
15
|
+
receipts in the application.
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import {
|
|
19
|
+
createSupaCloudHandler,
|
|
20
|
+
createWorkerHttpHandler,
|
|
21
|
+
} from "@supacloud/function-adapter";
|
|
22
|
+
|
|
23
|
+
export default createSupaCloudHandler(createWorkerHttpHandler({
|
|
24
|
+
expectedSecret: process.env.WORKER_SECRET ?? "",
|
|
25
|
+
defaultBatchSize: 5,
|
|
26
|
+
maxBatchSize: 20,
|
|
27
|
+
runBatch: ({ batchSize }) => applicationWorker.runBatch(batchSize),
|
|
28
|
+
}));
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
The worker accepts an empty body or a JSON object with an optional integer
|
|
32
|
+
`batchSize`. Bodies are limited to 4096 bytes by default; `maxBodyBytes` can
|
|
33
|
+
configure this limit. The limit is checked while reading the stream, regardless
|
|
34
|
+
of `Content-Length`, and oversized bodies return HTTP 400 before executing work.
|
|
35
|
+
The default header is `x-supacloud-worker-secret`; `secretHeader` and `errorCodes`
|
|
36
|
+
can preserve an application's existing invocation contract. Batch bounds are
|
|
37
|
+
validated when constructing the handler. Secrets must have at least 32
|
|
38
|
+
characters. Missing or weak secrets fail closed with HTTP 503.
|
|
39
|
+
|
|
40
|
+
Worker authentication targets the Bun runtime: it uses `Bun.CryptoHasher` SHA-256
|
|
41
|
+
and Bun's native `node:crypto` `timingSafeEqual`. Each handler caches its expected
|
|
42
|
+
digest at construction, avoiding repeated encoding, hashing of the configured
|
|
43
|
+
secret, and Web Crypto Promise scheduling in the request path. Recreate the
|
|
44
|
+
handler when rotating credentials or changing its authorization callback.
|
|
45
|
+
`constantTimeSecretMatches` retains its Promise-based API for existing callers.
|
|
46
|
+
`Response.json` remains the native Fetch response path; no JSON library is added.
|
|
47
|
+
Run `bun bench/worker-auth.ts` from this package to compare authentication alone
|
|
48
|
+
against the previous Web Crypto implementation, not end-to-end Function latency.
|
|
49
|
+
|
|
50
|
+
For scheduled invocations, supply exactly one of `expectedBearer` (the full
|
|
51
|
+
expected token, without the `Bearer ` prefix) or `authorize(request)`. A bearer
|
|
52
|
+
is compared to the configured secret; this is not JWT claim verification.
|
|
53
|
+
Use `authorize` for a platform JWT/signature verifier; only an explicit `true`
|
|
54
|
+
result authorizes execution. The scheduled adapter does not parse the body:
|
|
55
|
+
applications that consume it in `authorize` or `runBatch` must enforce their
|
|
56
|
+
own input limits. Never authorize a token
|
|
57
|
+
merely by decoding a `service_role` claim.
|
|
58
|
+
|
|
59
|
+
Both adapters return `{ ok: true, result }` on success, with HTTP 200 by default.
|
|
60
|
+
`successStatus` may select 202 for delegated execution. Errors use
|
|
61
|
+
`{ ok: false, error: { code } }` (the worker also includes a generic message).
|
|
62
|
+
They never include exception details. Optional `logError` receives the original
|
|
63
|
+
exception for application-controlled reporting; redact credentials before
|
|
64
|
+
logging it. These adapters do not register cron jobs, start polling loops, or
|
|
65
|
+
replace `createWorker()` / `createSupAuthRequestContext()` in `@supacloud/elysia`.
|
|
66
|
+
Publishing this package does not migrate existing application entry points.
|
|
67
|
+
|
|
5
68
|
The adapter returns a default-exportable object with `fetch(request)` and
|
|
6
69
|
explicit SupaCloud metadata. It never listens on a port, starts a process, or
|
|
7
70
|
serves static assets.
|
package/dist/index.d.ts
CHANGED
|
@@ -10,3 +10,5 @@ export type SupaCloudFunctionExport = {
|
|
|
10
10
|
/** Mark a Fetch handler as a route-aware SupaCloud Function adapter. */
|
|
11
11
|
export declare function createSupaCloudHandler(handler: SupaCloudFunctionHandler, framework?: SupaCloudFunctionFramework): SupaCloudFunctionExport;
|
|
12
12
|
export { createSvelteKitHandler } from "./sveltekit";
|
|
13
|
+
export { constantTimeSecretMatches, createWorkerHttpHandler, type WorkerBatchRequest, type WorkerHttpErrorCodes, type WorkerHttpOptions, } from "./worker-http";
|
|
14
|
+
export { createScheduledWorkerHttpHandler, type ScheduledWorkerHttpOptions, } from "./scheduled-worker";
|
package/dist/index.js
CHANGED
|
@@ -6,6 +6,175 @@ function createSvelteKitHandler(options) {
|
|
|
6
6
|
getClientAddress: () => options.getClientAddress?.(request) ?? "0.0.0.0"
|
|
7
7
|
}), "sveltekit-function");
|
|
8
8
|
}
|
|
9
|
+
// src/secret.ts
|
|
10
|
+
import { timingSafeEqual } from "crypto";
|
|
11
|
+
function createSecretMatcher(expected) {
|
|
12
|
+
const expectedDigest = Bun.CryptoHasher.hash("sha256", expected);
|
|
13
|
+
const configured = expected.length > 0;
|
|
14
|
+
return (provided) => {
|
|
15
|
+
const providedDigest = Bun.CryptoHasher.hash("sha256", provided);
|
|
16
|
+
return timingSafeEqual(providedDigest, expectedDigest) && provided.length > 0 && configured;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// src/worker-http.ts
|
|
21
|
+
var DEFAULT_ERROR_CODES = {
|
|
22
|
+
notConfigured: "SUPACLOUD_WORKER_SECRET_NOT_CONFIGURED",
|
|
23
|
+
unauthorized: "SUPACLOUD_WORKER_UNAUTHORIZED",
|
|
24
|
+
invalidRequest: "SUPACLOUD_WORKER_REQUEST_INVALID",
|
|
25
|
+
unavailable: "SUPACLOUD_WORKER_UNAVAILABLE"
|
|
26
|
+
};
|
|
27
|
+
function jsonResponse(body, status) {
|
|
28
|
+
return Response.json(body, {
|
|
29
|
+
status,
|
|
30
|
+
headers: {
|
|
31
|
+
"cache-control": "no-store",
|
|
32
|
+
...status === 405 ? { allow: "POST" } : {}
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
async function constantTimeSecretMatches(provided, expected) {
|
|
37
|
+
return createSecretMatcher(expected)(provided);
|
|
38
|
+
}
|
|
39
|
+
async function parseBatchRequest(request, defaultBatchSize, maxBatchSize, maxBodyBytes) {
|
|
40
|
+
let text = "";
|
|
41
|
+
if (request.body) {
|
|
42
|
+
const reader = request.body.getReader();
|
|
43
|
+
const decoder = new TextDecoder;
|
|
44
|
+
let size = 0;
|
|
45
|
+
try {
|
|
46
|
+
while (true) {
|
|
47
|
+
const { done, value } = await reader.read();
|
|
48
|
+
if (done)
|
|
49
|
+
break;
|
|
50
|
+
size += value.byteLength;
|
|
51
|
+
if (size > maxBodyBytes) {
|
|
52
|
+
reader.cancel().catch(() => {
|
|
53
|
+
return;
|
|
54
|
+
});
|
|
55
|
+
throw new RangeError("request body exceeds the byte limit");
|
|
56
|
+
}
|
|
57
|
+
text += decoder.decode(value, { stream: true });
|
|
58
|
+
}
|
|
59
|
+
text += decoder.decode();
|
|
60
|
+
} finally {
|
|
61
|
+
reader.releaseLock();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (!text.trim())
|
|
65
|
+
return { batchSize: defaultBatchSize };
|
|
66
|
+
let payload;
|
|
67
|
+
try {
|
|
68
|
+
payload = JSON.parse(text);
|
|
69
|
+
} catch {
|
|
70
|
+
throw new TypeError("request body must be JSON");
|
|
71
|
+
}
|
|
72
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
73
|
+
throw new TypeError("request body must be an object");
|
|
74
|
+
}
|
|
75
|
+
const batchSize = Object.hasOwn(payload, "batchSize") ? payload.batchSize : defaultBatchSize;
|
|
76
|
+
if (!Number.isSafeInteger(batchSize) || Number(batchSize) < 1 || Number(batchSize) > maxBatchSize) {
|
|
77
|
+
throw new RangeError(`batchSize must be between 1 and ${maxBatchSize}`);
|
|
78
|
+
}
|
|
79
|
+
return { batchSize: Number(batchSize) };
|
|
80
|
+
}
|
|
81
|
+
function createWorkerHttpHandler(options) {
|
|
82
|
+
const errorCodes = { ...DEFAULT_ERROR_CODES, ...options.errorCodes };
|
|
83
|
+
const defaultBatchSize = options.defaultBatchSize;
|
|
84
|
+
const maxBatchSize = options.maxBatchSize ?? 20;
|
|
85
|
+
const maxBodyBytes = options.maxBodyBytes ?? 4096;
|
|
86
|
+
const minimumSecretLength = options.minimumSecretLength ?? 32;
|
|
87
|
+
const secretHeader = options.secretHeader ?? "x-supacloud-worker-secret";
|
|
88
|
+
if (!Number.isSafeInteger(maxBatchSize) || maxBatchSize < 1 || !Number.isSafeInteger(defaultBatchSize) || defaultBatchSize < 1 || defaultBatchSize > maxBatchSize || !Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1 || !Number.isSafeInteger(minimumSecretLength) || minimumSecretLength < 32) {
|
|
89
|
+
throw new RangeError("Invalid worker batch/body bounds or minimum secret length");
|
|
90
|
+
}
|
|
91
|
+
new Headers({ [secretHeader]: "" });
|
|
92
|
+
const { expectedSecret } = options;
|
|
93
|
+
const configured = typeof expectedSecret === "string" && expectedSecret.length >= minimumSecretLength;
|
|
94
|
+
const matchesSecret = configured ? createSecretMatcher(expectedSecret) : undefined;
|
|
95
|
+
return async (request) => {
|
|
96
|
+
if (request.method !== "POST") {
|
|
97
|
+
return jsonResponse({ ok: false, error: { code: "METHOD_NOT_ALLOWED", message: "Method Not Allowed" } }, 405);
|
|
98
|
+
}
|
|
99
|
+
if (!configured) {
|
|
100
|
+
return jsonResponse({ ok: false, error: { code: errorCodes.notConfigured, message: "Worker is unavailable." } }, 503);
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
if (!matchesSecret?.(request.headers.get(secretHeader) ?? "")) {
|
|
104
|
+
return jsonResponse({ ok: false, error: { code: errorCodes.unauthorized, message: "Worker authentication failed." } }, 401);
|
|
105
|
+
}
|
|
106
|
+
let batchRequest;
|
|
107
|
+
try {
|
|
108
|
+
batchRequest = await parseBatchRequest(request, defaultBatchSize, maxBatchSize, maxBodyBytes);
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (!(error instanceof TypeError) && !(error instanceof RangeError))
|
|
111
|
+
throw error;
|
|
112
|
+
return jsonResponse({ ok: false, error: { code: errorCodes.invalidRequest, message: "Worker request is invalid." } }, 400);
|
|
113
|
+
}
|
|
114
|
+
const result = await options.runBatch(batchRequest);
|
|
115
|
+
return jsonResponse({ ok: true, result }, options.successStatus?.(result) ?? 200);
|
|
116
|
+
} catch (error) {
|
|
117
|
+
try {
|
|
118
|
+
Promise.resolve(options.logError?.(error)).catch(() => {
|
|
119
|
+
return;
|
|
120
|
+
});
|
|
121
|
+
} catch {}
|
|
122
|
+
return jsonResponse({ ok: false, error: { code: errorCodes.unavailable, message: "Worker execution failed." } }, 503);
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
// src/scheduled-worker.ts
|
|
127
|
+
var DEFAULT_ERROR_CODES2 = {
|
|
128
|
+
notConfigured: "SUPACLOUD_SCHEDULED_WORKER_NOT_CONFIGURED",
|
|
129
|
+
unauthorized: "SUPACLOUD_SCHEDULED_WORKER_UNAUTHORIZED",
|
|
130
|
+
invalidRequest: "SUPACLOUD_SCHEDULED_WORKER_REQUEST_INVALID",
|
|
131
|
+
unavailable: "SUPACLOUD_SCHEDULED_WORKER_UNAVAILABLE"
|
|
132
|
+
};
|
|
133
|
+
function jsonResponse2(body, status) {
|
|
134
|
+
return Response.json(body, {
|
|
135
|
+
status,
|
|
136
|
+
headers: {
|
|
137
|
+
"cache-control": "no-store",
|
|
138
|
+
...status === 405 ? { allow: "POST" } : {}
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
function bearerToken(request) {
|
|
143
|
+
const authorization = request.headers.get("authorization") ?? "";
|
|
144
|
+
return authorization.startsWith("Bearer ") ? authorization.slice("Bearer ".length) : "";
|
|
145
|
+
}
|
|
146
|
+
function createScheduledWorkerHttpHandler(options) {
|
|
147
|
+
const errorCodes = { ...DEFAULT_ERROR_CODES2, ...options.errorCodes };
|
|
148
|
+
const minimumSecretLength = options.minimumSecretLength ?? 32;
|
|
149
|
+
if (!Number.isSafeInteger(minimumSecretLength) || minimumSecretLength < 32) {
|
|
150
|
+
throw new RangeError("Minimum secret length must be at least 32");
|
|
151
|
+
}
|
|
152
|
+
const { expectedBearer, authorize } = options;
|
|
153
|
+
const configured = expectedBearer === undefined ? typeof authorize === "function" : authorize === undefined && typeof expectedBearer === "string" && expectedBearer.length >= minimumSecretLength;
|
|
154
|
+
const matchesSecret = configured && typeof expectedBearer === "string" ? createSecretMatcher(expectedBearer) : undefined;
|
|
155
|
+
return async (request) => {
|
|
156
|
+
if (request.method !== "POST") {
|
|
157
|
+
return jsonResponse2({ ok: false, error: { code: "METHOD_NOT_ALLOWED" } }, 405);
|
|
158
|
+
}
|
|
159
|
+
if (!configured) {
|
|
160
|
+
return jsonResponse2({ ok: false, error: { code: errorCodes.notConfigured } }, 503);
|
|
161
|
+
}
|
|
162
|
+
try {
|
|
163
|
+
if (!(authorize ? await authorize(request) === true : matchesSecret?.(bearerToken(request)))) {
|
|
164
|
+
return jsonResponse2({ ok: false, error: { code: errorCodes.unauthorized } }, 401);
|
|
165
|
+
}
|
|
166
|
+
const result = await options.runBatch(request);
|
|
167
|
+
return jsonResponse2({ ok: true, result }, options.successStatus?.(result) ?? 200);
|
|
168
|
+
} catch (error) {
|
|
169
|
+
try {
|
|
170
|
+
Promise.resolve(options.logError?.(error)).catch(() => {
|
|
171
|
+
return;
|
|
172
|
+
});
|
|
173
|
+
} catch {}
|
|
174
|
+
return jsonResponse2({ ok: false, error: { code: errorCodes.unavailable } }, 503);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
}
|
|
9
178
|
|
|
10
179
|
// src/index.ts
|
|
11
180
|
function createSupaCloudHandler(handler, framework = "fetch") {
|
|
@@ -15,6 +184,9 @@ function createSupaCloudHandler(handler, framework = "fetch") {
|
|
|
15
184
|
};
|
|
16
185
|
}
|
|
17
186
|
export {
|
|
187
|
+
constantTimeSecretMatches,
|
|
188
|
+
createScheduledWorkerHttpHandler,
|
|
18
189
|
createSupaCloudHandler,
|
|
19
|
-
createSvelteKitHandler
|
|
190
|
+
createSvelteKitHandler,
|
|
191
|
+
createWorkerHttpHandler
|
|
20
192
|
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { WorkerHttpErrorCodes } from "./worker-http";
|
|
2
|
+
export type ScheduledWorkerHttpOptions<TResult> = {
|
|
3
|
+
expectedBearer?: string;
|
|
4
|
+
authorize?: (request: Request) => boolean | Promise<boolean>;
|
|
5
|
+
runBatch: (request: Request) => TResult | Promise<TResult>;
|
|
6
|
+
successStatus?: (result: TResult) => 200 | 202;
|
|
7
|
+
minimumSecretLength?: number;
|
|
8
|
+
errorCodes?: Partial<WorkerHttpErrorCodes>;
|
|
9
|
+
logError?: (error: unknown) => void;
|
|
10
|
+
};
|
|
11
|
+
/** Creates a POST-only scheduled invocation endpoint with injected trust. */
|
|
12
|
+
export declare function createScheduledWorkerHttpHandler<TResult>(options: ScheduledWorkerHttpOptions<TResult>): (request: Request) => Promise<Response>;
|
package/dist/secret.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export type WorkerBatchRequest = {
|
|
2
|
+
batchSize: number;
|
|
3
|
+
};
|
|
4
|
+
export type WorkerHttpErrorCodes = {
|
|
5
|
+
notConfigured: string;
|
|
6
|
+
unauthorized: string;
|
|
7
|
+
invalidRequest: string;
|
|
8
|
+
unavailable: string;
|
|
9
|
+
};
|
|
10
|
+
export type WorkerHttpOptions<TResult> = {
|
|
11
|
+
expectedSecret: string;
|
|
12
|
+
runBatch: (request: WorkerBatchRequest) => TResult | Promise<TResult>;
|
|
13
|
+
defaultBatchSize: number;
|
|
14
|
+
maxBatchSize?: number;
|
|
15
|
+
maxBodyBytes?: number;
|
|
16
|
+
secretHeader?: string;
|
|
17
|
+
minimumSecretLength?: number;
|
|
18
|
+
successStatus?: (result: TResult) => 200 | 202;
|
|
19
|
+
errorCodes?: Partial<WorkerHttpErrorCodes>;
|
|
20
|
+
logError?: (error: unknown) => void;
|
|
21
|
+
};
|
|
22
|
+
/** Compare secrets without making the comparison dependent on their contents. */
|
|
23
|
+
export declare function constantTimeSecretMatches(provided: string, expected: string): Promise<boolean>;
|
|
24
|
+
/**
|
|
25
|
+
* Creates a POST-only worker endpoint. Queue claims, leases, and domain work
|
|
26
|
+
* remain injected into `runBatch`; this adapter only handles invocation trust
|
|
27
|
+
* and HTTP response hygiene.
|
|
28
|
+
*/
|
|
29
|
+
export declare function createWorkerHttpHandler<TResult>(options: WorkerHttpOptions<TResult>): (request: Request) => Promise<Response>;
|