@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.
@@ -8,8 +8,8 @@ configured for the project.
8
8
  ## `defineScript`
9
9
 
10
10
  `defineScript<Input, Output>(handler)` wraps an async Cogover script. It parses
11
- the input JSON, supplies `input`, `request`, `invocation`, `response`, `data`, `schema`, `log`, `state`, `locks`, and `push`, awaits the handler,
12
- and serializes its result.
11
+ the input JSON, supplies `input`, `request`, `invocation`, `response`, `data`, `schema`, `log`, `state`, `locks`,
12
+ `push`, `jobs`, `secrets`, and `crypto`, awaits the handler, and serializes its result.
13
13
 
14
14
  ```typescript
15
15
  function defineScript<
@@ -40,6 +40,9 @@ interface ScriptContext<Input, Schema extends object = EffectiveWorkspaceObjects
40
40
  readonly state: ProjectState;
41
41
  readonly locks: DistributedLocks;
42
42
  readonly push: PushApi<Schema>;
43
+ readonly jobs: JobsApi;
44
+ readonly secrets: SecretsApi;
45
+ readonly crypto: CryptoApi;
43
46
  }
44
47
  ```
45
48
 
@@ -50,9 +53,9 @@ Returning `null` produces a null handler result; returning `undefined` is invali
50
53
  ## HTTP routers and request context
51
54
 
52
55
  `ScriptContext<TInput, TSchema>` provides `input`, `request`, `invocation`, `response`, `data`, `schema`,
53
- `log`, `state`, `locks`, and `push` to both script and route handlers. `input` preserves the invocation
54
- input. Prefer `request.body` for business data: it excludes invocation metadata and
55
- transport/authentication fields removed by Cogover.
56
+ `log`, `state`, `locks`, `push`, `jobs`, `secrets`, and `crypto` to both script and route handlers. `input`
57
+ preserves the invocation input. Prefer `request.body` for business data: it excludes invocation
58
+ metadata and transport/authentication fields removed by Cogover.
56
59
 
57
60
  ```typescript
58
61
  type RequestMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
@@ -67,6 +70,8 @@ interface ScriptRequest<TBody = unknown> {
67
70
  readonly query: ScriptQuery;
68
71
  readonly headers: ScriptHeaders;
69
72
  readonly body: TBody;
73
+ readonly rawBody?: string; // Webhook calls only
74
+ readonly contentType?: string; // Webhook calls only
70
75
  }
71
76
  ```
72
77
 
@@ -77,6 +82,11 @@ credentials such as `authorization` and `cookie` are never exposed. Dynamic path
77
82
  parameters are percent-decoded after safe route matching. TypeScript types do not
78
83
  validate runtime business input.
79
84
 
85
+ `rawBody` and `contentType` are present only for a call that reached the project
86
+ through an inbound webhook (see [Inbound webhooks](#inbound-webhooks)): `rawBody`
87
+ is the request body exactly as received, as a UTF-8 string, and `contentType` is
88
+ the request's `Content-Type` header. For every other call both fields are absent.
89
+
80
90
  ## Invocation identity and workspace
81
91
 
82
92
  `context.invocation` is a synchronous, immutable snapshot built from metadata that
@@ -84,7 +94,7 @@ Cogover already authenticated and loaded for the current execution. Reading it
84
94
  does not make a data API request.
85
95
 
86
96
  ```typescript
87
- type InvocationContext = UserInvocationContext | SystemInvocationContext;
97
+ type InvocationContext = UserInvocationContext | SystemInvocationContext | InboundInvocationContext;
88
98
 
89
99
  interface CurrentWorkspace {
90
100
  readonly id: string;
@@ -125,16 +135,36 @@ interface SystemInvocationContext {
125
135
  readonly workspace: CurrentWorkspace;
126
136
  readonly user: null;
127
137
  }
138
+
139
+ interface InboundInvocationContext {
140
+ readonly identity: "inbound";
141
+ readonly workspace: CurrentWorkspace;
142
+ readonly user: null;
143
+ readonly inbound: {
144
+ readonly id: string; // Part of the webhook URL
145
+ readonly name: string;
146
+ readonly mode: "KEY" | "HMAC"; // How the call was authenticated
147
+ };
148
+ }
128
149
  ```
129
150
 
130
151
  All fields are readonly. Optional profile and workspace fields may be absent, so
131
152
  scripts must not assume that they contain a value.
132
153
 
154
+ `identity` is `"user"` for a call made by an authenticated Workspace user,
155
+ `"system"` for an execution without a user, such as a scheduled job, and
156
+ `"inbound"` for a webhook call authenticated by one of the project's inbound
157
+ accesses (see [Inbound webhooks](#inbound-webhooks)). An inbound invocation has no
158
+ user; `inbound` identifies the inbound access that authenticated the call.
159
+
133
160
  ```typescript
134
161
  export default defineScript(({ invocation }) => {
135
162
  if (invocation.identity === "system") {
136
163
  return {workspaceId: invocation.workspace.id, user: null};
137
164
  }
165
+ if (invocation.identity === "inbound") {
166
+ return {workspaceId: invocation.workspace.id, inbound: invocation.inbound.name};
167
+ }
138
168
  return {
139
169
  workspaceId: invocation.workspace.id,
140
170
  accountId: invocation.user.accountId,
@@ -144,9 +174,9 @@ export default defineScript(({ invocation }) => {
144
174
  ```
145
175
 
146
176
  Cogover ignores caller-supplied invocation metadata and creates this snapshot from
147
- the authenticated request context. Raw authentication data, tokens, and credentials
148
- are not included. A handler called outside Cogover has no authenticated invocation
149
- snapshot.
177
+ the authenticated request context. Raw authentication data, tokens, inbound keys,
178
+ and credentials are not included. A handler called outside Cogover has no
179
+ authenticated invocation snapshot.
150
180
 
151
181
  ### `createRouter<TSchema = EffectiveWorkspaceObjects>(): ScriptRouter<TSchema>`
152
182
 
@@ -468,6 +498,9 @@ interface TriggerContext<
468
498
  readonly schema: SchemaApi<Schema>;
469
499
  readonly log: ScriptLogger;
470
500
  readonly push: PushApi<Schema>;
501
+ readonly jobs: JobsApi;
502
+ readonly secrets: SecretsApi;
503
+ readonly crypto: CryptoApi;
471
504
  }
472
505
 
473
506
  interface TriggerInfo<Operation extends TriggerOperation = TriggerOperation> {
@@ -503,12 +536,11 @@ receives all records of the same change that run the trigger, up to 200 records
503
536
  once per record. Keep `fields` short, and read related data for the whole list with
504
537
  one `records.getMany` call rather than one read per record.
505
538
 
506
- `data`, `schema`, `log`, `push`, and `invocation` are the same APIs that scripts receive.
507
- A trigger context has no `input`, `request`, `response`, `state`, or `locks`; `push` is
508
- refused in a before-change trigger.
509
- `trigger.operation` is the operation of the current call, `trigger.id` identifies the
510
- trigger registration, and `trigger.changeId` identifies the record change that caused
511
- the call.
539
+ `data`, `schema`, `log`, `invocation`, `push`, `jobs`, `secrets`, and `crypto` are the
540
+ same APIs that scripts receive. A trigger context has no `input`, `request`, `response`,
541
+ `state`, or `locks`; `push` is refused in a before-change trigger. `trigger.operation` is
542
+ the operation of the current call, `trigger.id` identifies the trigger registration, and
543
+ `trigger.changeId` identifies the record change that caused the call.
512
544
 
513
545
  Each `TriggerRecord` describes one record:
514
546
 
@@ -585,9 +617,12 @@ merges, and cascading deletes — do not run before-change triggers, and neither
585
617
  a request that only validates input without saving.
586
618
 
587
619
  - **Read-only.** A before-change trigger may read records and schema, but every
588
- record write, `fetch`, lock, state write, and push message is refused with
620
+ record write, `fetch`, lock, state write, push message, `jobs.enqueue`, `secrets.get`,
621
+ and every `crypto` operation with a `{ secret }` key is refused with
589
622
  `PermissionDeniedError` whose `details.reason` is `"TRIGGER_READ_ONLY"`. This
590
- applies to every identity, including `data.asSystem()`.
623
+ applies to every identity, including `data.asSystem()`. Every `crypto` operation
624
+ with a key given in the call remains available, as do `crypto.sha256`,
625
+ `crypto.randomBytes`, `crypto.randomUUID`, and `crypto.timingSafeEqual`.
591
626
  - **Identity.** `data.object()` acts as the user who made the change, with that
592
627
  user's permissions, and `invocation` describes the same user. When a change has
593
628
  no user, `invocation.identity` is `"system"` and `data.object()` works only if the
@@ -649,11 +684,13 @@ export const triggers = [
649
684
  were saved, including the record ID and values assigned while saving, such as an
650
685
  auto number. For a deleted record `record.new` is `null` and `record.old` holds the
651
686
  last values.
652
- - **May write and call out.** Record writes and `fetch` work as they do in a script,
653
- within the same runtime limits. `data.object()` acts as the user who made the
654
- change, and the other identity rules of before-change triggers apply. The trigger
655
- context has no `state` or `locks`; `push` is available and is the usual way to
656
- refresh the records the handler changed for everyone who has them open.
687
+ - **May write and call out.** Record writes, `fetch`, `push`, `jobs.enqueue`,
688
+ `secrets.get`, and `crypto` work as they do in a script, within the same runtime
689
+ limits. `data.object()` acts as the user who made the change, and the other identity
690
+ rules of before-change triggers apply. The trigger context has no `state` or `locks`;
691
+ `push` is the usual way to refresh the records the handler changed for everyone who
692
+ has them open, and longer work, or work that needs `state` or `locks`, belongs in a
693
+ [background job](#background-jobs).
657
694
  - **Best-effort delivery.** Cogover does not guarantee that an after-change handler
658
695
  runs exactly once. It may occasionally run more than once for the same change, or
659
696
  not at all. Make every handler idempotent: `trigger.changeId` together with
@@ -679,6 +716,279 @@ export const triggers = [
679
716
  order. A retried call may run after a later change of the same record has already
680
717
  been processed, so read the current record when the latest values matter.
681
718
 
719
+ ## Background jobs
720
+
721
+ A background job runs project code outside an HTTP request: enqueued by a script, a
722
+ trigger, another job, or an administrator, or started by a cron schedule. Declare
723
+ each job with `defineJob` and list the results in the project's named `jobs`
724
+ export. The default export is still the HTTP handler and is optional in a project
725
+ that only declares jobs and triggers.
726
+
727
+ This example assumes that `workspace.d.ts` declares the `order` Object and the
728
+ fields used below.
729
+
730
+ ```typescript
731
+ import { defineJob } from "@cogover/sdk";
732
+
733
+ interface RecalcPayload {
734
+ cursor?: string;
735
+ }
736
+
737
+ export const jobs = [
738
+ // Enqueued by a route or a trigger; walks all orders one page per run.
739
+ defineJob<RecalcPayload>({
740
+ key: "recalc_totals",
741
+ name: "Recalculate order totals",
742
+ timeoutMs: 60_000,
743
+ }, async ({ payload, data, jobs, log }) => {
744
+ const orders = data.object("order");
745
+ const page = await orders.records.list({
746
+ fields: ["subtotal", "tax"],
747
+ limit: 200,
748
+ ...(payload?.cursor ? { cursor: payload.cursor } : {}),
749
+ });
750
+ for (const order of page.items) {
751
+ await orders.records.update(order.id, {
752
+ total: (order.fields.subtotal ?? 0) + (order.fields.tax ?? 0),
753
+ });
754
+ }
755
+ if (page.nextCursor) {
756
+ // Continue with the next page in a new run instead of one long run.
757
+ await jobs.enqueue("recalc_totals", { cursor: page.nextCursor });
758
+ return;
759
+ }
760
+ log.info("Order totals recalculated");
761
+ }),
762
+
763
+ // Runs every day at 02:00 in the given time zone.
764
+ defineJob({
765
+ key: "cancel_stale_orders",
766
+ schedule: { cron: "0 2 * * *", timezone: "Asia/Ho_Chi_Minh" },
767
+ }, async ({ data }) => {
768
+ const orders = data.object("order");
769
+ const stale = await orders.records.list({
770
+ where: orders.fields.status.eq("new"),
771
+ fields: ["status"],
772
+ limit: 200,
773
+ });
774
+ for (const order of stale.items) {
775
+ await orders.records.update(order.id, { status: "cancelled" });
776
+ }
777
+ }),
778
+ ];
779
+ ```
780
+
781
+ Cogover reads the job configuration when a project version is published and applies
782
+ it while that version is active: `jobs.enqueue` accepts only the keys declared by the
783
+ active version, and schedules run only while their version is active. Deactivating
784
+ the project removes its schedules. A project can declare at most 50 jobs.
785
+
786
+ ### `defineJob(config, handler): JobDefinition`
787
+
788
+ ```typescript
789
+ function defineJob<
790
+ Payload = unknown,
791
+ Schema extends object = EffectiveWorkspaceObjects,
792
+ >(config: JobConfig, handler: JobHandler<Payload, Schema>): JobDefinition;
793
+ ```
794
+
795
+ `Payload` is the type of the value passed to `jobs.enqueue`; it is not validated at
796
+ run time, so treat the payload like request input. `defineJob` validates the
797
+ configuration immediately and throws `ValidationError` for any violation, for an
798
+ unknown configuration key, or for a handler that is not a function. It returns a
799
+ frozen `JobDefinition`.
800
+
801
+ ```typescript
802
+ interface JobConfig {
803
+ readonly key: string;
804
+ readonly name?: string;
805
+ readonly timeoutMs?: number;
806
+ readonly maxAttempts?: number;
807
+ readonly schedule?: JobSchedule;
808
+ }
809
+
810
+ interface JobSchedule {
811
+ readonly cron: string;
812
+ readonly timezone?: string;
813
+ }
814
+ ```
815
+
816
+ | Option | Required | Rules and meaning |
817
+ |---|---|---|
818
+ | `key` | Yes | Identifies the job inside the project. Starts with an ASCII letter and contains letters, digits, or `_`; at most 100 characters; unique in the project regardless of case. Keep it stable between versions: a new key is a different job. |
819
+ | `name` | No | Display name of at most 250 characters. Defaults to `key`. |
820
+ | `timeoutMs` | No | Integer from 1000 through 60000; defaults to `30000`. Time budget of one attempt. |
821
+ | `maxAttempts` | No | Integer from 1 through 10; defaults to `5`. Total number of attempts of one run, including the first. |
822
+ | `schedule` | No | Runs the job automatically. `cron` has five fields — minute, hour, day-of-month, month, day-of-week — and `timezone` is an IANA time zone ID of at most 64 characters, defaulting to `"UTC"`. |
823
+
824
+ A cron field is `*`, a number, a range `a-b`, a list `a,b`, a step `*/n`, or a
825
+ stepped range `a-b/n`; the fields accept minutes 0–59, hours 0–23, days 1–31,
826
+ months 1–12, and weekdays 0–7 where both 0 and 7 are Sunday. Names such as `MON`,
827
+ the characters `L`, `W`, `#`, and `?`, and macros such as `@daily` are not supported.
828
+ The shortest period is one minute. Whitespace between the fields is normalized to
829
+ one space in the manifest.
830
+
831
+ ### `JobDefinition` and `JobManifest`
832
+
833
+ ```typescript
834
+ interface JobManifest {
835
+ readonly key: string;
836
+ readonly name?: string;
837
+ readonly timeoutMs: number;
838
+ readonly maxAttempts: number;
839
+ readonly schedule?: { readonly cron: string; readonly timezone: string };
840
+ }
841
+
842
+ interface JobDefinition {
843
+ readonly key: string;
844
+ readonly config: JobManifest;
845
+ readonly __cogoverJobHandler: SandboxHandler;
846
+ }
847
+ ```
848
+
849
+ `config` is the normalized configuration as deeply frozen plain JSON, with every
850
+ default applied: `timeoutMs: 30000`, `maxAttempts: 5`, and `schedule.timezone:
851
+ "UTC"`. Optional settings that were not provided are absent. It is detached from the
852
+ object passed to `defineJob`, so later edits of that object have no effect.
853
+ `__cogoverJobHandler` is reserved for Cogover; project code does not call it.
854
+
855
+ ### Job handler context
856
+
857
+ ```typescript
858
+ type JobHandler<
859
+ Payload = unknown,
860
+ Schema extends object = EffectiveWorkspaceObjects,
861
+ > = (context: JobContext<Payload, Schema>) => void | Promise<void>;
862
+
863
+ interface JobContext<Payload = unknown, Schema extends object = EffectiveWorkspaceObjects> {
864
+ readonly job: JobInfo;
865
+ readonly payload: Payload | null;
866
+ readonly invocation: InvocationContext;
867
+ readonly data: DataApi<Schema>;
868
+ readonly schema: SchemaApi<Schema>;
869
+ readonly log: ScriptLogger;
870
+ readonly state: ProjectState;
871
+ readonly locks: DistributedLocks;
872
+ readonly jobs: JobsApi;
873
+ readonly secrets: SecretsApi;
874
+ readonly crypto: CryptoApi;
875
+ }
876
+
877
+ interface JobInfo {
878
+ readonly id: string;
879
+ readonly key: string;
880
+ readonly attempt: number;
881
+ readonly maxAttempts: number;
882
+ readonly source: "enqueue" | "schedule";
883
+ readonly runAt: number;
884
+ readonly enqueuedAt?: number;
885
+ }
886
+ ```
887
+
888
+ A handler may be synchronous or asynchronous; its return value is ignored. `data`,
889
+ `schema`, `log`, `invocation`, `state`, `locks`, `jobs`, `secrets`, and `crypto`
890
+ are the same APIs that scripts receive. A job context has no `input`, `request`, or
891
+ `response`.
892
+
893
+ - `job.id` identifies the run and stays the same across its attempts; use it as the
894
+ idempotency key of external calls. `job.attempt` starts at 1.
895
+ - `job.source` is `"enqueue"` for a run created by `jobs.enqueue` or by an
896
+ administrator and `"schedule"` for a run created by the job's schedule. `job.runAt`
897
+ is when the run became due and `job.enqueuedAt` when it was enqueued; both are Unix
898
+ milliseconds, and `enqueuedAt` is absent for a scheduled run.
899
+ - `payload` is the JSON value passed to `jobs.enqueue`, or `null` when none was
900
+ passed or the run is scheduled. It is plain, mutable data.
901
+
902
+ ### `jobs.enqueue(jobKey, payload?, options?): Promise<EnqueueResult>`
903
+
904
+ ```typescript
905
+ interface JobsApi {
906
+ enqueue(jobKey: string, payload?: unknown, options?: EnqueueOptions): Promise<EnqueueResult>;
907
+ }
908
+
909
+ interface EnqueueOptions {
910
+ readonly delayMs?: number;
911
+ readonly runAt?: number;
912
+ readonly idempotencyKey?: string;
913
+ }
914
+
915
+ interface EnqueueResult {
916
+ readonly runId: string;
917
+ readonly duplicate: boolean;
918
+ }
919
+ ```
920
+
921
+ ```typescript
922
+ const { runId, duplicate } = await jobs.enqueue("sync_order", { orderId: order.id }, {
923
+ delayMs: 60_000,
924
+ idempotencyKey: `sync_order:${order.id}:${order.system.updatedAt}`,
925
+ });
926
+ ```
927
+
928
+ `jobKey` must be a job declared by the active version; otherwise Cogover throws
929
+ `ValidationError`. `payload` is any JSON value of at most 65,536 UTF-8 bytes after
930
+ serialization; `undefined` and `null` enqueue the run without a payload. Values that
931
+ JSON would silently change, such as `NaN` or class instances, are rejected with
932
+ `ValidationError`. `delayMs` is an integer from 0 through 2,592,000,000 (30 days)
933
+ and `runAt` a Unix millisecond time at most 30 days ahead; pass one or neither, not
934
+ both. `idempotencyKey` starts with a letter or digit, contains letters, digits, `.`,
935
+ `_`, `:`, or `-`, and is at most 128 characters: a second enqueue of the same job
936
+ with the same key while the earlier run is still kept returns that run with
937
+ `duplicate: true` instead of creating another. Run history is kept for 7 days.
938
+
939
+ `enqueue` works in scripts and routes, after-change triggers, jobs, and inbound
940
+ webhook calls. A before-change trigger is refused with `PermissionDeniedError`
941
+ (`details.reason === "TRIGGER_READ_ONLY"`), and so is a local development session
942
+ without write permission (`"DEVELOPMENT_SESSION_READ_ONLY"`). One invocation may
943
+ enqueue at most 50 runs, and a project may have at most 10,000 runs waiting or
944
+ running; beyond that `RateLimitError` is thrown. When jobs are not enabled for the
945
+ Workspace, the error is `CogoverApiError` with `code: "JOBS_DISABLED"`.
946
+
947
+ ### Job execution rules
948
+
949
+ - **Identity.** A run enqueued from a script, route, or trigger runs as the user of
950
+ that invocation: `invocation` describes that user and `data.object()` acts with
951
+ that user's permissions. A scheduled run, a run enqueued by an administrator, and
952
+ a run enqueued from an inbound webhook call have no user: `invocation.identity`
953
+ is `"system"`, and `data.object()` works only if the project's approved identity
954
+ policy sets `allowInternalSystem: true`; otherwise its calls throw
955
+ `PermissionDeniedError` with `details.reason` `"IDENTITY_NOT_GRANTED"`.
956
+ `data.asUser()` and `data.asSystem()` follow the identity policy as usual.
957
+ - **Capabilities.** A job may do everything a script can: read and write records,
958
+ call `fetch`, use `state` and `locks`, enqueue jobs, read secrets, and use
959
+ `crypto`, within the runtime limits of the job lane.
960
+ - **Time.** Each attempt must finish within `timeoutMs`. Work that needs longer is
961
+ split: process one page, save the cursor, and enqueue the same job again with the
962
+ cursor in the payload, as in the example above.
963
+ - **At least once.** Cogover does not guarantee that a run executes exactly once: an
964
+ attempt that was interrupted, for example by a restart, is started again. Make
965
+ every handler idempotent. `job.id` identifies the run across attempts, and
966
+ `idempotencyKey` on `enqueue` prevents duplicate runs.
967
+ - **Retries.** Throw `RetryableError` when the handler fails for a temporary reason,
968
+ such as an external service that is unavailable. Cogover runs the attempt again
969
+ later, waiting longer before each attempt, from a few seconds to about half an
970
+ hour, until `maxAttempts` attempts have been made. An attempt that exceeds
971
+ `timeoutMs`, or that Cogover could not run for a temporary reason, is retried the
972
+ same way. Any other error ends the run as failed: the failure is logged and the
973
+ handler does not run again for that run.
974
+ - **Order and concurrency.** Runs execute in no guaranteed order, and two runs of the
975
+ same project, even of the same job, may execute at the same time. Use `locks` when
976
+ a section must not run concurrently, and delay through `delayMs` or `runAt` rather
977
+ than by waiting inside the handler.
978
+ - **Loops end.** Record writes made by a run carry the automation budget of the
979
+ invocation that enqueued it (a scheduled run and an administrator's enqueue start
980
+ with the full budget of 10 steps), so a chain of jobs and triggers started by
981
+ record writes ends the same way as a trigger chain. Enqueueing a job does not use
982
+ a step: a job that enqueues itself must stop on its own, for example when the
983
+ cursor is exhausted.
984
+
985
+ A scheduled job creates one run for each time the schedule matches, in the
986
+ schedule's time zone; the run may start a little later than the scheduled minute
987
+ under load. A slot that is missed while the project is inactive is not run later.
988
+ A run is still created when the previous scheduled run has not finished, so a
989
+ schedule whose work can take longer than its period should guard itself with a
990
+ lock.
991
+
682
992
  ## Outbound HTTP `fetch`
683
993
 
684
994
  ```typescript
@@ -689,6 +999,7 @@ interface CogoverFetchInit {
689
999
  readonly headers?: Readonly<Record<string, string>>;
690
1000
  readonly body?: string;
691
1001
  readonly timeoutMs?: number;
1002
+ readonly credential?: string;
692
1003
  }
693
1004
 
694
1005
  interface CogoverFetchHeaders {
@@ -749,6 +1060,435 @@ Failures are `CogoverApiError` instances with `FETCH_DISABLED`, `FETCH_BLOCKED`,
749
1060
  times out or loses its response, the remote server may already have applied the
750
1061
  request. Use the remote API's idempotency mechanism and never retry blindly.
751
1062
 
1063
+ ### Authenticating with a credential
1064
+
1065
+ `credential` names a credential that an administrator stored for the project (see
1066
+ [Secrets and credentials](#secrets-and-credentials)). Cogover adds the credential's
1067
+ authentication header to the request, so project code never handles the value:
1068
+
1069
+ ```typescript
1070
+ const response = await fetch("https://erp.example.com/v1/orders", {
1071
+ method: "POST",
1072
+ credential: "erp_api",
1073
+ headers: { "content-type": "application/json" },
1074
+ body: JSON.stringify({ id: "ORD-1" }),
1075
+ });
1076
+ ```
1077
+
1078
+ Depending on how the credential was created, Cogover sends `Authorization: Bearer
1079
+ <value>`, `Authorization: Basic <base64 of value>`, or a header with the configured
1080
+ name. The name must start with a letter and contain at most 64 letters, digits, or
1081
+ underscores. A credential can only be sent to the hosts its administrator allowed;
1082
+ a request to another host, a request that sets the same header itself, or a name
1083
+ that is not an active credential fails with `FETCH_BLOCKED`. Redirects are never
1084
+ followed, so a credential never leaves an allowed host.
1085
+
1086
+ ## Secrets and credentials
1087
+
1088
+ An administrator stores secrets for a project through the Cogover management API.
1089
+ Each one is either a **secret**, whose value code reads with `secrets.get`, or a
1090
+ **credential**, which only `fetch` uses (see
1091
+ [Authenticating with a credential](#authenticating-with-a-credential)); the value
1092
+ of a credential is never readable by code. Values are stored encrypted and are
1093
+ never returned by the management API, logged, or included in error messages.
1094
+
1095
+ ```typescript
1096
+ interface SecretsApi {
1097
+ get(name: string): Promise<string>;
1098
+ }
1099
+ ```
1100
+
1101
+ ```typescript
1102
+ const token = await secrets.get("erp_token");
1103
+ const response = await fetch("https://erp.example.com/v1/orders", {
1104
+ headers: { authorization: `Bearer ${token}` },
1105
+ });
1106
+ ```
1107
+
1108
+ ### `secrets.get(name): Promise<string>`
1109
+
1110
+ Returns the current value of the secret. `name` starts with a letter and contains
1111
+ at most 64 letters, digits, or underscores; other names throw `ValidationError`
1112
+ before the call. A secret that does not exist or is disabled throws
1113
+ `ValidationError` with the message `Secret '<name>' is not available`, and a
1114
+ credential throws `ValidationError` with `Secret '<name>' is a credential and
1115
+ cannot be read`.
1116
+
1117
+ `secrets.get` works in scripts and routes, after-change triggers, jobs, and inbound
1118
+ webhook calls. A before-change trigger is refused with `PermissionDeniedError`
1119
+ (`details.reason === "TRIGGER_READ_ONLY"`); a local development session reads
1120
+ secrets only when its administrator allowed it, otherwise the reason is
1121
+ `"SECRETS_NOT_ALLOWED"`. One invocation may read at most 20 secrets; reading the
1122
+ same name again in the same invocation returns the cached value. When secrets are
1123
+ not enabled for the Workspace, the error is `CogoverApiError` with
1124
+ `code: "SECRETS_DISABLED"`. Never write a secret value to the log, to a record, to
1125
+ state, or to a response. To sign, encrypt, or decrypt with a secret without
1126
+ reading it, pass `{ secret: name }` as the key of a [`crypto`](#cryptography)
1127
+ operation.
1128
+
1129
+ ## Cryptography
1130
+
1131
+ `crypto` provides hashing, message authentication, randomness, AES and RSA
1132
+ encryption, and RSA and ECDSA signatures through Cogover's managed
1133
+ implementation. Import it from `@cogover/sdk` or read it from `context.crypto`;
1134
+ both are the same frozen object.
1135
+
1136
+ ```typescript
1137
+ const crypto: CryptoApi;
1138
+
1139
+ type BinaryEncoding = "base64" | "base64url" | "hex";
1140
+ type DecryptOutput = "utf8" | "bytes" | BinaryEncoding;
1141
+
1142
+ interface SecretKeyReference {
1143
+ readonly secret: string;
1144
+ }
1145
+ type AesKey =
1146
+ | string
1147
+ | Uint8Array
1148
+ | (SecretKeyReference & { readonly encoding?: "utf8" | "base64" | "hex" });
1149
+ type AsymmetricKey = string | SecretKeyReference;
1150
+
1151
+ interface CryptoApi {
1152
+ sha256(data: string | Uint8Array, encoding?: "hex" | "base64"): Promise<string>;
1153
+ hmacSha256(
1154
+ key: string | Uint8Array | { readonly secret: string },
1155
+ data: string | Uint8Array,
1156
+ encoding?: "hex" | "base64",
1157
+ ): Promise<string>;
1158
+ randomBytes(length: number): Promise<Uint8Array>;
1159
+ randomUUID(): Promise<string>;
1160
+ timingSafeEqual(a: string | Uint8Array, b: string | Uint8Array): boolean;
1161
+
1162
+ aesEncrypt(key: AesKey, data: string | Uint8Array, options?: AesEncryptOptions): Promise<AesEncryptResult>;
1163
+ aesDecrypt(key: AesKey, ciphertext: string | Uint8Array, options: AesDecryptOptions): Promise<string>;
1164
+ aesDecrypt(
1165
+ key: AesKey,
1166
+ ciphertext: string | Uint8Array,
1167
+ options: AesDecryptOptions & { readonly output: "bytes" },
1168
+ ): Promise<Uint8Array>;
1169
+ rsaEncrypt(publicKey: AsymmetricKey, data: string | Uint8Array, options?: RsaEncryptOptions): Promise<string>;
1170
+ rsaDecrypt(privateKey: AsymmetricKey, ciphertext: string | Uint8Array, options?: RsaDecryptOptions): Promise<string>;
1171
+ rsaDecrypt(
1172
+ privateKey: AsymmetricKey,
1173
+ ciphertext: string | Uint8Array,
1174
+ options: RsaDecryptOptions & { readonly output: "bytes" },
1175
+ ): Promise<Uint8Array>;
1176
+ sign(
1177
+ algorithm: SignatureAlgorithm,
1178
+ privateKey: AsymmetricKey,
1179
+ data: string | Uint8Array,
1180
+ options?: SignatureOptions,
1181
+ ): Promise<string>;
1182
+ verify(
1183
+ algorithm: SignatureAlgorithm,
1184
+ publicKey: AsymmetricKey,
1185
+ data: string | Uint8Array,
1186
+ signature: string | Uint8Array,
1187
+ options?: SignatureOptions,
1188
+ ): Promise<boolean>;
1189
+ }
1190
+ ```
1191
+
1192
+ `aesDecrypt` and `rsaDecrypt` return a string unless `output` is `"bytes"`; when
1193
+ `output` is only known as a `DecryptOutput`, the result type is
1194
+ `string | Uint8Array`.
1195
+
1196
+ ```typescript
1197
+ import { crypto } from "@cogover/sdk";
1198
+
1199
+ const digest = await crypto.sha256(JSON.stringify(payload));
1200
+ const signature = await crypto.hmacSha256({ secret: "webhook_secret" }, request.rawBody ?? "");
1201
+ if (!crypto.timingSafeEqual(signature, request.headers["x-signature"] ?? "")) {
1202
+ return response.empty({ status: 401 });
1203
+ }
1204
+ const token = await crypto.randomUUID();
1205
+ ```
1206
+
1207
+ ### Hashing, HMAC, and randomness
1208
+
1209
+ - `sha256(data, encoding?)` returns the SHA-256 digest of `data`. A string is
1210
+ hashed as UTF-8; a `Uint8Array` is hashed as is. `encoding` is `"hex"` (default)
1211
+ or `"base64"`.
1212
+ - `hmacSha256(key, data, encoding?)` returns the HMAC-SHA256 of `data`. The key is a
1213
+ non-empty string (UTF-8), a non-empty `Uint8Array`, or `{ secret: name }` to use
1214
+ a project secret without reading its value.
1215
+ - `randomBytes(length)` returns `length` cryptographically secure random bytes;
1216
+ `length` is an integer from 1 through 1024.
1217
+ - `randomUUID()` returns a random version 4 UUID such as
1218
+ `"3f9c2d6e-8b1a-4c7d-9e2f-1a2b3c4d5e6f"`.
1219
+ - `timingSafeEqual(a, b)` compares two strings or byte arrays in constant time and
1220
+ returns `false` for different lengths. Strings are compared as UTF-8 bytes. Use
1221
+ it for every comparison of a signature, token, or key.
1222
+
1223
+ ### Keys
1224
+
1225
+ Every key can be given in the call or as `{ secret: name }`. A secret key is
1226
+ resolved by Cogover and its value never reaches project code; the named secret
1227
+ must be readable by `secrets.get` in the same context and counts as one secret
1228
+ read. Store every private key and every AES key as a project secret; a key written
1229
+ in source code is visible to everyone who can read the project.
1230
+
1231
+ - **AES keys** are 16, 24, or 32 bytes (AES-128, AES-192, AES-256). A string is
1232
+ used as its UTF-8 bytes and a `Uint8Array` as is. For a secret, `encoding` states
1233
+ how the secret's value holds the key: `"utf8"` (default) uses the text itself,
1234
+ and `"base64"` or `"hex"` decode it first, ignoring surrounding whitespace.
1235
+ - **RSA and EC keys** (`AsymmetricKey`) are PEM text, or the base64 body of one
1236
+ without the `-----BEGIN` lines (DER as `PUBLIC KEY` for a public key and as
1237
+ `PRIVATE KEY` for a private key). Text before the PEM block and an
1238
+ `EC PARAMETERS` block are ignored.
1239
+
1240
+ | Key | Accepted PEM types |
1241
+ |---|---|
1242
+ | Public key (`rsaEncrypt`, `verify`) | `PUBLIC KEY` (SubjectPublicKeyInfo), `RSA PUBLIC KEY` (PKCS #1), `CERTIFICATE` (X.509; only its public key is used) |
1243
+ | Private key (`rsaDecrypt`, `sign`) | `PRIVATE KEY` (PKCS #8), `RSA PRIVATE KEY` (PKCS #1), `EC PRIVATE KEY` (SEC1) |
1244
+
1245
+ RSA keys must be 2048 to 4096 bits. EC keys must use the P-256, P-384, or P-521
1246
+ curve. Encrypted private keys (`ENCRYPTED PRIVATE KEY`, or PEM with
1247
+ `Proc-Type` headers) and OpenSSH keys are not supported; store the unencrypted
1248
+ PKCS #8 key as a secret instead. Key text is limited to 16,384 characters. A
1249
+ certificate is not checked for expiry, revocation, or its issuer: it is only a
1250
+ container for the public key.
1251
+
1252
+ ### `crypto.aesEncrypt(key, data, options?): Promise<AesEncryptResult>`
1253
+
1254
+ ```typescript
1255
+ type AesMode = "GCM" | "CBC";
1256
+
1257
+ interface AesEncryptOptions {
1258
+ readonly mode?: AesMode; // Default "GCM"
1259
+ readonly iv?: string | Uint8Array; // Default: random
1260
+ readonly aad?: string | Uint8Array; // GCM only
1261
+ readonly separateTag?: boolean; // GCM only, default false
1262
+ readonly encoding?: BinaryEncoding; // Default "base64"
1263
+ }
1264
+
1265
+ interface AesEncryptResult {
1266
+ readonly ciphertext: string;
1267
+ readonly iv: string;
1268
+ readonly tag?: string; // Only with separateTag
1269
+ }
1270
+ ```
1271
+
1272
+ Encrypts `data` (a string is encoded as UTF-8) and returns the ciphertext and IV in
1273
+ `encoding`.
1274
+
1275
+ - `"GCM"` (default) is authenticated encryption: decryption detects any change to
1276
+ the ciphertext, IV, tag, or `aad`. `ciphertext` is the encrypted data followed by
1277
+ the 16-byte authentication tag, the form used by Java, .NET, and Web Crypto.
1278
+ With `separateTag: true` the tag is returned in `tag` instead, as systems built
1279
+ on Node.js or OpenSSL usually expect.
1280
+ - `"CBC"` uses PKCS #7 padding. It does not detect changes to the ciphertext; use
1281
+ it only when an external system requires it, and authenticate the ciphertext
1282
+ separately, for example with `hmacSha256`.
1283
+ - Without `iv`, a random IV is generated: 12 bytes for GCM and 16 bytes for CBC.
1284
+ A given `iv` must be 12 to 16 bytes for GCM and exactly 16 bytes for CBC; a
1285
+ string `iv` is decoded with `encoding`. **Never use the same IV twice with the
1286
+ same GCM key**: doing so breaks both confidentiality and authentication. Pass
1287
+ an IV only when an external system dictates it.
1288
+ - `aad` is additional data that is authenticated but not encrypted, such as a
1289
+ record ID; a string is encoded as UTF-8. The same `aad` must be given to
1290
+ decryption.
1291
+
1292
+ ### `crypto.aesDecrypt(key, ciphertext, options): Promise<string | Uint8Array>`
1293
+
1294
+ ```typescript
1295
+ interface AesDecryptOptions {
1296
+ readonly mode?: AesMode; // Default "GCM"
1297
+ readonly iv: string | Uint8Array;
1298
+ readonly tag?: string | Uint8Array; // GCM only, when not appended to the ciphertext
1299
+ readonly aad?: string | Uint8Array; // GCM only
1300
+ readonly encoding?: BinaryEncoding; // Of a string ciphertext, iv, and tag; default "base64"
1301
+ readonly output?: DecryptOutput; // Default "utf8"
1302
+ }
1303
+ ```
1304
+
1305
+ Decrypts an AES ciphertext. `iv` is required. In GCM mode, the last 16 bytes of
1306
+ `ciphertext` are the tag unless `tag` is given. `output` selects the result:
1307
+ `"utf8"` (default) decodes the plaintext as UTF-8 text and throws
1308
+ `ValidationError` if it is not valid UTF-8, `"bytes"` returns a `Uint8Array`, and
1309
+ `"base64"`, `"base64url"`, or `"hex"` return the plaintext bytes in that encoding.
1310
+
1311
+ A wrong key, IV, tag, or `aad`, a modified ciphertext, or invalid CBC padding
1312
+ throws `CogoverApiError` with `code: "DECRYPTION_FAILED"`. The error is the same
1313
+ for every cause, so that the result reveals nothing about the key or plaintext.
1314
+
1315
+ ```typescript
1316
+ import { crypto, CogoverApiError, defineScript } from "@cogover/sdk";
1317
+
1318
+ export default defineScript(async ({ request }) => {
1319
+ const { data, iv, tag } = request.body as { data: string; iv: string; tag: string };
1320
+ try {
1321
+ const json = await crypto.aesDecrypt({ secret: "partner_aes_key", encoding: "base64" }, data, { iv, tag });
1322
+ return { payment: JSON.parse(json) };
1323
+ } catch (error) {
1324
+ if (error instanceof CogoverApiError && error.code === "DECRYPTION_FAILED") {
1325
+ return { r: 1001, msg: "The payload could not be decrypted." };
1326
+ }
1327
+ throw error;
1328
+ }
1329
+ });
1330
+ ```
1331
+
1332
+ ### `crypto.rsaEncrypt(publicKey, data, options?)` and `crypto.rsaDecrypt(privateKey, ciphertext, options?)`
1333
+
1334
+ ```typescript
1335
+ type RsaPadding = "OAEP-SHA256" | "OAEP-SHA1" | "PKCS1";
1336
+
1337
+ interface RsaEncryptOptions {
1338
+ readonly padding?: RsaPadding; // Default "OAEP-SHA256"
1339
+ readonly encoding?: BinaryEncoding; // Of the ciphertext; default "base64"
1340
+ }
1341
+
1342
+ interface RsaDecryptOptions {
1343
+ readonly padding?: RsaPadding; // Default "OAEP-SHA256"
1344
+ readonly encoding?: BinaryEncoding; // Of a string ciphertext; default "base64"
1345
+ readonly output?: DecryptOutput; // Default "utf8"
1346
+ }
1347
+ ```
1348
+
1349
+ `rsaEncrypt` encrypts `data` (a string is encoded as UTF-8) with an RSA public key
1350
+ and returns the ciphertext in `encoding`. `rsaDecrypt` decrypts it with the
1351
+ matching private key and returns the plaintext as `output`, like `aesDecrypt`.
1352
+
1353
+ - `"OAEP-SHA256"` (default) is RSA-OAEP with SHA-256, and its mask generation
1354
+ function MGF1 also uses SHA-256, as in Web Crypto, Node.js, and OpenSSL.
1355
+ `"OAEP-SHA1"` uses SHA-1 for both. Some Java code written as
1356
+ `OAEPWithSHA-256AndMGF1Padding` keeps MGF1 on SHA-1 and is compatible with
1357
+ neither; ask the other system which digest its MGF1 uses.
1358
+ - `"PKCS1"` is PKCS #1 v1.5 padding. Use it only when an external system requires
1359
+ it.
1360
+ - RSA encrypts only a small amount of data: at most the key size in bytes minus
1361
+ 66 bytes for `"OAEP-SHA256"`, minus 42 for `"OAEP-SHA1"`, and minus 11 for
1362
+ `"PKCS1"` — 190, 214, and 245 bytes for a 2048-bit key. Larger data throws
1363
+ `ValidationError`. To send more, encrypt the data with `aesEncrypt` under a
1364
+ random key from `randomBytes(32)` and encrypt only that key with `rsaEncrypt`.
1365
+ - A decryption that fails for any reason throws `CogoverApiError` with
1366
+ `code: "DECRYPTION_FAILED"`.
1367
+
1368
+ ```typescript
1369
+ const cardToken = await crypto.rsaEncrypt({ secret: "bank_public_key" }, "4111111111111111");
1370
+ const plain = await crypto.rsaDecrypt({ secret: "our_private_key" }, request.body.data as string);
1371
+ ```
1372
+
1373
+ ### `crypto.sign(algorithm, privateKey, data, options?)` and `crypto.verify(algorithm, publicKey, data, signature, options?)`
1374
+
1375
+ ```typescript
1376
+ type SignatureAlgorithm =
1377
+ | "RSA-SHA1" | "RSA-SHA256" | "RSA-SHA384" | "RSA-SHA512"
1378
+ | "RSA-PSS-SHA256" | "RSA-PSS-SHA384" | "RSA-PSS-SHA512"
1379
+ | "ECDSA-SHA256" | "ECDSA-SHA384" | "ECDSA-SHA512";
1380
+
1381
+ interface SignatureOptions {
1382
+ readonly encoding?: BinaryEncoding; // Of the signature; default "base64"
1383
+ readonly signatureFormat?: "der" | "ieee-p1363"; // ECDSA only; default "der"
1384
+ }
1385
+ ```
1386
+
1387
+ `sign` signs `data` (a string is encoded as UTF-8) with a private key and returns
1388
+ the signature in `encoding`. `verify` returns `true` when `signature` is a valid
1389
+ signature of `data` for the public key, and `false` otherwise, including when the
1390
+ signature cannot be decoded or has the wrong length; a signature normally comes
1391
+ from the party being verified, so a malformed one is not an error. An invalid
1392
+ key or algorithm still throws `ValidationError`.
1393
+
1394
+ - `RSA-SHA*` is RSASSA-PKCS1-v1_5 and requires an RSA key. `RSA-SHA1` exists only
1395
+ to verify signatures of systems that still use it; do not use it for new
1396
+ signatures.
1397
+ - `RSA-PSS-SHA*` is RSASSA-PSS with MGF1 on the same digest and a salt as long as
1398
+ the digest (32, 48, or 64 bytes), and requires an RSA key.
1399
+ - `ECDSA-SHA*` requires an EC key. `signatureFormat` is `"der"` (ASN.1, used by
1400
+ OpenSSL and Java) or `"ieee-p1363"` (the fixed-length `r || s` form used by JWT
1401
+ and Web Crypto); it is rejected for RSA algorithms.
1402
+
1403
+ | JWT `alg` | `algorithm` | Options |
1404
+ |---|---|---|
1405
+ | `RS256`, `RS384`, `RS512` | `RSA-SHA256`, `RSA-SHA384`, `RSA-SHA512` | `{ encoding: "base64url" }` |
1406
+ | `PS256`, `PS384`, `PS512` | `RSA-PSS-SHA256`, `RSA-PSS-SHA384`, `RSA-PSS-SHA512` | `{ encoding: "base64url" }` |
1407
+ | `ES256`, `ES384`, `ES512` | `ECDSA-SHA256`, `ECDSA-SHA384`, `ECDSA-SHA512` | `{ encoding: "base64url", signatureFormat: "ieee-p1363" }` |
1408
+
1409
+ ```typescript
1410
+ // Verify an ES256 JWT issued by a partner. Also check its claims (exp, iss, aud) before trusting it.
1411
+ const [header, payload, signature] = token.split(".");
1412
+ const valid = await crypto.verify("ECDSA-SHA256", { secret: "partner_jwt_public_key" },
1413
+ `${header}.${payload}`, signature ?? "", { encoding: "base64url", signatureFormat: "ieee-p1363" });
1414
+ if (!valid) return response.empty({ status: 401 });
1415
+
1416
+ // Sign a request to a bank that expects SHA256withRSA in base64.
1417
+ const body = JSON.stringify(order);
1418
+ const bankSignature = await crypto.sign("RSA-SHA256", { secret: "bank_signing_key" }, body);
1419
+ ```
1420
+
1421
+ ### Limits and availability
1422
+
1423
+ `data`, `aad`, and an explicit HMAC key are limited to 256 KiB, and a ciphertext
1424
+ to 256 KiB plus its tag; larger values and invalid arguments throw
1425
+ `ValidationError` before the call. The key, algorithm, and option errors that
1426
+ Cogover detects, such as a key of the wrong size or type, also throw
1427
+ `ValidationError`. Every operation except `timingSafeEqual` is a capability call
1428
+ and counts towards the invocation's limits.
1429
+
1430
+ The operations work in every context, including before-change triggers, with a key
1431
+ given in the call. A `{ secret }` key follows the rules of `secrets.get`: a
1432
+ before-change trigger is refused with `PermissionDeniedError`
1433
+ (`details.reason === "TRIGGER_READ_ONLY"`) and a local development session without
1434
+ secret access with `details.reason === "SECRETS_NOT_ALLOWED"`.
1435
+
1436
+ ## Inbound webhooks
1437
+
1438
+ An administrator can create an **inbound access** for a project so that an external
1439
+ system calls a route without a Cogover user session. The external system receives
1440
+ a URL of the form
1441
+
1442
+ ```text
1443
+ https://{WORKSPACE_DOMAIN}/api/v1/ts-projects/{projectSlug}/hooks/{inboundId}/{route}
1444
+ ```
1445
+
1446
+ and authenticates each call with the inbound key or the HMAC signature that was
1447
+ configured for the inbound access. Cogover verifies the key or signature, applies
1448
+ the rate limit, and rejects the call before any project code runs. A route handler
1449
+ sees such a call as `request.path === "/hooks/{route}"`: register webhook routes
1450
+ under `/hooks/` and the inbound ID is not part of the path.
1451
+
1452
+ ```typescript
1453
+ import { createRouter } from "@cogover/sdk";
1454
+
1455
+ const router = createRouter();
1456
+ router.post("/hooks/payments", async ({ request, invocation, crypto, jobs, response }) => {
1457
+ if (invocation.identity !== "inbound") return response.empty({ status: 403 });
1458
+
1459
+ // Optional: verify the external system's own signature over the raw body.
1460
+ const expected = await crypto.hmacSha256({ secret: "payment_signing_secret" }, request.rawBody ?? "");
1461
+ if (!crypto.timingSafeEqual(expected, request.headers["x-payment-signature"] ?? "")) {
1462
+ return response.empty({ status: 401 });
1463
+ }
1464
+
1465
+ const event = request.body as { id: string; orderId: string };
1466
+ await jobs.enqueue("sync_payment", event, { idempotencyKey: `payment:${event.id}` });
1467
+ return response.json({ received: true }, { status: 202 });
1468
+ });
1469
+ export default router.toHandler();
1470
+ ```
1471
+
1472
+ - **Identity.** `invocation.identity` is `"inbound"`, `invocation.user` is `null`,
1473
+ and `invocation.inbound` holds the `id`, `name`, and authentication `mode` of the
1474
+ inbound access. `data.object()` acts as the system identity and works only if the
1475
+ project's approved identity policy sets `allowInternalSystem: true`; otherwise its
1476
+ calls throw `PermissionDeniedError` with `details.reason` `"IDENTITY_NOT_GRANTED"`.
1477
+ `data.asUser()` and `data.asSystem()` follow the identity policy as usual.
1478
+ - **Body.** The request body is limited to 256 KiB. When it is a JSON object it is
1479
+ `request.body`; a form, text, or other body leaves `request.body` empty (`{}`).
1480
+ `request.rawBody` always holds the body exactly as received, as a UTF-8 string,
1481
+ and `request.contentType` the request's `Content-Type`, so a handler can verify a
1482
+ signature or parse another format itself.
1483
+ - **Response.** The handler's return value and the `response` helpers work as for
1484
+ any route. Keep the handler short: acknowledge the event and enqueue a job for
1485
+ the actual work, so that the external system gets a quick answer and retries
1486
+ cannot overlap with slow processing.
1487
+ - **Retries.** External systems usually retry a webhook that did not receive a
1488
+ 2xx response, so a handler may see the same event more than once. Use the event's
1489
+ own identifier as the `idempotencyKey` of the job it enqueues, or as a state key.
1490
+ An `Idempotency-Key` request header works as for any route.
1491
+
752
1492
  ## Record API
753
1493
 
754
1494
  ```typescript
@@ -1430,11 +2170,19 @@ there was no server response, such as local SDK validation. The original message
1430
2170
  remains in `error.message`.
1431
2171
 
1432
2172
  `RetryableError` (`code: "RETRYABLE"`) is thrown by project code, never by the SDK.
1433
- An after-change trigger handler throws it to report a temporary failure, and Cogover
1434
- runs the handler again later (see
1435
- [After-change execution rules](#after-change-execution-rules)). Anywhere else it
1436
- has no special meaning: a script that lets it escape returns HTTP 422, and a
1437
- before-change trigger that throws it rejects the write like any other failure.
2173
+ An after-change trigger handler or a job handler throws it to report a temporary
2174
+ failure, and Cogover runs the handler again later (see
2175
+ [After-change execution rules](#after-change-execution-rules) and
2176
+ [Job execution rules](#job-execution-rules)). Anywhere else it has no special
2177
+ meaning: a script that lets it escape returns HTTP 422, and a before-change trigger
2178
+ that throws it rejects the write like any other failure.
2179
+
2180
+ `jobs.enqueue`, `secrets.get`, and `crypto` fail with `ValidationError`,
2181
+ `PermissionDeniedError`, or `RateLimitError` as described in their sections, and
2182
+ with `CogoverApiError` whose `code` is `JOBS_DISABLED` or `SECRETS_DISABLED` when
2183
+ the feature is not enabled for the Workspace. `crypto.aesDecrypt` and
2184
+ `crypto.rsaDecrypt` throw `CogoverApiError` with `code: "DECRYPTION_FAILED"` when
2185
+ the ciphertext cannot be decrypted.
1438
2186
 
1439
2187
  Scripts can catch `CogoverApiError`, inspect `error.r`, and return their own client
1440
2188
  error, such as `{ r: 1001, msg: "You cannot update this order." }`, without exposing