@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.
@@ -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 `crypto.hmacSha256` 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()`. `crypto.sha256`,
624
+ `crypto.hmacSha256` with an explicit key, `crypto.randomBytes`,
625
+ `crypto.randomUUID`, and `crypto.timingSafeEqual` remain available.
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,182 @@ 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 data with a secret without reading it, use
1126
+ `crypto.hmacSha256({ secret: name }, data)`.
1127
+
1128
+ ## Cryptography
1129
+
1130
+ `crypto` provides hashing, message authentication, and randomness through
1131
+ Cogover's managed implementation. Import it from `@cogover/sdk` or read it from
1132
+ `context.crypto`; both are the same frozen object.
1133
+
1134
+ ```typescript
1135
+ const crypto: CryptoApi;
1136
+
1137
+ interface CryptoApi {
1138
+ sha256(data: string | Uint8Array, encoding?: "hex" | "base64"): Promise<string>;
1139
+ hmacSha256(
1140
+ key: string | Uint8Array | { readonly secret: string },
1141
+ data: string | Uint8Array,
1142
+ encoding?: "hex" | "base64",
1143
+ ): Promise<string>;
1144
+ randomBytes(length: number): Promise<Uint8Array>;
1145
+ randomUUID(): Promise<string>;
1146
+ timingSafeEqual(a: string | Uint8Array, b: string | Uint8Array): boolean;
1147
+ }
1148
+ ```
1149
+
1150
+ ```typescript
1151
+ import { crypto } from "@cogover/sdk";
1152
+
1153
+ const digest = await crypto.sha256(JSON.stringify(payload));
1154
+ const signature = await crypto.hmacSha256({ secret: "webhook_secret" }, request.rawBody ?? "");
1155
+ if (!crypto.timingSafeEqual(signature, request.headers["x-signature"] ?? "")) {
1156
+ return response.empty({ status: 401 });
1157
+ }
1158
+ const token = await crypto.randomUUID();
1159
+ ```
1160
+
1161
+ - `sha256(data, encoding?)` returns the SHA-256 digest of `data`. A string is
1162
+ hashed as UTF-8; a `Uint8Array` is hashed as is. `encoding` is `"hex"` (default)
1163
+ or `"base64"`.
1164
+ - `hmacSha256(key, data, encoding?)` returns the HMAC-SHA256 of `data`. The key is a
1165
+ non-empty string (UTF-8), a non-empty `Uint8Array`, or `{ secret: name }` to use
1166
+ a project secret without reading its value; the named secret must be readable by
1167
+ `secrets.get` in the same context and counts as one secret read.
1168
+ - `randomBytes(length)` returns `length` cryptographically secure random bytes;
1169
+ `length` is an integer from 1 through 1024.
1170
+ - `randomUUID()` returns a random version 4 UUID such as
1171
+ `"3f9c2d6e-8b1a-4c7d-9e2f-1a2b3c4d5e6f"`.
1172
+ - `timingSafeEqual(a, b)` compares two strings or byte arrays in constant time and
1173
+ returns `false` for different lengths. Strings are compared as UTF-8 bytes. Use
1174
+ it for every comparison of a signature, token, or key.
1175
+
1176
+ `data` and an explicit key are limited to 256 KiB; larger values and invalid
1177
+ arguments throw `ValidationError` before the call. Every operation except
1178
+ `timingSafeEqual` is a capability call and counts towards the invocation's limits.
1179
+ The operations work in every context, including before-change triggers, except that
1180
+ a `{ secret }` key follows the rules of `secrets.get`. This version supports
1181
+ SHA-256 only.
1182
+
1183
+ ## Inbound webhooks
1184
+
1185
+ An administrator can create an **inbound access** for a project so that an external
1186
+ system calls a route without a Cogover user session. The external system receives
1187
+ a URL of the form
1188
+
1189
+ ```text
1190
+ https://{WORKSPACE_DOMAIN}/api/v1/ts-projects/{projectSlug}/hooks/{inboundId}/{route}
1191
+ ```
1192
+
1193
+ and authenticates each call with the inbound key or the HMAC signature that was
1194
+ configured for the inbound access. Cogover verifies the key or signature, applies
1195
+ the rate limit, and rejects the call before any project code runs. A route handler
1196
+ sees such a call as `request.path === "/hooks/{route}"`: register webhook routes
1197
+ under `/hooks/` and the inbound ID is not part of the path.
1198
+
1199
+ ```typescript
1200
+ import { createRouter } from "@cogover/sdk";
1201
+
1202
+ const router = createRouter();
1203
+ router.post("/hooks/payments", async ({ request, invocation, crypto, jobs, response }) => {
1204
+ if (invocation.identity !== "inbound") return response.empty({ status: 403 });
1205
+
1206
+ // Optional: verify the external system's own signature over the raw body.
1207
+ const expected = await crypto.hmacSha256({ secret: "payment_signing_secret" }, request.rawBody ?? "");
1208
+ if (!crypto.timingSafeEqual(expected, request.headers["x-payment-signature"] ?? "")) {
1209
+ return response.empty({ status: 401 });
1210
+ }
1211
+
1212
+ const event = request.body as { id: string; orderId: string };
1213
+ await jobs.enqueue("sync_payment", event, { idempotencyKey: `payment:${event.id}` });
1214
+ return response.json({ received: true }, { status: 202 });
1215
+ });
1216
+ export default router.toHandler();
1217
+ ```
1218
+
1219
+ - **Identity.** `invocation.identity` is `"inbound"`, `invocation.user` is `null`,
1220
+ and `invocation.inbound` holds the `id`, `name`, and authentication `mode` of the
1221
+ inbound access. `data.object()` acts as the system identity and works only if the
1222
+ project's approved identity policy sets `allowInternalSystem: true`; otherwise its
1223
+ calls throw `PermissionDeniedError` with `details.reason` `"IDENTITY_NOT_GRANTED"`.
1224
+ `data.asUser()` and `data.asSystem()` follow the identity policy as usual.
1225
+ - **Body.** The request body is limited to 256 KiB. When it is a JSON object it is
1226
+ `request.body`; a form, text, or other body leaves `request.body` empty (`{}`).
1227
+ `request.rawBody` always holds the body exactly as received, as a UTF-8 string,
1228
+ and `request.contentType` the request's `Content-Type`, so a handler can verify a
1229
+ signature or parse another format itself.
1230
+ - **Response.** The handler's return value and the `response` helpers work as for
1231
+ any route. Keep the handler short: acknowledge the event and enqueue a job for
1232
+ the actual work, so that the external system gets a quick answer and retries
1233
+ cannot overlap with slow processing.
1234
+ - **Retries.** External systems usually retry a webhook that did not receive a
1235
+ 2xx response, so a handler may see the same event more than once. Use the event's
1236
+ own identifier as the `idempotencyKey` of the job it enqueues, or as a state key.
1237
+ An `Idempotency-Key` request header works as for any route.
1238
+
752
1239
  ## Record API
753
1240
 
754
1241
  ```typescript
@@ -1430,11 +1917,17 @@ there was no server response, such as local SDK validation. The original message
1430
1917
  remains in `error.message`.
1431
1918
 
1432
1919
  `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.
1920
+ An after-change trigger handler or a job handler throws it to report a temporary
1921
+ failure, and Cogover runs the handler again later (see
1922
+ [After-change execution rules](#after-change-execution-rules) and
1923
+ [Job execution rules](#job-execution-rules)). Anywhere else it has no special
1924
+ meaning: a script that lets it escape returns HTTP 422, and a before-change trigger
1925
+ that throws it rejects the write like any other failure.
1926
+
1927
+ `jobs.enqueue`, `secrets.get`, and `crypto` fail with `ValidationError`,
1928
+ `PermissionDeniedError`, or `RateLimitError` as described in their sections, and
1929
+ with `CogoverApiError` whose `code` is `JOBS_DISABLED` or `SECRETS_DISABLED` when
1930
+ the feature is not enabled for the Workspace.
1438
1931
 
1439
1932
  Scripts can catch `CogoverApiError`, inspect `error.r`, and return their own client
1440
1933
  error, such as `{ r: 1001, msg: "You cannot update this order." }`, without exposing