@cogover/sdk 0.7.0 → 0.9.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 +110 -4
- package/dist/crypto.d.ts +133 -0
- package/dist/crypto.js +418 -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 +775 -27
- package/docs/en/usage-guide.md +253 -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,62 @@ 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`. It also encrypts and signs: `aesEncrypt` and
|
|
322
|
+
`aesDecrypt` (AES-GCM or AES-CBC), `rsaEncrypt` and `rsaDecrypt` (RSA-OAEP or
|
|
323
|
+
PKCS #1 v1.5), and `sign` and `verify` (RSA, RSA-PSS, and ECDSA, including the JWT
|
|
324
|
+
signature formats). Keys may be PEM text or `{ secret: name }`, so private keys stay
|
|
325
|
+
in project secrets.
|
|
326
|
+
|
|
327
|
+
```typescript
|
|
328
|
+
const sealed = await crypto.aesEncrypt({ secret: "partner_aes_key", encoding: "base64" }, JSON.stringify(order));
|
|
329
|
+
const signature = await crypto.sign("RSA-SHA256", { secret: "our_signing_key" }, JSON.stringify(sealed));
|
|
330
|
+
const valid = await crypto.verify("ECDSA-SHA256", { secret: "partner_public_key" }, body, signatureHeader);
|
|
331
|
+
```
|
|
332
|
+
|
|
227
333
|
## Record API
|
|
228
334
|
|
|
229
335
|
An Object client exposes `records.get`, `records.getMany`, `records.list`,
|
package/dist/crypto.d.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/** Text encoding of binary values such as ciphertexts, IVs, tags and signatures. */
|
|
2
|
+
export type BinaryEncoding = "base64" | "base64url" | "hex";
|
|
3
|
+
/**
|
|
4
|
+
* What a decryption returns: `"utf8"` decodes the plaintext as UTF-8 text, `"bytes"` returns a `Uint8Array`, and
|
|
5
|
+
* a {@link BinaryEncoding} returns the plaintext bytes in that encoding.
|
|
6
|
+
*/
|
|
7
|
+
export type DecryptOutput = "utf8" | "bytes" | BinaryEncoding;
|
|
8
|
+
/** A key stored as a project secret, used without reading its value. */
|
|
9
|
+
export interface SecretKeyReference {
|
|
10
|
+
readonly secret: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* An AES key: 16, 24 or 32 bytes given as a UTF-8 string, as bytes, or as a project secret. For a secret,
|
|
14
|
+
* `encoding` tells how its text encodes the key bytes and defaults to `"utf8"`.
|
|
15
|
+
*/
|
|
16
|
+
export type AesKey = string | Uint8Array | (SecretKeyReference & {
|
|
17
|
+
readonly encoding?: "utf8" | "base64" | "hex";
|
|
18
|
+
});
|
|
19
|
+
/**
|
|
20
|
+
* An RSA or EC key as PEM text or base64 DER, or a project secret holding one. Public keys may be
|
|
21
|
+
* SubjectPublicKeyInfo (`PUBLIC KEY`), PKCS #1 (`RSA PUBLIC KEY`) or an X.509 `CERTIFICATE`; private keys may be
|
|
22
|
+
* PKCS #8 (`PRIVATE KEY`), PKCS #1 (`RSA PRIVATE KEY`) or SEC1 (`EC PRIVATE KEY`).
|
|
23
|
+
*/
|
|
24
|
+
export type AsymmetricKey = string | SecretKeyReference;
|
|
25
|
+
/** AES block cipher mode. */
|
|
26
|
+
export type AesMode = "GCM" | "CBC";
|
|
27
|
+
/** Options of {@link CryptoApi.aesEncrypt}. */
|
|
28
|
+
export interface AesEncryptOptions {
|
|
29
|
+
/** `"GCM"` (default, authenticated) or `"CBC"` with PKCS #7 padding. */
|
|
30
|
+
readonly mode?: AesMode;
|
|
31
|
+
/** IV to use; a random one is generated when omitted. A string is decoded with `encoding`. */
|
|
32
|
+
readonly iv?: string | Uint8Array;
|
|
33
|
+
/** Additional authenticated data for GCM; a string is encoded as UTF-8. */
|
|
34
|
+
readonly aad?: string | Uint8Array;
|
|
35
|
+
/** GCM only: return the authentication tag in `tag` instead of appending it to `ciphertext`. */
|
|
36
|
+
readonly separateTag?: boolean;
|
|
37
|
+
/** Encoding of the result and of a string `iv`; defaults to `"base64"`. */
|
|
38
|
+
readonly encoding?: BinaryEncoding;
|
|
39
|
+
}
|
|
40
|
+
/** Result of {@link CryptoApi.aesEncrypt}, in the requested encoding. */
|
|
41
|
+
export interface AesEncryptResult {
|
|
42
|
+
/** The ciphertext; in GCM mode it ends with the 16-byte tag unless `separateTag` was set. */
|
|
43
|
+
readonly ciphertext: string;
|
|
44
|
+
readonly iv: string;
|
|
45
|
+
/** The GCM tag, present only when `separateTag` was set. */
|
|
46
|
+
readonly tag?: string;
|
|
47
|
+
}
|
|
48
|
+
/** Options of {@link CryptoApi.aesDecrypt}. */
|
|
49
|
+
export interface AesDecryptOptions {
|
|
50
|
+
/** `"GCM"` (default) or `"CBC"`. */
|
|
51
|
+
readonly mode?: AesMode;
|
|
52
|
+
/** The IV used for encryption. */
|
|
53
|
+
readonly iv: string | Uint8Array;
|
|
54
|
+
/** GCM only: the tag, when it is not appended to the ciphertext. */
|
|
55
|
+
readonly tag?: string | Uint8Array;
|
|
56
|
+
/** GCM only: the additional authenticated data given to encryption. */
|
|
57
|
+
readonly aad?: string | Uint8Array;
|
|
58
|
+
/** Encoding of a string ciphertext, `iv` and `tag`; defaults to `"base64"`. */
|
|
59
|
+
readonly encoding?: BinaryEncoding;
|
|
60
|
+
/** Form of the plaintext; defaults to `"utf8"`. */
|
|
61
|
+
readonly output?: DecryptOutput;
|
|
62
|
+
}
|
|
63
|
+
/** RSA encryption padding: OAEP with SHA-256 or SHA-1 (MGF1 uses the same digest), or PKCS #1 v1.5. */
|
|
64
|
+
export type RsaPadding = "OAEP-SHA256" | "OAEP-SHA1" | "PKCS1";
|
|
65
|
+
/** Options of {@link CryptoApi.rsaEncrypt}. */
|
|
66
|
+
export interface RsaEncryptOptions {
|
|
67
|
+
/** Defaults to `"OAEP-SHA256"`. */
|
|
68
|
+
readonly padding?: RsaPadding;
|
|
69
|
+
/** Encoding of the ciphertext; defaults to `"base64"`. */
|
|
70
|
+
readonly encoding?: BinaryEncoding;
|
|
71
|
+
}
|
|
72
|
+
/** Options of {@link CryptoApi.rsaDecrypt}. */
|
|
73
|
+
export interface RsaDecryptOptions {
|
|
74
|
+
/** Defaults to `"OAEP-SHA256"`. */
|
|
75
|
+
readonly padding?: RsaPadding;
|
|
76
|
+
/** Encoding of a string ciphertext; defaults to `"base64"`. */
|
|
77
|
+
readonly encoding?: BinaryEncoding;
|
|
78
|
+
/** Form of the plaintext; defaults to `"utf8"`. */
|
|
79
|
+
readonly output?: DecryptOutput;
|
|
80
|
+
}
|
|
81
|
+
/** Signature algorithm: RSA PKCS #1 v1.5, RSA-PSS (salt length equal to the digest length) or ECDSA. */
|
|
82
|
+
export type SignatureAlgorithm = "RSA-SHA1" | "RSA-SHA256" | "RSA-SHA384" | "RSA-SHA512" | "RSA-PSS-SHA256" | "RSA-PSS-SHA384" | "RSA-PSS-SHA512" | "ECDSA-SHA256" | "ECDSA-SHA384" | "ECDSA-SHA512";
|
|
83
|
+
/** Options of {@link CryptoApi.sign} and {@link CryptoApi.verify}. */
|
|
84
|
+
export interface SignatureOptions {
|
|
85
|
+
/** Encoding of the signature; defaults to `"base64"`. */
|
|
86
|
+
readonly encoding?: BinaryEncoding;
|
|
87
|
+
/** ECDSA only: `"der"` (default) or `"ieee-p1363"`, the raw `r || s` form that JWT and Web Crypto use. */
|
|
88
|
+
readonly signatureFormat?: "der" | "ieee-p1363";
|
|
89
|
+
}
|
|
90
|
+
/** Hashing, message authentication, randomness, encryption and signatures provided by Cogover. */
|
|
91
|
+
export interface CryptoApi {
|
|
92
|
+
/** SHA-256 digest of a string (encoded as UTF-8) or of bytes; `encoding` defaults to `"hex"`. */
|
|
93
|
+
sha256(data: string | Uint8Array, encoding?: "hex" | "base64"): Promise<string>;
|
|
94
|
+
/**
|
|
95
|
+
* HMAC-SHA256 of `data`. The key is a string (UTF-8), bytes, or `{ secret: name }` to use a project
|
|
96
|
+
* secret without reading its value; `encoding` defaults to `"hex"`.
|
|
97
|
+
*/
|
|
98
|
+
hmacSha256(key: string | Uint8Array | {
|
|
99
|
+
readonly secret: string;
|
|
100
|
+
}, data: string | Uint8Array, encoding?: "hex" | "base64"): Promise<string>;
|
|
101
|
+
/** Cryptographically secure random bytes; `length` is 1 through 1024. */
|
|
102
|
+
randomBytes(length: number): Promise<Uint8Array>;
|
|
103
|
+
/** A random version 4 UUID in its canonical lower-case form. */
|
|
104
|
+
randomUUID(): Promise<string>;
|
|
105
|
+
/** Compares two values in constant time; strings are compared as UTF-8 bytes. */
|
|
106
|
+
timingSafeEqual(a: string | Uint8Array, b: string | Uint8Array): boolean;
|
|
107
|
+
/** Encrypts `data` (a string is encoded as UTF-8) with AES-GCM or AES-CBC. */
|
|
108
|
+
aesEncrypt(key: AesKey, data: string | Uint8Array, options?: AesEncryptOptions): Promise<AesEncryptResult>;
|
|
109
|
+
/** Decrypts an AES ciphertext; fails with `DECRYPTION_FAILED` when the key, IV, tag or data is wrong. */
|
|
110
|
+
aesDecrypt(key: AesKey, ciphertext: string | Uint8Array, options: AesDecryptOptions & {
|
|
111
|
+
readonly output: "bytes";
|
|
112
|
+
}): Promise<Uint8Array>;
|
|
113
|
+
aesDecrypt(key: AesKey, ciphertext: string | Uint8Array, options: AesDecryptOptions & {
|
|
114
|
+
readonly output?: Exclude<DecryptOutput, "bytes">;
|
|
115
|
+
}): Promise<string>;
|
|
116
|
+
aesDecrypt(key: AesKey, ciphertext: string | Uint8Array, options: AesDecryptOptions): Promise<string | Uint8Array>;
|
|
117
|
+
/** Encrypts `data` (a string is encoded as UTF-8) with an RSA public key. */
|
|
118
|
+
rsaEncrypt(publicKey: AsymmetricKey, data: string | Uint8Array, options?: RsaEncryptOptions): Promise<string>;
|
|
119
|
+
/** Decrypts an RSA ciphertext with the private key; fails with `DECRYPTION_FAILED` when it cannot. */
|
|
120
|
+
rsaDecrypt(privateKey: AsymmetricKey, ciphertext: string | Uint8Array, options: RsaDecryptOptions & {
|
|
121
|
+
readonly output: "bytes";
|
|
122
|
+
}): Promise<Uint8Array>;
|
|
123
|
+
rsaDecrypt(privateKey: AsymmetricKey, ciphertext: string | Uint8Array, options?: RsaDecryptOptions & {
|
|
124
|
+
readonly output?: Exclude<DecryptOutput, "bytes">;
|
|
125
|
+
}): Promise<string>;
|
|
126
|
+
rsaDecrypt(privateKey: AsymmetricKey, ciphertext: string | Uint8Array, options?: RsaDecryptOptions): Promise<string | Uint8Array>;
|
|
127
|
+
/** Signs `data` (a string is encoded as UTF-8) with an RSA or EC private key. */
|
|
128
|
+
sign(algorithm: SignatureAlgorithm, privateKey: AsymmetricKey, data: string | Uint8Array, options?: SignatureOptions): Promise<string>;
|
|
129
|
+
/** Whether `signature` is a valid signature of `data`; a malformed signature is `false`, not an error. */
|
|
130
|
+
verify(algorithm: SignatureAlgorithm, publicKey: AsymmetricKey, data: string | Uint8Array, signature: string | Uint8Array, options?: SignatureOptions): Promise<boolean>;
|
|
131
|
+
}
|
|
132
|
+
/** Cryptographic helpers backed by Cogover's managed implementation. */
|
|
133
|
+
export declare const crypto: CryptoApi;
|