@cogover/sdk 0.6.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 +126 -5
- 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 +7 -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 +9 -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/push.d.ts +48 -0
- package/dist/push.js +190 -0
- package/dist/request.d.ts +4 -0
- package/dist/response.js +1 -15
- package/dist/router.js +4 -0
- package/dist/script.d.ts +8 -0
- package/dist/script.js +8 -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 +11 -0
- package/docs/en/api-reference.md +631 -25
- package/docs/en/usage-guide.md +230 -6
- package/package.json +1 -1
package/docs/en/usage-guide.md
CHANGED
|
@@ -10,8 +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,
|
|
14
|
-
|
|
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.
|
|
15
17
|
|
|
16
18
|
A typical development flow is:
|
|
17
19
|
|
|
@@ -160,6 +162,50 @@ configuration. Requests and responses are bounded. For remote mutations, use the
|
|
|
160
162
|
destination API's idempotency mechanism: a timeout or missing response does not
|
|
161
163
|
prove that the remote request was not applied.
|
|
162
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
|
+
|
|
163
209
|
## Permissions and limits
|
|
164
210
|
|
|
165
211
|
- Cogover authentication credentials are never exposed to module code. Access is
|
|
@@ -209,6 +255,120 @@ longer work, watch `expiresAt` and call `renew()` before expiry. Use the fencing
|
|
|
209
255
|
token in downstream systems where possible to reject stale writers. Locks do not
|
|
210
256
|
replace idempotency or provide exactly-once execution.
|
|
211
257
|
|
|
258
|
+
## Tell open record pages to reload
|
|
259
|
+
|
|
260
|
+
```typescript
|
|
261
|
+
export default defineTrigger({
|
|
262
|
+
key: "recalculate_totals",
|
|
263
|
+
object: "order",
|
|
264
|
+
timing: "afterChange",
|
|
265
|
+
operations: ["update"],
|
|
266
|
+
fields: ["subtotal", "tax"],
|
|
267
|
+
}, async ({ records, data, push }) => {
|
|
268
|
+
const items = records.flatMap(record => record.id === null ? [] : [{
|
|
269
|
+
id: record.id,
|
|
270
|
+
fields: { total: (record.new.subtotal ?? 0) + (record.new.tax ?? 0) },
|
|
271
|
+
}]);
|
|
272
|
+
await data.object("order").records.batchUpdate(items);
|
|
273
|
+
// Everyone who has one of these orders open reloads it, including the user who saved.
|
|
274
|
+
await push.refreshRecords("order", items.map(item => item.id));
|
|
275
|
+
});
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
`push` also shows a toast (`push.toast`) or sends a silent message
|
|
279
|
+
(`push.message`) to the people viewing given records or to explicit personnel IDs
|
|
280
|
+
(`recipients`); `exclude: ["actor"]` skips the user who caused the execution.
|
|
281
|
+
Delivery is best-effort and each call counts as one capability call. The API
|
|
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.
|
|
371
|
+
|
|
212
372
|
## Choose the identity for record operations
|
|
213
373
|
|
|
214
374
|
Keep using `data.object("order")` to inherit the caller's identity. When an
|
|
@@ -359,10 +519,10 @@ inside the loop. Collect the IDs, call `records.getMany` once, and look the resu
|
|
|
359
519
|
up from a `Map`, as in the example above.
|
|
360
520
|
|
|
361
521
|
**Read-only.** A before-change trigger may read records and schema. Record writes,
|
|
362
|
-
`fetch`, locks,
|
|
522
|
+
`fetch`, locks, state writes, and push messages are refused with `PermissionDeniedError`
|
|
363
523
|
(`details.reason === "TRIGGER_READ_ONLY"`), for every identity. The trigger context
|
|
364
|
-
has `records`, `trigger`, `invocation`, `data`, `schema`, and `
|
|
365
|
-
`request`, `response`, `state`, or `locks`.
|
|
524
|
+
has `records`, `trigger`, `invocation`, `data`, `schema`, `log`, and `push`; it has
|
|
525
|
+
no `request`, `response`, `state`, or `locks`.
|
|
366
526
|
|
|
367
527
|
**Identity.** `data.object()` acts as the user who made the change, with that user's
|
|
368
528
|
permissions, so a read can legitimately return nothing for a record the user cannot
|
|
@@ -380,7 +540,8 @@ rejected and nothing is saved. Keep handlers short and deterministic. See the
|
|
|
380
540
|
Set `timing: "afterChange"` to run code after a change has been saved. The handler
|
|
381
541
|
runs asynchronously, shortly after the write: the writer does not wait for it, and
|
|
382
542
|
the handler can neither reject nor modify the saved change. Unlike a before-change
|
|
383
|
-
trigger it may write records
|
|
543
|
+
trigger it may write records, call `fetch`, read secrets, and enqueue background
|
|
544
|
+
jobs, like a script.
|
|
384
545
|
|
|
385
546
|
```typescript
|
|
386
547
|
import { defineTrigger, fetch, RetryableError } from "@cogover/sdk";
|
|
@@ -493,3 +654,66 @@ HTTP 200. `response.json`, `text`, `bytes`, `empty`, and `redirect` provide expl
|
|
|
493
654
|
status, safe response headers, and text/binary bodies. Missing routes return 404;
|
|
494
655
|
unsupported methods return 405. Existing `defineScript()` projects continue at `/`.
|
|
495
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.
|