@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.
@@ -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,50 @@ 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
+
164
209
  ## Permissions and limits
165
210
 
166
211
  - Cogover authentication credentials are never exposed to module code. Access is
@@ -235,6 +280,94 @@ export default defineTrigger({
235
280
  (`recipients`); `exclude: ["actor"]` skips the user who caused the execution.
236
281
  Delivery is best-effort and each call counts as one capability call. The API
237
282
  reference lists the limits and message fields.
283
+ ## Run work in the background with jobs
284
+
285
+ An HTTP route or a trigger has a short time budget. Move longer work — walking
286
+ many records, calling a slow external API, nightly maintenance — into a
287
+ **background job**. Declare jobs with `defineJob` and list them in the named `jobs`
288
+ export; enqueue a run from a route, a trigger, or another job with `jobs.enqueue`,
289
+ or let a cron `schedule` start it.
290
+
291
+ ```typescript
292
+ import { defineJob } from "@cogover/sdk";
293
+
294
+ interface RecalcPayload {
295
+ cursor?: string;
296
+ }
297
+
298
+ // Processes one page per run and enqueues itself again with the next cursor.
299
+ export const recalcTotals = defineJob<RecalcPayload>({
300
+ key: "recalc_totals",
301
+ timeoutMs: 60_000,
302
+ }, async ({ payload, data, jobs, log }) => {
303
+ const orders = data.object("order");
304
+ const page = await orders.records.list({
305
+ fields: ["subtotal", "tax"],
306
+ limit: 200,
307
+ ...(payload?.cursor ? { cursor: payload.cursor } : {}),
308
+ });
309
+ for (const order of page.items) {
310
+ await orders.records.update(order.id, {
311
+ total: (order.fields.subtotal ?? 0) + (order.fields.tax ?? 0),
312
+ });
313
+ }
314
+ if (page.nextCursor) {
315
+ await jobs.enqueue("recalc_totals", { cursor: page.nextCursor });
316
+ return;
317
+ }
318
+ log.info("Order totals recalculated");
319
+ });
320
+
321
+ // Runs every night at 02:00 in the given time zone, with no payload.
322
+ export const cancelStaleOrders = defineJob({
323
+ key: "cancel_stale_orders",
324
+ schedule: { cron: "0 2 * * *", timezone: "Asia/Ho_Chi_Minh" },
325
+ }, async ({ data }) => {
326
+ const orders = data.object("order");
327
+ const stale = await orders.records.list({
328
+ where: orders.fields.status.eq("new"),
329
+ fields: ["status"],
330
+ limit: 200,
331
+ });
332
+ for (const order of stale.items) {
333
+ await orders.records.update(order.id, { status: "cancelled" });
334
+ }
335
+ });
336
+
337
+ export const jobs = [recalcTotals, cancelStaleOrders];
338
+ ```
339
+
340
+ Start the batch from a route:
341
+
342
+ ```typescript
343
+ router.post("/recalculate", async ({ jobs, response }) => {
344
+ const { runId } = await jobs.enqueue("recalc_totals", {}, { idempotencyKey: "recalc:daily" });
345
+ return response.json({ runId }, { status: 202 });
346
+ });
347
+ ```
348
+
349
+ - A job handler receives `job` (run ID, key, attempt, source), the `payload` passed
350
+ to `enqueue` (or `null`), and the same `data`, `schema`, `log`, `state`, `locks`,
351
+ `jobs`, `secrets`, and `crypto` APIs as a script. Its return value is ignored.
352
+ - A run enqueued from a route or trigger acts as the user of that call. A scheduled
353
+ run has no user: `data.object()` works only when the identity policy allows the
354
+ system identity, so approve `allowInternalSystem` for projects with schedules.
355
+ - Runs are delivered at least once: a run interrupted by a restart is started
356
+ again, and a temporary failure reported with `RetryableError` (or a timeout) is
357
+ retried with growing delays up to `maxAttempts` times. Make the handler
358
+ idempotent and use `job.id` or a business key as the idempotency key of external
359
+ calls. Any other error fails the run without a retry.
360
+ - Each attempt must finish within `timeoutMs` (up to 60 seconds). Split longer work
361
+ into pages and enqueue the next page, as in the example: enqueueing does not
362
+ consume the automation budget, so the chain is only limited by the handler's own
363
+ stop condition. Record writes made by a job do use the budget and run triggers
364
+ like any other write.
365
+ - `idempotencyKey` makes a repeated enqueue return the existing run with
366
+ `duplicate: true`; `delayMs` or `runAt` postpones a run by up to 30 days. A
367
+ payload is JSON of at most 64 KiB.
368
+
369
+ See the [background job reference](api-reference.md#background-jobs) for every
370
+ option and rule.
238
371
 
239
372
  ## Choose the identity for record operations
240
373
 
@@ -407,7 +540,8 @@ rejected and nothing is saved. Keep handlers short and deterministic. See the
407
540
  Set `timing: "afterChange"` to run code after a change has been saved. The handler
408
541
  runs asynchronously, shortly after the write: the writer does not wait for it, and
409
542
  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.
543
+ trigger it may write records, call `fetch`, read secrets, and enqueue background
544
+ jobs, like a script.
411
545
 
412
546
  ```typescript
413
547
  import { defineTrigger, fetch, RetryableError } from "@cogover/sdk";
@@ -520,3 +654,66 @@ HTTP 200. `response.json`, `text`, `bytes`, `empty`, and `redirect` provide expl
520
654
  status, safe response headers, and text/binary bodies. Missing routes return 404;
521
655
  unsupported methods return 405. Existing `defineScript()` projects continue at `/`.
522
656
  Validate all business input. See the [router API reference](api-reference.md#http-routers-and-request-context).
657
+
658
+ ## Receive webhooks
659
+
660
+ An external system can call a route without a Cogover user session through an
661
+ **inbound access** that an administrator creates for the project. The
662
+ administrator gives the external system a URL of the form
663
+ `https://{WORKSPACE_DOMAIN}/api/v1/ts-projects/{projectSlug}/hooks/{inboundId}/{route}`
664
+ together with an inbound key or an HMAC signing secret. Cogover authenticates each
665
+ call and rejects invalid ones before the module runs; the module sees the call at
666
+ `/hooks/{route}` with `invocation.identity === "inbound"`.
667
+
668
+ ```typescript
669
+ import { createRouter, defineJob } from "@cogover/sdk";
670
+
671
+ interface PaymentEvent { id: string; orderId: string; status: "succeeded" | "failed" }
672
+
673
+ const router = createRouter();
674
+ router.post("/hooks/payments", async ({ request, invocation, crypto, jobs, response }) => {
675
+ if (invocation.identity !== "inbound") return response.empty({ status: 403 });
676
+
677
+ // Optional: this provider also signs "<timestamp>.<raw body>" with its own secret.
678
+ const timestamp = request.headers["x-payment-timestamp"] ?? "";
679
+ const expected = await crypto.hmacSha256(
680
+ { secret: "payment_signing_secret" }, `${timestamp}.${request.rawBody ?? ""}`);
681
+ if (!crypto.timingSafeEqual(`sha256=${expected}`, request.headers["x-payment-signature"] ?? "")) {
682
+ return response.empty({ status: 401 });
683
+ }
684
+
685
+ const event = request.body as Partial<PaymentEvent>;
686
+ if (typeof event.id !== "string" || typeof event.orderId !== "string") {
687
+ return response.json({ error: "Invalid event" }, { status: 400 });
688
+ }
689
+ await jobs.enqueue("sync_payment", event, { idempotencyKey: `payment:${event.id}` });
690
+ return response.json({ received: true }, { status: 202 });
691
+ });
692
+ export default router.toHandler();
693
+
694
+ export const jobs = [
695
+ defineJob<PaymentEvent>({ key: "sync_payment" }, async ({ payload, data }) => {
696
+ if (!payload) return;
697
+ // An ID from outside is a plain string: read the record first, then update it through its own ID.
698
+ const orders = data.object("order");
699
+ const order = await orders.records.get(payload.orderId, { fields: ["status"] });
700
+ if (!order) return;
701
+ await orders.records.update(order.id, {
702
+ status: payload.status === "succeeded" ? "processed" : "cancelled",
703
+ });
704
+ }),
705
+ ];
706
+ ```
707
+
708
+ - `request.rawBody` is the body exactly as received and `request.contentType` its
709
+ content type, so a handler can verify the sender's signature or parse a
710
+ non-JSON body. `request.body` holds the parsed JSON object, or `{}` for any other
711
+ body.
712
+ - An inbound call has no user. `data.object()` uses the system identity and works
713
+ only when the identity policy allows it; `data.asUser()` and `data.asSystem()`
714
+ follow the policy as usual. Prefer to acknowledge quickly and enqueue a job — the
715
+ job also runs as the system identity.
716
+ - Providers retry webhooks that did not get a 2xx answer, so use the event's own
717
+ ID as the job's `idempotencyKey`.
718
+
719
+ 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.8.0",
4
4
  "description": "TypeScript SDK for developing Custom Backend Modules on Cogover",
5
5
  "type": "module",
6
6
  "sideEffects": false,