@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.
@@ -10,9 +10,10 @@ interface.
10
10
 
11
11
  Custom Backend Modules are written in TypeScript. `@cogover/sdk` supplies the
12
12
  types and APIs for the current invocation, workspace data, schema metadata,
13
- logging, outbound HTTPS requests, state, distributed locks, and push messages to
14
- web clients. Cogover executes
15
- the module with the permissions and resource limits configured for the project.
13
+ logging, outbound HTTPS requests, state, distributed locks, push messages to web
14
+ clients, background jobs, secrets, cryptography, and inbound webhooks. Cogover
15
+ executes the module with the permissions and resource limits configured for the
16
+ project.
16
17
 
17
18
  A typical development flow is:
18
19
 
@@ -161,6 +162,102 @@ configuration. Requests and responses are bounded. For remote mutations, use the
161
162
  destination API's idempotency mechanism: a timeout or missing response does not
162
163
  prove that the remote request was not applied.
163
164
 
165
+ ## Use secrets and credentials
166
+
167
+ Do not put API tokens in the source code or in request input. An administrator
168
+ stores them for the project through the Cogover management API, in one of two
169
+ forms:
170
+
171
+ - A **credential** is used only by `fetch`. Name it in `credential` and Cogover adds
172
+ the authentication header — `Authorization: Bearer …`, `Authorization: Basic …`,
173
+ or a custom header — to the request. The code never sees the value, and the
174
+ credential can only be sent to the hosts the administrator allowed.
175
+ - A **secret** is read with `secrets.get` when the code needs the value itself,
176
+ for example to build a signature or a non-standard header.
177
+
178
+ ```typescript
179
+ import { defineScript, fetch } from "@cogover/sdk";
180
+
181
+ export default defineScript<{ orderId: string }>(async ({ input, secrets, crypto }) => {
182
+ // Preferred: the token is added by Cogover and never enters the code.
183
+ const response = await fetch("https://erp.example.com/v1/orders", {
184
+ method: "POST",
185
+ credential: "erp_api",
186
+ headers: { "content-type": "application/json" },
187
+ body: JSON.stringify({ id: input.orderId }),
188
+ });
189
+
190
+ // When the value itself is needed, read a secret and sign with it.
191
+ const body = await response.text();
192
+ const signature = await crypto.hmacSha256({ secret: "partner_signing_key" }, body);
193
+ const apiKey = await secrets.get("partner_api_key");
194
+ await fetch("https://partner.example.com/events", {
195
+ method: "POST",
196
+ headers: { "x-api-key": apiKey, "x-signature": signature },
197
+ body,
198
+ });
199
+ return { status: response.status };
200
+ });
201
+ ```
202
+
203
+ `crypto.hmacSha256({ secret: name }, data)` signs with a secret without reading it,
204
+ which is enough for most signatures. Never write a secret to the log, to a record,
205
+ to state, or to a response, and prefer a credential over `secrets.get` whenever the
206
+ value is only needed for an HTTP header. Secrets and credentials are not available
207
+ in before-change triggers.
208
+
209
+ ## Encrypt, decrypt, and sign data
210
+
211
+ `crypto` also encrypts and signs with keys that stay in project secrets. Pass
212
+ `{ secret: name }` as the key: Cogover resolves it and the value never enters the
213
+ code.
214
+
215
+ ```typescript
216
+ import { createRouter, crypto, fetch } from "@cogover/sdk";
217
+
218
+ const router = createRouter();
219
+ router.post("/payments", async ({ request, response }) => {
220
+ // AES-256-GCM with a random IV; the partner receives the ciphertext and the IV.
221
+ const aesKey = { secret: "partner_aes_key", encoding: "base64" } as const;
222
+ const sealed = await crypto.aesEncrypt(aesKey, JSON.stringify(request.body));
223
+
224
+ // RSA: encrypt a small value with the partner's public key, sign with our private key.
225
+ const cardToken = await crypto.rsaEncrypt({ secret: "partner_public_key" }, "4111111111111111");
226
+ const body = JSON.stringify({ ...sealed, cardToken });
227
+ const signature = await crypto.sign("RSA-SHA256", { secret: "our_signing_key" }, body);
228
+ const reply = await fetch("https://partner.example.com/payments", {
229
+ method: "POST",
230
+ headers: { "content-type": "application/json", "x-signature": signature },
231
+ body,
232
+ });
233
+
234
+ // Verify the partner's ECDSA signature before trusting the reply.
235
+ const replyBody = await reply.text();
236
+ const valid = await crypto.verify("ECDSA-SHA256", { secret: "partner_public_key_ec" }, replyBody,
237
+ reply.headers.get("x-signature") ?? "");
238
+ return valid ? response.json(JSON.parse(replyBody)) : response.empty({ status: 502 });
239
+ });
240
+ export default router.toHandler();
241
+ ```
242
+
243
+ - `aesEncrypt`/`aesDecrypt` use AES-GCM by default; `mode: "CBC"` exists for
244
+ systems that require it. Leave out `iv` so that a new random IV is used every
245
+ time.
246
+ - `rsaEncrypt`/`rsaDecrypt` use RSA-OAEP with SHA-256 by default and encrypt at
247
+ most a few hundred bytes; encrypt larger data with AES and only the AES key
248
+ with RSA.
249
+ - `sign`/`verify` support RSA (PKCS #1 v1.5 and PSS) and ECDSA, including the
250
+ `base64url` and `ieee-p1363` forms used by JWT. `verify` returns `false` for a
251
+ malformed signature instead of throwing.
252
+ - A failed decryption throws `CogoverApiError` with `code: "DECRYPTION_FAILED"`.
253
+ - Keys are PEM text in a secret: store private keys unencrypted in PKCS #8, PKCS #1,
254
+ or SEC1 form; public keys may be a certificate. RSA keys must be 2048 to 4096 bits
255
+ and EC keys P-256, P-384, or P-521.
256
+
257
+ With a key from a secret, these operations follow the rules of secrets and are
258
+ not available in before-change triggers. The API reference describes every option
259
+ and the JWT algorithm names.
260
+
164
261
  ## Permissions and limits
165
262
 
166
263
  - Cogover authentication credentials are never exposed to module code. Access is
@@ -235,6 +332,94 @@ export default defineTrigger({
235
332
  (`recipients`); `exclude: ["actor"]` skips the user who caused the execution.
236
333
  Delivery is best-effort and each call counts as one capability call. The API
237
334
  reference lists the limits and message fields.
335
+ ## Run work in the background with jobs
336
+
337
+ An HTTP route or a trigger has a short time budget. Move longer work — walking
338
+ many records, calling a slow external API, nightly maintenance — into a
339
+ **background job**. Declare jobs with `defineJob` and list them in the named `jobs`
340
+ export; enqueue a run from a route, a trigger, or another job with `jobs.enqueue`,
341
+ or let a cron `schedule` start it.
342
+
343
+ ```typescript
344
+ import { defineJob } from "@cogover/sdk";
345
+
346
+ interface RecalcPayload {
347
+ cursor?: string;
348
+ }
349
+
350
+ // Processes one page per run and enqueues itself again with the next cursor.
351
+ export const recalcTotals = defineJob<RecalcPayload>({
352
+ key: "recalc_totals",
353
+ timeoutMs: 60_000,
354
+ }, async ({ payload, data, jobs, log }) => {
355
+ const orders = data.object("order");
356
+ const page = await orders.records.list({
357
+ fields: ["subtotal", "tax"],
358
+ limit: 200,
359
+ ...(payload?.cursor ? { cursor: payload.cursor } : {}),
360
+ });
361
+ for (const order of page.items) {
362
+ await orders.records.update(order.id, {
363
+ total: (order.fields.subtotal ?? 0) + (order.fields.tax ?? 0),
364
+ });
365
+ }
366
+ if (page.nextCursor) {
367
+ await jobs.enqueue("recalc_totals", { cursor: page.nextCursor });
368
+ return;
369
+ }
370
+ log.info("Order totals recalculated");
371
+ });
372
+
373
+ // Runs every night at 02:00 in the given time zone, with no payload.
374
+ export const cancelStaleOrders = defineJob({
375
+ key: "cancel_stale_orders",
376
+ schedule: { cron: "0 2 * * *", timezone: "Asia/Ho_Chi_Minh" },
377
+ }, async ({ data }) => {
378
+ const orders = data.object("order");
379
+ const stale = await orders.records.list({
380
+ where: orders.fields.status.eq("new"),
381
+ fields: ["status"],
382
+ limit: 200,
383
+ });
384
+ for (const order of stale.items) {
385
+ await orders.records.update(order.id, { status: "cancelled" });
386
+ }
387
+ });
388
+
389
+ export const jobs = [recalcTotals, cancelStaleOrders];
390
+ ```
391
+
392
+ Start the batch from a route:
393
+
394
+ ```typescript
395
+ router.post("/recalculate", async ({ jobs, response }) => {
396
+ const { runId } = await jobs.enqueue("recalc_totals", {}, { idempotencyKey: "recalc:daily" });
397
+ return response.json({ runId }, { status: 202 });
398
+ });
399
+ ```
400
+
401
+ - A job handler receives `job` (run ID, key, attempt, source), the `payload` passed
402
+ to `enqueue` (or `null`), and the same `data`, `schema`, `log`, `state`, `locks`,
403
+ `jobs`, `secrets`, and `crypto` APIs as a script. Its return value is ignored.
404
+ - A run enqueued from a route or trigger acts as the user of that call. A scheduled
405
+ run has no user: `data.object()` works only when the identity policy allows the
406
+ system identity, so approve `allowInternalSystem` for projects with schedules.
407
+ - Runs are delivered at least once: a run interrupted by a restart is started
408
+ again, and a temporary failure reported with `RetryableError` (or a timeout) is
409
+ retried with growing delays up to `maxAttempts` times. Make the handler
410
+ idempotent and use `job.id` or a business key as the idempotency key of external
411
+ calls. Any other error fails the run without a retry.
412
+ - Each attempt must finish within `timeoutMs` (up to 60 seconds). Split longer work
413
+ into pages and enqueue the next page, as in the example: enqueueing does not
414
+ consume the automation budget, so the chain is only limited by the handler's own
415
+ stop condition. Record writes made by a job do use the budget and run triggers
416
+ like any other write.
417
+ - `idempotencyKey` makes a repeated enqueue return the existing run with
418
+ `duplicate: true`; `delayMs` or `runAt` postpones a run by up to 30 days. A
419
+ payload is JSON of at most 64 KiB.
420
+
421
+ See the [background job reference](api-reference.md#background-jobs) for every
422
+ option and rule.
238
423
 
239
424
  ## Choose the identity for record operations
240
425
 
@@ -407,7 +592,8 @@ rejected and nothing is saved. Keep handlers short and deterministic. See the
407
592
  Set `timing: "afterChange"` to run code after a change has been saved. The handler
408
593
  runs asynchronously, shortly after the write: the writer does not wait for it, and
409
594
  the handler can neither reject nor modify the saved change. Unlike a before-change
410
- trigger it may write records and call `fetch`, like a script.
595
+ trigger it may write records, call `fetch`, read secrets, and enqueue background
596
+ jobs, like a script.
411
597
 
412
598
  ```typescript
413
599
  import { defineTrigger, fetch, RetryableError } from "@cogover/sdk";
@@ -520,3 +706,66 @@ HTTP 200. `response.json`, `text`, `bytes`, `empty`, and `redirect` provide expl
520
706
  status, safe response headers, and text/binary bodies. Missing routes return 404;
521
707
  unsupported methods return 405. Existing `defineScript()` projects continue at `/`.
522
708
  Validate all business input. See the [router API reference](api-reference.md#http-routers-and-request-context).
709
+
710
+ ## Receive webhooks
711
+
712
+ An external system can call a route without a Cogover user session through an
713
+ **inbound access** that an administrator creates for the project. The
714
+ administrator gives the external system a URL of the form
715
+ `https://{WORKSPACE_DOMAIN}/api/v1/ts-projects/{projectSlug}/hooks/{inboundId}/{route}`
716
+ together with an inbound key or an HMAC signing secret. Cogover authenticates each
717
+ call and rejects invalid ones before the module runs; the module sees the call at
718
+ `/hooks/{route}` with `invocation.identity === "inbound"`.
719
+
720
+ ```typescript
721
+ import { createRouter, defineJob } from "@cogover/sdk";
722
+
723
+ interface PaymentEvent { id: string; orderId: string; status: "succeeded" | "failed" }
724
+
725
+ const router = createRouter();
726
+ router.post("/hooks/payments", async ({ request, invocation, crypto, jobs, response }) => {
727
+ if (invocation.identity !== "inbound") return response.empty({ status: 403 });
728
+
729
+ // Optional: this provider also signs "<timestamp>.<raw body>" with its own secret.
730
+ const timestamp = request.headers["x-payment-timestamp"] ?? "";
731
+ const expected = await crypto.hmacSha256(
732
+ { secret: "payment_signing_secret" }, `${timestamp}.${request.rawBody ?? ""}`);
733
+ if (!crypto.timingSafeEqual(`sha256=${expected}`, request.headers["x-payment-signature"] ?? "")) {
734
+ return response.empty({ status: 401 });
735
+ }
736
+
737
+ const event = request.body as Partial<PaymentEvent>;
738
+ if (typeof event.id !== "string" || typeof event.orderId !== "string") {
739
+ return response.json({ error: "Invalid event" }, { status: 400 });
740
+ }
741
+ await jobs.enqueue("sync_payment", event, { idempotencyKey: `payment:${event.id}` });
742
+ return response.json({ received: true }, { status: 202 });
743
+ });
744
+ export default router.toHandler();
745
+
746
+ export const jobs = [
747
+ defineJob<PaymentEvent>({ key: "sync_payment" }, async ({ payload, data }) => {
748
+ if (!payload) return;
749
+ // An ID from outside is a plain string: read the record first, then update it through its own ID.
750
+ const orders = data.object("order");
751
+ const order = await orders.records.get(payload.orderId, { fields: ["status"] });
752
+ if (!order) return;
753
+ await orders.records.update(order.id, {
754
+ status: payload.status === "succeeded" ? "processed" : "cancelled",
755
+ });
756
+ }),
757
+ ];
758
+ ```
759
+
760
+ - `request.rawBody` is the body exactly as received and `request.contentType` its
761
+ content type, so a handler can verify the sender's signature or parse a
762
+ non-JSON body. `request.body` holds the parsed JSON object, or `{}` for any other
763
+ body.
764
+ - An inbound call has no user. `data.object()` uses the system identity and works
765
+ only when the identity policy allows it; `data.asUser()` and `data.asSystem()`
766
+ follow the policy as usual. Prefer to acknowledge quickly and enqueue a job — the
767
+ job also runs as the system identity.
768
+ - Providers retry webhooks that did not get a 2xx answer, so use the event's own
769
+ ID as the job's `idempotencyKey`.
770
+
771
+ See [Inbound webhooks](api-reference.md#inbound-webhooks) for the complete rules.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cogover/sdk",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "TypeScript SDK for developing Custom Backend Modules on Cogover",
5
5
  "type": "module",
6
6
  "sideEffects": false,