@cogover/sdk 0.7.0 → 0.8.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.
- package/README.md +100 -4
- package/dist/crypto.d.ts +20 -0
- package/dist/crypto.js +123 -0
- package/dist/errors.d.ts +2 -2
- package/dist/errors.js +2 -2
- package/dist/fetch.d.ts +2 -0
- package/dist/fetch.js +6 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.js +2 -0
- package/dist/internal/base64.js +41 -0
- package/dist/internal/invocation.js +15 -0
- package/dist/internal/job-config.js +143 -0
- package/dist/internal/job-runtime.js +90 -0
- package/dist/internal/jobs-api.js +58 -0
- package/dist/internal/request.js +14 -2
- package/dist/internal/trigger-runtime.js +7 -0
- package/dist/internal/utf8.js +55 -0
- package/dist/internal/validation.js +8 -0
- package/dist/invocation.d.ts +14 -1
- package/dist/jobs.d.ts +95 -0
- package/dist/jobs.js +15 -0
- package/dist/request.d.ts +4 -0
- package/dist/response.js +1 -15
- package/dist/router.js +3 -0
- package/dist/script.d.ts +6 -0
- package/dist/script.js +6 -0
- package/dist/secrets.d.ts +8 -0
- package/dist/secrets.js +17 -0
- package/dist/state.js +2 -19
- package/dist/trigger.d.ts +8 -0
- package/docs/en/api-reference.md +520 -27
- package/docs/en/usage-guide.md +201 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -45,10 +45,10 @@ export default defineScript<Input, Output>(async ({ input, data, log }) => {
|
|
|
45
45
|
```
|
|
46
46
|
|
|
47
47
|
`defineScript` parses the input JSON, provides invocation metadata and scoped
|
|
48
|
-
data, schema, logging, state, lock, and
|
|
49
|
-
serializes its result. Cogover authentication credentials are
|
|
50
|
-
project code, and Cogover enforces the configured permissions and
|
|
51
|
-
capability calls.
|
|
48
|
+
data, schema, logging, state, lock, push, job, secret, and crypto APIs, waits for
|
|
49
|
+
the async handler, and serializes its result. Cogover authentication credentials are
|
|
50
|
+
not exposed to project code, and Cogover enforces the configured permissions and
|
|
51
|
+
limits on capability calls.
|
|
52
52
|
|
|
53
53
|
## Current identity and workspace
|
|
54
54
|
|
|
@@ -189,6 +189,56 @@ not retried. Writes made by a trigger run triggers again, and Cogover ends such
|
|
|
189
189
|
chains after a bounded number of automated writes. The complete contract is included
|
|
190
190
|
in `docs/en/api-reference.md`.
|
|
191
191
|
|
|
192
|
+
## Background jobs
|
|
193
|
+
|
|
194
|
+
A background job runs project code outside an HTTP request, with a time budget of
|
|
195
|
+
up to 60 seconds per attempt. Declare jobs with `defineJob` and list them in the
|
|
196
|
+
named `jobs` export. Enqueue a run from a route, a trigger, or another job with
|
|
197
|
+
`jobs.enqueue`, or give the job a cron `schedule`.
|
|
198
|
+
|
|
199
|
+
```typescript
|
|
200
|
+
import { defineJob } from "@cogover/sdk";
|
|
201
|
+
|
|
202
|
+
interface RecalcPayload { cursor?: string }
|
|
203
|
+
|
|
204
|
+
export const jobs = [
|
|
205
|
+
// Processes one page per run and enqueues itself again with the next cursor.
|
|
206
|
+
defineJob<RecalcPayload>({ key: "recalc_totals", timeoutMs: 60_000 }, async ({ payload, data, jobs }) => {
|
|
207
|
+
const orders = data.object("order");
|
|
208
|
+
const page = await orders.records.list({
|
|
209
|
+
fields: ["subtotal", "tax"],
|
|
210
|
+
limit: 200,
|
|
211
|
+
...(payload?.cursor ? { cursor: payload.cursor } : {}),
|
|
212
|
+
});
|
|
213
|
+
for (const order of page.items) {
|
|
214
|
+
await orders.records.update(order.id, {
|
|
215
|
+
total: (order.fields.subtotal ?? 0) + (order.fields.tax ?? 0),
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
if (page.nextCursor) await jobs.enqueue("recalc_totals", { cursor: page.nextCursor });
|
|
219
|
+
}),
|
|
220
|
+
|
|
221
|
+
// Runs every day at 02:00 in the given time zone.
|
|
222
|
+
defineJob({
|
|
223
|
+
key: "cancel_stale_orders",
|
|
224
|
+
schedule: { cron: "0 2 * * *", timezone: "Asia/Ho_Chi_Minh" },
|
|
225
|
+
}, async ({ data }) => {
|
|
226
|
+
const orders = data.object("order");
|
|
227
|
+
const stale = await orders.records.list({ where: orders.fields.status.eq("new"), fields: ["status"] });
|
|
228
|
+
for (const order of stale.items) await orders.records.update(order.id, { status: "cancelled" });
|
|
229
|
+
}),
|
|
230
|
+
];
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
A job handler receives `job` (run ID, key, attempt, source), the `payload` passed
|
|
234
|
+
to `enqueue` or `null`, and the same `data`, `schema`, `log`, `state`, `locks`,
|
|
235
|
+
`jobs`, `secrets`, and `crypto` APIs as a script. Runs are delivered at least once
|
|
236
|
+
and retried with growing delays when the handler throws `RetryableError` or times
|
|
237
|
+
out, up to `maxAttempts` (default 5) attempts; other errors fail the run. A run
|
|
238
|
+
enqueued from a route acts as that route's user, while a scheduled run uses the
|
|
239
|
+
system identity. `jobs.enqueue(key, payload?, { delayMs?, runAt?, idempotencyKey? })`
|
|
240
|
+
returns `{ runId, duplicate }`.
|
|
241
|
+
|
|
192
242
|
## Outbound HTTP with `fetch`
|
|
193
243
|
|
|
194
244
|
Cogover provides a Fetch-compatible function for calling an external HTTPS API.
|
|
@@ -224,6 +274,52 @@ dispatcher, agent, DNS, and TLS settings are not supported. A failed mutating re
|
|
|
224
274
|
may already have reached the remote API, so use the remote API's idempotency mechanism
|
|
225
275
|
and do not retry blindly.
|
|
226
276
|
|
|
277
|
+
## Secrets and credentials
|
|
278
|
+
|
|
279
|
+
An administrator stores secrets for the project; values are never returned by an
|
|
280
|
+
API or written to a log. A **credential** is used by `fetch` through the
|
|
281
|
+
`credential` option: Cogover adds the authentication header, restricts the
|
|
282
|
+
credential to its allowed hosts, and the code never sees the value. A **secret**
|
|
283
|
+
is read with `secrets.get` when the value itself is needed.
|
|
284
|
+
|
|
285
|
+
```typescript
|
|
286
|
+
export default defineScript(async ({ secrets, crypto }) => {
|
|
287
|
+
const response = await fetch("https://erp.example.com/v1/orders", { credential: "erp_api" });
|
|
288
|
+
const apiKey = await secrets.get("partner_api_key");
|
|
289
|
+
const signature = await crypto.hmacSha256({ secret: "partner_signing_key" }, await response.text());
|
|
290
|
+
return { apiKeyLength: apiKey.length, signature };
|
|
291
|
+
});
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
## Webhooks and cryptography
|
|
295
|
+
|
|
296
|
+
An administrator can create an **inbound access** so that an external system calls a
|
|
297
|
+
route at `https://{WORKSPACE_DOMAIN}/api/v1/ts-projects/{projectSlug}/hooks/{inboundId}/{route}`
|
|
298
|
+
with an inbound key or an HMAC signature, without a Cogover user session. Cogover
|
|
299
|
+
verifies the call before the module runs; the route sees `request.path` as
|
|
300
|
+
`/hooks/{route}`, `invocation.identity === "inbound"`, the raw body in
|
|
301
|
+
`request.rawBody`, and its content type in `request.contentType`.
|
|
302
|
+
|
|
303
|
+
```typescript
|
|
304
|
+
import { createRouter } from "@cogover/sdk";
|
|
305
|
+
|
|
306
|
+
const router = createRouter();
|
|
307
|
+
router.post("/hooks/payments", async ({ request, crypto, jobs, response }) => {
|
|
308
|
+
const expected = await crypto.hmacSha256({ secret: "payment_signing_secret" }, request.rawBody ?? "");
|
|
309
|
+
if (!crypto.timingSafeEqual(expected, request.headers["x-payment-signature"] ?? "")) {
|
|
310
|
+
return response.empty({ status: 401 });
|
|
311
|
+
}
|
|
312
|
+
const event = request.body as { id: string };
|
|
313
|
+
await jobs.enqueue("sync_payment", event, { idempotencyKey: `payment:${event.id}` });
|
|
314
|
+
return response.json({ received: true }, { status: 202 });
|
|
315
|
+
});
|
|
316
|
+
export default router.toHandler();
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
`crypto` — also importable from `@cogover/sdk` — provides `sha256`, `hmacSha256`
|
|
320
|
+
(with a string, byte, or `{ secret }` key), `randomBytes`, `randomUUID`, and the
|
|
321
|
+
constant-time `timingSafeEqual`.
|
|
322
|
+
|
|
227
323
|
## Record API
|
|
228
324
|
|
|
229
325
|
An Object client exposes `records.get`, `records.getMany`, `records.list`,
|
package/dist/crypto.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Hashing, message authentication and randomness provided by Cogover. */
|
|
2
|
+
export interface CryptoApi {
|
|
3
|
+
/** SHA-256 digest of a string (encoded as UTF-8) or of bytes; `encoding` defaults to `"hex"`. */
|
|
4
|
+
sha256(data: string | Uint8Array, encoding?: "hex" | "base64"): Promise<string>;
|
|
5
|
+
/**
|
|
6
|
+
* HMAC-SHA256 of `data`. The key is a string (UTF-8), bytes, or `{ secret: name }` to use a project
|
|
7
|
+
* secret without reading its value; `encoding` defaults to `"hex"`.
|
|
8
|
+
*/
|
|
9
|
+
hmacSha256(key: string | Uint8Array | {
|
|
10
|
+
readonly secret: string;
|
|
11
|
+
}, data: string | Uint8Array, encoding?: "hex" | "base64"): Promise<string>;
|
|
12
|
+
/** Cryptographically secure random bytes; `length` is 1 through 1024. */
|
|
13
|
+
randomBytes(length: number): Promise<Uint8Array>;
|
|
14
|
+
/** A random version 4 UUID in its canonical lower-case form. */
|
|
15
|
+
randomUUID(): Promise<string>;
|
|
16
|
+
/** Compares two values in constant time; strings are compared as UTF-8 bytes. */
|
|
17
|
+
timingSafeEqual(a: string | Uint8Array, b: string | Uint8Array): boolean;
|
|
18
|
+
}
|
|
19
|
+
/** Cryptographic helpers backed by Cogover's managed implementation. */
|
|
20
|
+
export declare const crypto: CryptoApi;
|
package/dist/crypto.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { CogoverApiError, ValidationError } from "./errors.js";
|
|
2
|
+
import { decodeBase64, encodeBase64 } from "./internal/base64.js";
|
|
3
|
+
import { callBridge } from "./internal/bridge.js";
|
|
4
|
+
import { encodeUtf8, utf8ByteLength } from "./internal/utf8.js";
|
|
5
|
+
import { requireSecretName } from "./internal/validation.js";
|
|
6
|
+
import { isRecord } from "./internal/values.js";
|
|
7
|
+
const MAX_DATA_BYTES = 256 * 1024;
|
|
8
|
+
const MAX_RANDOM_BYTES = 1024;
|
|
9
|
+
const ENCODINGS = new Set(["hex", "base64"]);
|
|
10
|
+
/** Cryptographic helpers backed by Cogover's managed implementation. */
|
|
11
|
+
export const crypto = Object.freeze({
|
|
12
|
+
async sha256(data, encoding = "hex") {
|
|
13
|
+
const { data: text, dataEncoding } = bridgeData(data, "sha256() data");
|
|
14
|
+
return digest(await callBridge("crypto.hash", {
|
|
15
|
+
algorithm: "SHA-256",
|
|
16
|
+
data: text,
|
|
17
|
+
dataEncoding,
|
|
18
|
+
encoding: digestEncoding(encoding, "sha256()"),
|
|
19
|
+
}));
|
|
20
|
+
},
|
|
21
|
+
async hmacSha256(key, data, encoding = "hex") {
|
|
22
|
+
const keyPayload = hmacKey(key);
|
|
23
|
+
const { data: text, dataEncoding } = bridgeData(data, "hmacSha256() data");
|
|
24
|
+
return digest(await callBridge("crypto.hmac", {
|
|
25
|
+
algorithm: "SHA-256",
|
|
26
|
+
key: keyPayload,
|
|
27
|
+
data: text,
|
|
28
|
+
dataEncoding,
|
|
29
|
+
encoding: digestEncoding(encoding, "hmacSha256()"),
|
|
30
|
+
}));
|
|
31
|
+
},
|
|
32
|
+
async randomBytes(length) {
|
|
33
|
+
if (!Number.isInteger(length) || length < 1 || length > MAX_RANDOM_BYTES) {
|
|
34
|
+
throw new ValidationError(`randomBytes() length must be an integer between 1 and ${MAX_RANDOM_BYTES}`);
|
|
35
|
+
}
|
|
36
|
+
const random = await callBridge("crypto.random", { bytes: length });
|
|
37
|
+
const bytes = isRecord(random) && typeof random.base64 === "string" ? decodeBase64(random.base64) : null;
|
|
38
|
+
if (bytes === null || bytes.length !== length) {
|
|
39
|
+
throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Random bytes are invalid");
|
|
40
|
+
}
|
|
41
|
+
return bytes;
|
|
42
|
+
},
|
|
43
|
+
async randomUUID() {
|
|
44
|
+
const bytes = await crypto.randomBytes(16);
|
|
45
|
+
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40; // version 4
|
|
46
|
+
bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80; // RFC 4122 variant
|
|
47
|
+
const hex = toHex(bytes);
|
|
48
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
49
|
+
},
|
|
50
|
+
timingSafeEqual(a, b) {
|
|
51
|
+
const left = toBytes(a, "timingSafeEqual() first value");
|
|
52
|
+
const right = toBytes(b, "timingSafeEqual() second value");
|
|
53
|
+
// Every byte of the longer value is visited, so the time depends only on the lengths, never on
|
|
54
|
+
// where the first difference is.
|
|
55
|
+
let mismatch = left.length ^ right.length;
|
|
56
|
+
const length = Math.max(left.length, right.length);
|
|
57
|
+
for (let index = 0; index < length; index++) {
|
|
58
|
+
mismatch |= (left[index] ?? 0) ^ (right[index] ?? 0);
|
|
59
|
+
}
|
|
60
|
+
return mismatch === 0;
|
|
61
|
+
},
|
|
62
|
+
});
|
|
63
|
+
function bridgeData(data, label) {
|
|
64
|
+
if (typeof data === "string") {
|
|
65
|
+
if (utf8ByteLength(data) > MAX_DATA_BYTES)
|
|
66
|
+
throw tooLarge(label);
|
|
67
|
+
return { data, dataEncoding: "utf8" };
|
|
68
|
+
}
|
|
69
|
+
if (data instanceof Uint8Array) {
|
|
70
|
+
if (data.length > MAX_DATA_BYTES)
|
|
71
|
+
throw tooLarge(label);
|
|
72
|
+
return { data: encodeBase64(data), dataEncoding: "base64" };
|
|
73
|
+
}
|
|
74
|
+
throw new ValidationError(`${label} must be a string or a Uint8Array`);
|
|
75
|
+
}
|
|
76
|
+
function hmacKey(key) {
|
|
77
|
+
if (typeof key === "string") {
|
|
78
|
+
if (key.length === 0)
|
|
79
|
+
throw new ValidationError("hmacSha256() key must not be empty");
|
|
80
|
+
if (utf8ByteLength(key) > MAX_DATA_BYTES)
|
|
81
|
+
throw tooLarge("hmacSha256() key");
|
|
82
|
+
return { value: key, encoding: "utf8" };
|
|
83
|
+
}
|
|
84
|
+
if (key instanceof Uint8Array) {
|
|
85
|
+
if (key.length === 0)
|
|
86
|
+
throw new ValidationError("hmacSha256() key must not be empty");
|
|
87
|
+
if (key.length > MAX_DATA_BYTES)
|
|
88
|
+
throw tooLarge("hmacSha256() key");
|
|
89
|
+
return { value: encodeBase64(key), encoding: "base64" };
|
|
90
|
+
}
|
|
91
|
+
if (isRecord(key) && Object.keys(key).length === 1 && "secret" in key) {
|
|
92
|
+
return { secret: requireSecretName(key.secret, "hmacSha256() key.secret") };
|
|
93
|
+
}
|
|
94
|
+
throw new ValidationError("hmacSha256() key must be a string, a Uint8Array or { secret: name }");
|
|
95
|
+
}
|
|
96
|
+
function digestEncoding(encoding, label) {
|
|
97
|
+
if (typeof encoding !== "string" || !ENCODINGS.has(encoding)) {
|
|
98
|
+
throw new ValidationError(`${label} encoding must be "hex" or "base64"`);
|
|
99
|
+
}
|
|
100
|
+
return encoding;
|
|
101
|
+
}
|
|
102
|
+
function digest(payload) {
|
|
103
|
+
if (!isRecord(payload) || typeof payload.digest !== "string" || payload.digest.length === 0) {
|
|
104
|
+
throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Digest is invalid");
|
|
105
|
+
}
|
|
106
|
+
return payload.digest;
|
|
107
|
+
}
|
|
108
|
+
function toBytes(value, label) {
|
|
109
|
+
if (typeof value === "string")
|
|
110
|
+
return encodeUtf8(value);
|
|
111
|
+
if (value instanceof Uint8Array)
|
|
112
|
+
return value;
|
|
113
|
+
throw new ValidationError(`${label} must be a string or a Uint8Array`);
|
|
114
|
+
}
|
|
115
|
+
function toHex(bytes) {
|
|
116
|
+
let hex = "";
|
|
117
|
+
for (const byte of bytes)
|
|
118
|
+
hex += (byte < 16 ? "0" : "") + byte.toString(16);
|
|
119
|
+
return hex;
|
|
120
|
+
}
|
|
121
|
+
function tooLarge(label) {
|
|
122
|
+
return new ValidationError(`${label} must not exceed ${MAX_DATA_BYTES} bytes`);
|
|
123
|
+
}
|
package/dist/errors.d.ts
CHANGED
|
@@ -20,8 +20,8 @@ export declare class RateLimitError extends CogoverApiError {
|
|
|
20
20
|
constructor(message: string, details?: unknown);
|
|
21
21
|
}
|
|
22
22
|
/**
|
|
23
|
-
* Thrown by an after-change trigger handler to report a temporary failure. Cogover runs
|
|
24
|
-
* later. Anywhere else it is an ordinary failure.
|
|
23
|
+
* Thrown by an after-change trigger handler or a job handler to report a temporary failure. Cogover runs
|
|
24
|
+
* the handler again later. Anywhere else it is an ordinary failure.
|
|
25
25
|
*/
|
|
26
26
|
export declare class RetryableError extends CogoverApiError {
|
|
27
27
|
constructor(message: string, details?: unknown);
|
package/dist/errors.js
CHANGED
|
@@ -43,8 +43,8 @@ export class RateLimitError extends CogoverApiError {
|
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
45
|
/**
|
|
46
|
-
* Thrown by an after-change trigger handler to report a temporary failure. Cogover runs
|
|
47
|
-
* later. Anywhere else it is an ordinary failure.
|
|
46
|
+
* Thrown by an after-change trigger handler or a job handler to report a temporary failure. Cogover runs
|
|
47
|
+
* the handler again later. Anywhere else it is an ordinary failure.
|
|
48
48
|
*/
|
|
49
49
|
export class RetryableError extends CogoverApiError {
|
|
50
50
|
constructor(message, details) {
|
package/dist/fetch.d.ts
CHANGED
|
@@ -3,6 +3,8 @@ export interface CogoverFetchInit {
|
|
|
3
3
|
readonly headers?: Readonly<Record<string, string>>;
|
|
4
4
|
readonly body?: string;
|
|
5
5
|
readonly timeoutMs?: number;
|
|
6
|
+
/** Name of a project credential; Cogover adds its authentication header to the request. */
|
|
7
|
+
readonly credential?: string;
|
|
6
8
|
}
|
|
7
9
|
export interface CogoverFetchHeaders {
|
|
8
10
|
get(name: string): string | null;
|
package/dist/fetch.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { ValidationError } from "./errors.js";
|
|
2
2
|
import { callBridge } from "./internal/bridge.js";
|
|
3
|
+
import { requireSecretName } from "./internal/validation.js";
|
|
3
4
|
const METHODS = new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]);
|
|
4
|
-
const OPTION_KEYS = new Set(["method", "headers", "body", "timeoutMs"]);
|
|
5
|
+
const OPTION_KEYS = new Set(["method", "headers", "body", "timeoutMs", "credential"]);
|
|
5
6
|
/** Fetch-compatible API using Cogover's managed network layer. */
|
|
6
7
|
export async function fetch(input, init) {
|
|
7
8
|
if (typeof input !== "string" || input.length === 0) {
|
|
@@ -30,6 +31,8 @@ export async function fetch(input, init) {
|
|
|
30
31
|
&& (init.headers === null || typeof init.headers !== "object" || Array.isArray(init.headers))) {
|
|
31
32
|
throw new ValidationError("fetch() headers must be an object");
|
|
32
33
|
}
|
|
34
|
+
if (init?.credential !== undefined)
|
|
35
|
+
requireSecretName(init.credential, "fetch() credential");
|
|
33
36
|
const payload = { url: input, method };
|
|
34
37
|
if (init?.headers !== undefined)
|
|
35
38
|
payload.headers = init.headers;
|
|
@@ -37,6 +40,8 @@ export async function fetch(input, init) {
|
|
|
37
40
|
payload.body = init.body;
|
|
38
41
|
if (init?.timeoutMs !== undefined)
|
|
39
42
|
payload.timeoutMs = init.timeoutMs;
|
|
43
|
+
if (init?.credential !== undefined)
|
|
44
|
+
payload.credential = init.credential;
|
|
40
45
|
const response = await callBridge("http.fetch", payload);
|
|
41
46
|
return createFetchResponse(response);
|
|
42
47
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -10,7 +10,12 @@ export { defineScript } from "./script.js";
|
|
|
10
10
|
export type { ScriptContext, ScriptHandler, SandboxHandler } from "./script.js";
|
|
11
11
|
export { defineTrigger } from "./trigger.js";
|
|
12
12
|
export type { TriggerTiming, TriggerOperation, TriggerRunWhen, TriggerFilterCondition, TriggerFilterGroup, TriggerFilter, TriggerConfig, TriggerManifest, TriggerSandboxHandler, TriggerDefinition, TriggerInfo, TriggerNewValues, TriggerOldValues, TriggerRecord, TriggerContext, TriggerHandler, } from "./trigger.js";
|
|
13
|
-
export
|
|
13
|
+
export { defineJob } from "./jobs.js";
|
|
14
|
+
export type { JobSchedule, JobConfig, JobManifest, JobDefinition, JobInfo, EnqueueOptions, EnqueueResult, JobsApi, JobContext, JobHandler, } from "./jobs.js";
|
|
15
|
+
export type { SecretsApi } from "./secrets.js";
|
|
16
|
+
export { crypto } from "./crypto.js";
|
|
17
|
+
export type { CryptoApi } from "./crypto.js";
|
|
18
|
+
export type { CurrentWorkspace, CurrentWorkspaceMembership, CurrentUser, UserInvocationContext, SystemInvocationContext, InboundInvocationContext, InvocationContext, } from "./invocation.js";
|
|
14
19
|
export { createRouter } from "./router.js";
|
|
15
20
|
export type { ScriptRouter } from "./router.js";
|
|
16
21
|
export type { RequestMethod, ScriptRequest, ScriptQuery, ScriptHeaders, ScriptPathParams, } from "./request.js";
|
package/dist/index.js
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
export { and, or } from "./query.js";
|
|
3
3
|
export { defineScript } from "./script.js";
|
|
4
4
|
export { defineTrigger } from "./trigger.js";
|
|
5
|
+
export { defineJob } from "./jobs.js";
|
|
6
|
+
export { crypto } from "./crypto.js";
|
|
5
7
|
export { createRouter } from "./router.js";
|
|
6
8
|
export { fetch } from "./fetch.js";
|
|
7
9
|
export { CogoverApiError, NotFoundError, ValidationError, PermissionDeniedError, RateLimitError, RetryableError, StateConflictError, LockUnavailableError, LockLostError, } from "./errors.js";
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
2
|
+
const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
|
3
|
+
// Sandboxed code has neither Buffer nor atob/btoa, so binary data crosses the bridge through these helpers.
|
|
4
|
+
/** Standard base64 with padding (RFC 4648 section 4). */
|
|
5
|
+
export function encodeBase64(bytes) {
|
|
6
|
+
let result = "";
|
|
7
|
+
for (let index = 0; index < bytes.length; index += 3) {
|
|
8
|
+
const first = bytes[index] ?? 0;
|
|
9
|
+
const second = bytes[index + 1] ?? 0;
|
|
10
|
+
const third = bytes[index + 2] ?? 0;
|
|
11
|
+
const value = (first << 16) | (second << 8) | third;
|
|
12
|
+
result += ALPHABET.charAt((value >>> 18) & 63)
|
|
13
|
+
+ ALPHABET.charAt((value >>> 12) & 63)
|
|
14
|
+
+ (index + 1 < bytes.length ? ALPHABET.charAt((value >>> 6) & 63) : "=")
|
|
15
|
+
+ (index + 2 < bytes.length ? ALPHABET.charAt(value & 63) : "=");
|
|
16
|
+
}
|
|
17
|
+
return result;
|
|
18
|
+
}
|
|
19
|
+
/** Decodes padded standard base64; returns null for text that is not canonical base64. */
|
|
20
|
+
export function decodeBase64(text) {
|
|
21
|
+
if (typeof text !== "string" || !BASE64.test(text))
|
|
22
|
+
return null;
|
|
23
|
+
const padding = text.endsWith("==") ? 2 : text.endsWith("=") ? 1 : 0;
|
|
24
|
+
const bytes = new Uint8Array((text.length / 4) * 3 - padding);
|
|
25
|
+
let position = 0;
|
|
26
|
+
for (let index = 0; index < text.length; index += 4) {
|
|
27
|
+
const value = (digit(text, index) << 18) | (digit(text, index + 1) << 12)
|
|
28
|
+
| (digit(text, index + 2) << 6) | digit(text, index + 3);
|
|
29
|
+
if (position < bytes.length)
|
|
30
|
+
bytes[position++] = (value >>> 16) & 255;
|
|
31
|
+
if (position < bytes.length)
|
|
32
|
+
bytes[position++] = (value >>> 8) & 255;
|
|
33
|
+
if (position < bytes.length)
|
|
34
|
+
bytes[position++] = value & 255;
|
|
35
|
+
}
|
|
36
|
+
return bytes;
|
|
37
|
+
}
|
|
38
|
+
function digit(text, index) {
|
|
39
|
+
const character = text.charAt(index);
|
|
40
|
+
return character === "=" ? 0 : ALPHABET.indexOf(character);
|
|
41
|
+
}
|
|
@@ -8,6 +8,9 @@ export function invocationContext(input) {
|
|
|
8
8
|
if (context.executionIdentity === "system") {
|
|
9
9
|
return Object.freeze({ identity: "system", workspace, user: null });
|
|
10
10
|
}
|
|
11
|
+
if (context.executionIdentity === "inbound") {
|
|
12
|
+
return Object.freeze({ identity: "inbound", workspace, user: null, inbound: inboundSnapshot(context.inbound) });
|
|
13
|
+
}
|
|
11
14
|
if (context.executionIdentity !== "user" || !isRecord(context.user)) {
|
|
12
15
|
throw new ValidationError("Invalid invocation identity metadata");
|
|
13
16
|
}
|
|
@@ -36,6 +39,18 @@ function userSnapshot(raw) {
|
|
|
36
39
|
membership,
|
|
37
40
|
});
|
|
38
41
|
}
|
|
42
|
+
function inboundSnapshot(raw) {
|
|
43
|
+
if (!isRecord(raw))
|
|
44
|
+
throw new ValidationError("Invalid invocation identity metadata");
|
|
45
|
+
const mode = raw.mode;
|
|
46
|
+
if (mode !== "KEY" && mode !== "HMAC")
|
|
47
|
+
throw new ValidationError("Invalid invocation inbound mode");
|
|
48
|
+
return Object.freeze({
|
|
49
|
+
id: requiredString(raw.id, "inbound id"),
|
|
50
|
+
name: requiredString(raw.name, "inbound name"),
|
|
51
|
+
mode,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
39
54
|
function requiredString(value, label) {
|
|
40
55
|
if (typeof value !== "string" || value === "") {
|
|
41
56
|
throw new ValidationError(`Invalid invocation ${label}`);
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { ValidationError } from "../errors.js";
|
|
2
|
+
import { deepFreeze } from "./json.js";
|
|
3
|
+
import { isRecord } from "./values.js";
|
|
4
|
+
export const JOB_KEY = /^[A-Za-z][A-Za-z0-9_]{0,99}$/;
|
|
5
|
+
const CONFIG_KEYS = new Set(["key", "name", "timeoutMs", "maxAttempts", "schedule"]);
|
|
6
|
+
const SCHEDULE_KEYS = new Set(["cron", "timezone"]);
|
|
7
|
+
const MAX_NAME_LENGTH = 250;
|
|
8
|
+
const MIN_TIMEOUT_MILLIS = 1000;
|
|
9
|
+
const MAX_TIMEOUT_MILLIS = 60_000;
|
|
10
|
+
const DEFAULT_TIMEOUT_MILLIS = 30_000;
|
|
11
|
+
const MIN_ATTEMPTS = 1;
|
|
12
|
+
const MAX_ATTEMPTS = 10;
|
|
13
|
+
const DEFAULT_ATTEMPTS = 5;
|
|
14
|
+
const MAX_TIMEZONE_LENGTH = 64;
|
|
15
|
+
const DEFAULT_TIMEZONE = "UTC";
|
|
16
|
+
// The shape of an IANA zone ID; Cogover checks that the zone exists when the version is published.
|
|
17
|
+
const TIMEZONE = /^[A-Za-z][A-Za-z0-9_+-]*(?:\/[A-Za-z0-9_+-]+)*$/;
|
|
18
|
+
const CRON_FIELDS = [
|
|
19
|
+
{ name: "minute", minimum: 0, maximum: 59 },
|
|
20
|
+
{ name: "hour", minimum: 0, maximum: 23 },
|
|
21
|
+
{ name: "day-of-month", minimum: 1, maximum: 31 },
|
|
22
|
+
{ name: "month", minimum: 1, maximum: 12 },
|
|
23
|
+
{ name: "day-of-week", minimum: 0, maximum: 7 },
|
|
24
|
+
];
|
|
25
|
+
/** Validates a defineJob() config and returns the frozen plain-JSON manifest with defaults applied. */
|
|
26
|
+
export function normalizeJobConfig(config) {
|
|
27
|
+
if (!isRecord(config)) {
|
|
28
|
+
throw new ValidationError("defineJob() requires a configuration object");
|
|
29
|
+
}
|
|
30
|
+
const key = config.key;
|
|
31
|
+
if (typeof key !== "string" || !JOB_KEY.test(key)) {
|
|
32
|
+
throw new ValidationError("Job key must start with a letter and contain at most 100 letters, digits or underscores");
|
|
33
|
+
}
|
|
34
|
+
const fail = (option, message) => new ValidationError(`Job '${key}': ${message}`, { jobKey: key, option });
|
|
35
|
+
for (const option of Object.keys(config)) {
|
|
36
|
+
if (!CONFIG_KEYS.has(option))
|
|
37
|
+
throw fail(option, `unknown config key '${option}'`);
|
|
38
|
+
}
|
|
39
|
+
let name;
|
|
40
|
+
if (config.name !== undefined) {
|
|
41
|
+
name = typeof config.name === "string" ? config.name.trim() : "";
|
|
42
|
+
if (name.length === 0 || name.length > MAX_NAME_LENGTH) {
|
|
43
|
+
throw fail("name", `name must be a non-empty string of at most ${MAX_NAME_LENGTH} characters`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const timeoutMs = integerOption(config.timeoutMs, "timeoutMs", MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS, DEFAULT_TIMEOUT_MILLIS, fail);
|
|
47
|
+
const maxAttempts = integerOption(config.maxAttempts, "maxAttempts", MIN_ATTEMPTS, MAX_ATTEMPTS, DEFAULT_ATTEMPTS, fail);
|
|
48
|
+
let schedule;
|
|
49
|
+
if (config.schedule !== undefined) {
|
|
50
|
+
schedule = normalizeSchedule(config.schedule, fail);
|
|
51
|
+
}
|
|
52
|
+
// Key order follows the manifest contract; absent optional keys are omitted, never undefined.
|
|
53
|
+
const manifest = {
|
|
54
|
+
key,
|
|
55
|
+
...(name === undefined ? {} : { name }),
|
|
56
|
+
timeoutMs,
|
|
57
|
+
maxAttempts,
|
|
58
|
+
...(schedule === undefined ? {} : { schedule }),
|
|
59
|
+
};
|
|
60
|
+
return deepFreeze(manifest);
|
|
61
|
+
}
|
|
62
|
+
function normalizeSchedule(value, fail) {
|
|
63
|
+
if (!isRecord(value)) {
|
|
64
|
+
throw fail("schedule", "schedule must be an object such as { cron: \"0 2 * * *\", timezone: \"UTC\" }");
|
|
65
|
+
}
|
|
66
|
+
for (const option of Object.keys(value)) {
|
|
67
|
+
if (!SCHEDULE_KEYS.has(option))
|
|
68
|
+
throw fail("schedule", `schedule contains the unknown key '${option}'`);
|
|
69
|
+
}
|
|
70
|
+
const cron = normalizeCron(value.cron, fail);
|
|
71
|
+
let timezone = DEFAULT_TIMEZONE;
|
|
72
|
+
if (value.timezone !== undefined) {
|
|
73
|
+
if (typeof value.timezone !== "string" || value.timezone.length === 0
|
|
74
|
+
|| value.timezone.length > MAX_TIMEZONE_LENGTH || !TIMEZONE.test(value.timezone)) {
|
|
75
|
+
throw fail("schedule", "schedule.timezone must be an IANA time zone ID of at most "
|
|
76
|
+
+ `${MAX_TIMEZONE_LENGTH} characters, for example "Asia/Ho_Chi_Minh"`);
|
|
77
|
+
}
|
|
78
|
+
timezone = value.timezone;
|
|
79
|
+
}
|
|
80
|
+
return { cron, timezone };
|
|
81
|
+
}
|
|
82
|
+
/** Validates a five-field cron expression and returns it with single spaces between the fields. */
|
|
83
|
+
function normalizeCron(expression, fail) {
|
|
84
|
+
if (typeof expression !== "string" || expression.trim().length === 0) {
|
|
85
|
+
throw fail("schedule", "schedule.cron must be a string of five fields: "
|
|
86
|
+
+ "minute hour day-of-month month day-of-week");
|
|
87
|
+
}
|
|
88
|
+
const trimmed = expression.trim();
|
|
89
|
+
if (trimmed.startsWith("@")) {
|
|
90
|
+
throw fail("schedule", `schedule.cron does not support the macro '${trimmed}'; use five fields`);
|
|
91
|
+
}
|
|
92
|
+
const fields = trimmed.split(/\s+/u);
|
|
93
|
+
if (fields.length !== 5) {
|
|
94
|
+
throw fail("schedule", `schedule.cron must contain exactly five fields, found ${fields.length}`);
|
|
95
|
+
}
|
|
96
|
+
fields.forEach((field, index) => validateCronField(field, CRON_FIELDS[index], fail));
|
|
97
|
+
return fields.join(" ");
|
|
98
|
+
}
|
|
99
|
+
function validateCronField(field, spec, fail) {
|
|
100
|
+
const unsupported = (item) => fail("schedule", `schedule.cron ${spec.name} field contains the unsupported value '${item}'; `
|
|
101
|
+
+ `use *, a, a-b, */n or a-b/n with numbers from ${spec.minimum} to ${spec.maximum}`);
|
|
102
|
+
for (const item of field.split(",")) {
|
|
103
|
+
const parts = item.split("/");
|
|
104
|
+
const range = parts[0] ?? "";
|
|
105
|
+
const step = parts[1];
|
|
106
|
+
if (parts.length > 2 || range === "" || step === "")
|
|
107
|
+
throw unsupported(item);
|
|
108
|
+
if (step !== undefined) {
|
|
109
|
+
const stepValue = cronNumber(step);
|
|
110
|
+
if (stepValue === null || stepValue < 1 || stepValue > spec.maximum) {
|
|
111
|
+
throw fail("schedule", `schedule.cron ${spec.name} field has the invalid step '${item}'; `
|
|
112
|
+
+ `the step must be a number from 1 to ${spec.maximum}`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if (range === "*")
|
|
116
|
+
continue;
|
|
117
|
+
const bounds = range.split("-");
|
|
118
|
+
if (bounds.length > 2)
|
|
119
|
+
throw unsupported(item);
|
|
120
|
+
if (step !== undefined && bounds.length !== 2) {
|
|
121
|
+
throw fail("schedule", `schedule.cron ${spec.name} field has the invalid step '${item}'; `
|
|
122
|
+
+ "a step applies to * or to a range a-b");
|
|
123
|
+
}
|
|
124
|
+
const values = bounds.map(cronNumber);
|
|
125
|
+
if (values.some(value => value === null || value < spec.minimum || value > spec.maximum)) {
|
|
126
|
+
throw unsupported(item);
|
|
127
|
+
}
|
|
128
|
+
if (values.length === 2 && values[0] > values[1]) {
|
|
129
|
+
throw fail("schedule", `schedule.cron ${spec.name} field has the range '${item}' whose start is after its end`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function cronNumber(text) {
|
|
134
|
+
return /^\d{1,2}$/u.test(text) ? Number(text) : null;
|
|
135
|
+
}
|
|
136
|
+
function integerOption(value, option, minimum, maximum, fallback, fail) {
|
|
137
|
+
if (value === undefined)
|
|
138
|
+
return fallback;
|
|
139
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < minimum || value > maximum) {
|
|
140
|
+
throw fail(option, `${option} must be an integer between ${minimum} and ${maximum}`);
|
|
141
|
+
}
|
|
142
|
+
return value;
|
|
143
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { crypto } from "../crypto.js";
|
|
2
|
+
import { createDataApi } from "../data.js";
|
|
3
|
+
import { ValidationError } from "../errors.js";
|
|
4
|
+
import { installCogoverFetch } from "../fetch.js";
|
|
5
|
+
import { createLocksApi } from "../locks.js";
|
|
6
|
+
import { SCRIPT_LOGGER } from "../logger.js";
|
|
7
|
+
import { createSchemaApi } from "../schema.js";
|
|
8
|
+
import { createSecretsApi } from "../secrets.js";
|
|
9
|
+
import { createStateApi } from "../state.js";
|
|
10
|
+
import { invocationContext } from "./invocation.js";
|
|
11
|
+
import { createJobsApi } from "./jobs-api.js";
|
|
12
|
+
import { errorMessage, isRecord } from "./values.js";
|
|
13
|
+
// Both spellings of a source are accepted; project code only ever sees the SDK literals.
|
|
14
|
+
const SOURCES = new Map([
|
|
15
|
+
["enqueue", "enqueue"],
|
|
16
|
+
["ENQUEUE", "enqueue"],
|
|
17
|
+
["schedule", "schedule"],
|
|
18
|
+
["SCHEDULE", "schedule"],
|
|
19
|
+
]);
|
|
20
|
+
export function createJobSandboxHandler(manifest, handler) {
|
|
21
|
+
return async (inputJson) => {
|
|
22
|
+
installCogoverFetch();
|
|
23
|
+
let input;
|
|
24
|
+
try {
|
|
25
|
+
input = JSON.parse(inputJson);
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
throw new ValidationError("Job input must be valid JSON", errorMessage(error));
|
|
29
|
+
}
|
|
30
|
+
if (!isRecord(input))
|
|
31
|
+
throw new ValidationError("Job input must be a JSON object");
|
|
32
|
+
const job = jobInfo(input, manifest);
|
|
33
|
+
let invocation;
|
|
34
|
+
await handler(Object.freeze({
|
|
35
|
+
job,
|
|
36
|
+
payload: input.payload ?? null,
|
|
37
|
+
get invocation() {
|
|
38
|
+
return invocation ??= invocationContext(input);
|
|
39
|
+
},
|
|
40
|
+
data: createDataApi(),
|
|
41
|
+
schema: createSchemaApi(),
|
|
42
|
+
log: SCRIPT_LOGGER,
|
|
43
|
+
state: createStateApi(),
|
|
44
|
+
locks: createLocksApi(),
|
|
45
|
+
jobs: createJobsApi(),
|
|
46
|
+
secrets: createSecretsApi(),
|
|
47
|
+
crypto,
|
|
48
|
+
}));
|
|
49
|
+
// The result of a job is not delivered anywhere, so nothing is serialized.
|
|
50
|
+
return null;
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
function jobInfo(input, manifest) {
|
|
54
|
+
const context = isRecord(input.__context) ? input.__context : undefined;
|
|
55
|
+
const raw = context !== undefined && isRecord(context.job) ? context.job : undefined;
|
|
56
|
+
if (raw === undefined) {
|
|
57
|
+
throw new ValidationError("Job metadata is unavailable outside Cogover Runtime");
|
|
58
|
+
}
|
|
59
|
+
const source = SOURCES.get(raw.source);
|
|
60
|
+
if (source === undefined)
|
|
61
|
+
throw new ValidationError("Invalid job source metadata");
|
|
62
|
+
const info = Object.freeze({
|
|
63
|
+
id: requiredString(raw.id, "id"),
|
|
64
|
+
key: requiredString(raw.key, "key"),
|
|
65
|
+
attempt: requiredInteger(raw.attempt, "attempt", 1),
|
|
66
|
+
maxAttempts: requiredInteger(raw.maxAttempts, "maxAttempts", 1),
|
|
67
|
+
source,
|
|
68
|
+
runAt: requiredInteger(raw.runAt, "runAt", 0),
|
|
69
|
+
...(raw.enqueuedAt === undefined || raw.enqueuedAt === null
|
|
70
|
+
? {}
|
|
71
|
+
: { enqueuedAt: requiredInteger(raw.enqueuedAt, "enqueuedAt", 0) }),
|
|
72
|
+
});
|
|
73
|
+
// A mismatch means the call was routed to a definition it was not registered for.
|
|
74
|
+
if (info.key !== manifest.key) {
|
|
75
|
+
throw new ValidationError(`Job input for '${info.key}' does not match the definition of '${manifest.key}'`);
|
|
76
|
+
}
|
|
77
|
+
return info;
|
|
78
|
+
}
|
|
79
|
+
function requiredString(value, name) {
|
|
80
|
+
if (typeof value !== "string" || value === "") {
|
|
81
|
+
throw new ValidationError(`Invalid job ${name} metadata`);
|
|
82
|
+
}
|
|
83
|
+
return value;
|
|
84
|
+
}
|
|
85
|
+
function requiredInteger(value, name, minimum) {
|
|
86
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < minimum) {
|
|
87
|
+
throw new ValidationError(`Invalid job ${name} metadata`);
|
|
88
|
+
}
|
|
89
|
+
return value;
|
|
90
|
+
}
|