@cogover/sdk 0.11.0 → 0.12.1

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.
Files changed (41) hide show
  1. package/README.md +65 -21
  2. package/dist/crypto.js +89 -46
  3. package/dist/data.js +4 -1
  4. package/dist/email.d.ts +77 -0
  5. package/dist/email.js +192 -0
  6. package/dist/index.d.ts +2 -0
  7. package/dist/internal/base64.js +76 -27
  8. package/dist/internal/bridge.js +41 -3
  9. package/dist/internal/job-config.js +7 -1
  10. package/dist/internal/job-runtime.js +4 -0
  11. package/dist/internal/messaging.js +75 -0
  12. package/dist/internal/trigger-runtime.js +5 -0
  13. package/dist/internal/utf8.js +18 -17
  14. package/dist/jobs.d.ts +4 -0
  15. package/dist/locks.js +13 -3
  16. package/dist/logger.js +47 -1
  17. package/dist/notifications.d.ts +56 -0
  18. package/dist/notifications.js +92 -0
  19. package/dist/org.js +14 -14
  20. package/dist/records.d.ts +13 -0
  21. package/dist/response.js +21 -1
  22. package/dist/router.js +2 -0
  23. package/dist/schema.d.ts +1 -0
  24. package/dist/script.d.ts +4 -0
  25. package/dist/script.js +11 -3
  26. package/dist/trigger.d.ts +6 -0
  27. package/docs/en/api-reference/background-jobs.md +288 -0
  28. package/docs/en/api-reference/cryptography.md +317 -0
  29. package/docs/en/api-reference/fetch-and-secrets.md +184 -0
  30. package/docs/en/api-reference/inbound-webhooks.md +65 -0
  31. package/docs/en/api-reference/notifications-and-email.md +317 -0
  32. package/docs/en/api-reference/organization-structure.md +304 -0
  33. package/docs/en/api-reference/overview.md +198 -0
  34. package/docs/en/api-reference/push-messages.md +115 -0
  35. package/docs/en/api-reference/record-triggers.md +469 -0
  36. package/docs/en/api-reference/records.md +447 -0
  37. package/docs/en/api-reference/scripts-and-routes.md +354 -0
  38. package/docs/en/api-reference/state-and-locks.md +162 -0
  39. package/docs/en/usage-guide.md +218 -19
  40. package/package.json +1 -1
  41. package/docs/en/api-reference.md +0 -2619
@@ -0,0 +1,288 @@
1
+ # `@cogover/sdk` API reference: Background jobs
2
+
3
+ This page is part of the [`@cogover/sdk` API reference](overview.md).
4
+
5
+ ## Background jobs
6
+
7
+ A background job runs project code outside an HTTP request: enqueued by a script, a
8
+ trigger, another job, or an administrator, or started by a cron schedule. Declare
9
+ each job with `defineJob` and list the results in the project's named `jobs`
10
+ export. The default export is still the HTTP handler and is optional in a project
11
+ that only declares jobs and triggers.
12
+
13
+ This example assumes that `workspace.d.ts` declares the `order` Object and the
14
+ fields used below.
15
+
16
+ ```typescript
17
+ import { defineJob } from "@cogover/sdk";
18
+
19
+ interface RecalcPayload {
20
+ cursor?: string;
21
+ }
22
+
23
+ export const jobs = [
24
+ // Enqueued by a route or a trigger; walks all orders one page per run.
25
+ defineJob<RecalcPayload>({
26
+ key: "recalc_totals",
27
+ name: "Recalculate order totals",
28
+ timeoutMs: 60_000,
29
+ }, async ({ payload, data, jobs, log }) => {
30
+ const orders = data.object("order");
31
+ const page = await orders.records.list({
32
+ fields: ["subtotal", "tax"],
33
+ limit: 200,
34
+ ...(payload?.cursor ? { cursor: payload.cursor } : {}),
35
+ });
36
+ for (const order of page.items) {
37
+ await orders.records.update(order.id, {
38
+ total: (order.fields.subtotal ?? 0) + (order.fields.tax ?? 0),
39
+ });
40
+ }
41
+ if (page.nextCursor) {
42
+ // Continue with the next page in a new run instead of one long run.
43
+ await jobs.enqueue("recalc_totals", { cursor: page.nextCursor });
44
+ return;
45
+ }
46
+ log.info("Order totals recalculated");
47
+ }),
48
+
49
+ // Runs every day at 02:00 in the given time zone.
50
+ defineJob({
51
+ key: "cancel_stale_orders",
52
+ schedule: { cron: "0 2 * * *", timezone: "Asia/Ho_Chi_Minh" },
53
+ }, async ({ data }) => {
54
+ const orders = data.object("order");
55
+ const stale = await orders.records.list({
56
+ where: orders.fields.status.eq("new"),
57
+ fields: ["status"],
58
+ limit: 200,
59
+ });
60
+ for (const order of stale.items) {
61
+ await orders.records.update(order.id, { status: "cancelled" });
62
+ }
63
+ }),
64
+ ];
65
+ ```
66
+
67
+ Cogover reads the job configuration when a project version is published and applies
68
+ it while that version is active: `jobs.enqueue` accepts only the keys declared by the
69
+ active version, and schedules run only while their version is active. Deactivating
70
+ the project removes its schedules. A project can declare at most 50 jobs.
71
+
72
+ ### `defineJob(config, handler): JobDefinition`
73
+
74
+ ```typescript
75
+ function defineJob<
76
+ Payload = unknown,
77
+ Schema extends object = EffectiveWorkspaceObjects,
78
+ >(config: JobConfig, handler: JobHandler<Payload, Schema>): JobDefinition;
79
+ ```
80
+
81
+ `Payload` is the type of the value passed to `jobs.enqueue`; it is not validated at
82
+ run time, so treat the payload like request input. `defineJob` validates the
83
+ configuration immediately and throws `ValidationError` for any violation, for an
84
+ unknown configuration key, or for a handler that is not a function. It returns a
85
+ frozen `JobDefinition`.
86
+
87
+ ```typescript
88
+ interface JobConfig {
89
+ readonly key: string;
90
+ readonly name?: string;
91
+ readonly timeoutMs?: number;
92
+ readonly maxAttempts?: number;
93
+ readonly schedule?: JobSchedule;
94
+ }
95
+
96
+ interface JobSchedule {
97
+ readonly cron: string;
98
+ readonly timezone?: string;
99
+ }
100
+ ```
101
+
102
+ | Option | Required | Rules and meaning |
103
+ |---|---|---|
104
+ | `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. |
105
+ | `name` | No | Display name of at most 250 characters. Defaults to `key`. |
106
+ | `timeoutMs` | No | Integer from 1000 through 60000; defaults to `30000`. Time budget of one attempt. |
107
+ | `maxAttempts` | No | Integer from 1 through 10; defaults to `5`. Total number of attempts of one run, including the first. |
108
+ | `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"`. |
109
+
110
+ A cron field is `*`, a number, a range `a-b`, a list `a,b`, a step `*/n`, or a
111
+ stepped range `a-b/n`; the fields accept minutes 0–59, hours 0–23, days 1–31,
112
+ months 1–12, and weekdays 0–7 where both 0 and 7 are Sunday. Names such as `MON`,
113
+ the characters `L`, `W`, `#`, and `?`, and macros such as `@daily` are not supported.
114
+ The shortest period is one minute. Whitespace between the fields is normalized to
115
+ one space in the manifest, and the normalized expression may have at most 128
116
+ characters; a longer one throws `ValidationError`. Cogover stores the time zone in its
117
+ normalized form, so an offset such as `UTC+7` is listed as `UTC+07:00` in the project's
118
+ schedules.
119
+
120
+ ### `JobDefinition` and `JobManifest`
121
+
122
+ ```typescript
123
+ interface JobManifest {
124
+ readonly key: string;
125
+ readonly name?: string;
126
+ readonly timeoutMs: number;
127
+ readonly maxAttempts: number;
128
+ readonly schedule?: { readonly cron: string; readonly timezone: string };
129
+ }
130
+
131
+ interface JobDefinition {
132
+ readonly key: string;
133
+ readonly config: JobManifest;
134
+ readonly __cogoverJobHandler: SandboxHandler;
135
+ }
136
+ ```
137
+
138
+ `config` is the normalized configuration as deeply frozen plain JSON, with every
139
+ default applied: `timeoutMs: 30000`, `maxAttempts: 5`, and `schedule.timezone:
140
+ "UTC"`. Optional settings that were not provided are absent. It is detached from the
141
+ object passed to `defineJob`, so later edits of that object have no effect.
142
+ `__cogoverJobHandler` is reserved for Cogover; project code does not call it.
143
+
144
+ ### Job handler context
145
+
146
+ ```typescript
147
+ type JobHandler<
148
+ Payload = unknown,
149
+ Schema extends object = EffectiveWorkspaceObjects,
150
+ > = (context: JobContext<Payload, Schema>) => void | Promise<void>;
151
+
152
+ interface JobContext<Payload = unknown, Schema extends object = EffectiveWorkspaceObjects> {
153
+ readonly job: JobInfo;
154
+ readonly payload: Payload | null;
155
+ readonly invocation: InvocationContext;
156
+ readonly data: DataApi<Schema>;
157
+ readonly schema: SchemaApi<Schema>;
158
+ readonly log: ScriptLogger;
159
+ readonly state: ProjectState;
160
+ readonly locks: DistributedLocks;
161
+ readonly notifications: NotificationsApi;
162
+ readonly email: EmailApi<Schema>;
163
+ readonly jobs: JobsApi;
164
+ readonly secrets: SecretsApi;
165
+ readonly crypto: CryptoApi;
166
+ readonly org: OrgApi;
167
+ }
168
+
169
+ interface JobInfo {
170
+ readonly id: string;
171
+ readonly key: string;
172
+ readonly attempt: number;
173
+ readonly maxAttempts: number;
174
+ readonly source: "enqueue" | "schedule";
175
+ readonly runAt: number;
176
+ readonly enqueuedAt?: number;
177
+ }
178
+ ```
179
+
180
+ A handler may be synchronous or asynchronous; its return value is ignored. `data`,
181
+ `schema`, `log`, `invocation`, `state`, `locks`, `notifications`, `email`, `jobs`,
182
+ `secrets`, `crypto`, and `org` are the same APIs that scripts receive. A job context has
183
+ no `input`, `request`, `response`, or `push`.
184
+
185
+ - `job.id` identifies the run and stays the same across its attempts; use it as the
186
+ idempotency key of external calls. `job.attempt` starts at 1.
187
+ - `job.source` is `"enqueue"` for a run created by `jobs.enqueue` or by an
188
+ administrator and `"schedule"` for a run created by the job's schedule. `job.runAt`
189
+ is when the run became due and `job.enqueuedAt` when it was enqueued; both are Unix
190
+ milliseconds, and `enqueuedAt` is absent for a scheduled run.
191
+ - `payload` is the JSON value passed to `jobs.enqueue`, or `null` when none was
192
+ passed or the run is scheduled. It is plain, mutable data.
193
+
194
+ ### `jobs.enqueue(jobKey, payload?, options?): Promise<EnqueueResult>`
195
+
196
+ ```typescript
197
+ interface JobsApi {
198
+ enqueue(jobKey: string, payload?: unknown, options?: EnqueueOptions): Promise<EnqueueResult>;
199
+ }
200
+
201
+ interface EnqueueOptions {
202
+ readonly delayMs?: number;
203
+ readonly runAt?: number;
204
+ readonly idempotencyKey?: string;
205
+ }
206
+
207
+ interface EnqueueResult {
208
+ readonly runId: string;
209
+ readonly duplicate: boolean;
210
+ }
211
+ ```
212
+
213
+ ```typescript
214
+ const { runId, duplicate } = await jobs.enqueue("sync_order", { orderId: order.id }, {
215
+ delayMs: 60_000,
216
+ idempotencyKey: `sync_order:${order.id}:${order.system.updatedAt}`,
217
+ });
218
+ ```
219
+
220
+ `jobKey` must be a job declared by the active version; otherwise Cogover throws
221
+ `ValidationError`. `payload` is any JSON value of at most 65,536 UTF-8 bytes in its
222
+ `JSON.stringify` form, in which a quote, a backslash, or a control character counts as
223
+ its escape sequence; `undefined` and `null` enqueue the run without a payload. Values that
224
+ JSON would silently change, such as `NaN` or class instances, are rejected with
225
+ `ValidationError`. `delayMs` is an integer from 0 through 2,592,000,000 (30 days)
226
+ and `runAt` a Unix millisecond time at most 30 days ahead; pass one or neither, not
227
+ both. `idempotencyKey` starts with a letter or digit, contains letters, digits, `.`,
228
+ `_`, `:`, or `-`, and is at most 128 characters: a second enqueue of the same job
229
+ with the same key while the earlier run is still kept returns that run with
230
+ `duplicate: true` instead of creating another. Run history is kept for 7 days.
231
+
232
+ `enqueue` works in scripts and routes, after-change triggers, jobs, and inbound
233
+ webhook calls. A before-change trigger is refused with `PermissionDeniedError`
234
+ (`details.reason === "TRIGGER_READ_ONLY"`), and so is a local development session
235
+ without write permission (`"DEVELOPMENT_SESSION_READ_ONLY"`). One invocation may
236
+ enqueue at most 50 runs, and a project may have at most 10,000 runs waiting or
237
+ running; beyond that `RateLimitError` is thrown. An HTTP route or a trigger reaches
238
+ its budget of 20 capability calls first (see
239
+ [Execution limits](overview.md#execution-limits)), so there the limit of 50 enqueues
240
+ is not reached. When jobs are not enabled for the Workspace, the error is
241
+ `CogoverApiError` with `code: "JOBS_DISABLED"`.
242
+
243
+ ### Job execution rules
244
+
245
+ - **Identity.** A run enqueued from a script, route, or trigger runs as the user of
246
+ that invocation: `invocation` describes that user and `data.object()` acts with
247
+ that user's permissions. A run that a Super Admin enqueues through the job
248
+ management API likewise runs as that Super Admin, and the run history shows it with
249
+ `enqueuedBy: "management"`. A scheduled run and a run enqueued from an inbound
250
+ webhook call have no user: `invocation.identity`
251
+ is `"system"`, and `data.object()` works only if the project's approved identity
252
+ policy sets `allowInternalSystem: true`; otherwise its calls throw
253
+ `PermissionDeniedError` with `details.reason` `"IDENTITY_NOT_GRANTED"`.
254
+ `data.asUser()` and `data.asSystem()` follow the identity policy as usual.
255
+ - **Capabilities.** A job may read and write records, call `fetch`, use `state` and
256
+ `locks`, send notifications and email, enqueue jobs, read secrets, and use `crypto`,
257
+ within the runtime limits of the job lane.
258
+ - **Time.** Each attempt must finish within `timeoutMs`. Work that needs longer is
259
+ split: process one page, save the cursor, and enqueue the same job again with the
260
+ cursor in the payload, as in the example above.
261
+ - **At least once.** Cogover does not guarantee that a run executes exactly once: an
262
+ attempt that was interrupted, for example by a restart, is started again. Make
263
+ every handler idempotent. `job.id` identifies the run across attempts, and
264
+ `idempotencyKey` on `enqueue` prevents duplicate runs.
265
+ - **Retries.** Throw `RetryableError` when the handler fails for a temporary reason,
266
+ such as an external service that is unavailable. Cogover runs the attempt again
267
+ later, waiting longer before each attempt, from a few seconds to about half an
268
+ hour, until `maxAttempts` attempts have been made. An attempt that exceeds
269
+ `timeoutMs`, or that Cogover could not run for a temporary reason, is retried the
270
+ same way. Any other error ends the run as failed: the failure is logged and the
271
+ handler does not run again for that run.
272
+ - **Order and concurrency.** Runs execute in no guaranteed order, and two runs of the
273
+ same project, even of the same job, may execute at the same time. Use `locks` when
274
+ a section must not run concurrently, and delay through `delayMs` or `runAt` rather
275
+ than by waiting inside the handler.
276
+ - **Loops end.** Record writes made by a run carry the automation budget of the
277
+ invocation that enqueued it (a scheduled run and an administrator's enqueue start
278
+ with the full budget of 10 steps), so a chain of jobs and triggers started by
279
+ record writes ends the same way as a trigger chain. Enqueueing a job does not use
280
+ a step: a job that enqueues itself must stop on its own, for example when the
281
+ cursor is exhausted.
282
+
283
+ A scheduled job creates one run for each time the schedule matches, in the
284
+ schedule's time zone; the run may start a little later than the scheduled minute
285
+ under load. A slot that is missed while the project is inactive is not run later.
286
+ A run is still created when the previous scheduled run has not finished, so a
287
+ schedule whose work can take longer than its period should guard itself with a
288
+ lock.
@@ -0,0 +1,317 @@
1
+ # `@cogover/sdk` API reference: Cryptography
2
+
3
+ This page is part of the [`@cogover/sdk` API reference](overview.md).
4
+
5
+ ## Cryptography
6
+
7
+ `crypto` provides hashing, message authentication, randomness, AES and RSA
8
+ encryption, and RSA and ECDSA signatures through Cogover's managed
9
+ implementation. Import it from `@cogover/sdk` or read it from `context.crypto`;
10
+ both are the same frozen object.
11
+
12
+ ```typescript
13
+ const crypto: CryptoApi;
14
+
15
+ type BinaryEncoding = "base64" | "base64url" | "hex";
16
+ type DecryptOutput = "utf8" | "bytes" | BinaryEncoding;
17
+
18
+ interface SecretKeyReference {
19
+ readonly secret: string;
20
+ }
21
+ type AesKey =
22
+ | string
23
+ | Uint8Array
24
+ | (SecretKeyReference & { readonly encoding?: "utf8" | "base64" | "hex" });
25
+ type AsymmetricKey = string | SecretKeyReference;
26
+
27
+ interface CryptoApi {
28
+ sha256(data: string | Uint8Array, encoding?: "hex" | "base64"): Promise<string>;
29
+ hmacSha256(
30
+ key: string | Uint8Array | { readonly secret: string },
31
+ data: string | Uint8Array,
32
+ encoding?: "hex" | "base64",
33
+ ): Promise<string>;
34
+ randomBytes(length: number): Promise<Uint8Array>;
35
+ randomUUID(): Promise<string>;
36
+ timingSafeEqual(a: string | Uint8Array, b: string | Uint8Array): boolean;
37
+
38
+ aesEncrypt(key: AesKey, data: string | Uint8Array, options?: AesEncryptOptions): Promise<AesEncryptResult>;
39
+ aesDecrypt(key: AesKey, ciphertext: string | Uint8Array, options: AesDecryptOptions): Promise<string>;
40
+ aesDecrypt(
41
+ key: AesKey,
42
+ ciphertext: string | Uint8Array,
43
+ options: AesDecryptOptions & { readonly output: "bytes" },
44
+ ): Promise<Uint8Array>;
45
+ rsaEncrypt(publicKey: AsymmetricKey, data: string | Uint8Array, options?: RsaEncryptOptions): Promise<string>;
46
+ rsaDecrypt(privateKey: AsymmetricKey, ciphertext: string | Uint8Array, options?: RsaDecryptOptions): Promise<string>;
47
+ rsaDecrypt(
48
+ privateKey: AsymmetricKey,
49
+ ciphertext: string | Uint8Array,
50
+ options: RsaDecryptOptions & { readonly output: "bytes" },
51
+ ): Promise<Uint8Array>;
52
+ sign(
53
+ algorithm: SignatureAlgorithm,
54
+ privateKey: AsymmetricKey,
55
+ data: string | Uint8Array,
56
+ options?: SignatureOptions,
57
+ ): Promise<string>;
58
+ verify(
59
+ algorithm: SignatureAlgorithm,
60
+ publicKey: AsymmetricKey,
61
+ data: string | Uint8Array,
62
+ signature: string | Uint8Array,
63
+ options?: SignatureOptions,
64
+ ): Promise<boolean>;
65
+ }
66
+ ```
67
+
68
+ `aesDecrypt` and `rsaDecrypt` return a string unless `output` is `"bytes"`; when
69
+ `output` is only known as a `DecryptOutput`, the result type is
70
+ `string | Uint8Array`.
71
+
72
+ ```typescript
73
+ import { crypto } from "@cogover/sdk";
74
+
75
+ const digest = await crypto.sha256(JSON.stringify(payload));
76
+ const signature = await crypto.hmacSha256({ secret: "webhook_secret" }, request.rawBody ?? "");
77
+ if (!crypto.timingSafeEqual(signature, request.headers["x-signature"] ?? "")) {
78
+ return response.empty({ status: 401 });
79
+ }
80
+ const token = await crypto.randomUUID();
81
+ ```
82
+
83
+ ### Hashing, HMAC, and randomness
84
+
85
+ - `sha256(data, encoding?)` returns the SHA-256 digest of `data`. A string is
86
+ hashed as UTF-8; a `Uint8Array` is hashed as is. `encoding` is `"hex"` (default)
87
+ or `"base64"`.
88
+ - `hmacSha256(key, data, encoding?)` returns the HMAC-SHA256 of `data`. The key is a
89
+ non-empty string (UTF-8), a non-empty `Uint8Array`, or `{ secret: name }` to use
90
+ a project secret without reading its value.
91
+ - `randomBytes(length)` returns `length` cryptographically secure random bytes;
92
+ `length` is an integer from 1 through 1024.
93
+ - `randomUUID()` returns a random version 4 UUID such as
94
+ `"3f9c2d6e-8b1a-4c7d-9e2f-1a2b3c4d5e6f"`.
95
+ - `timingSafeEqual(a, b)` compares two strings or byte arrays in constant time and
96
+ returns `false` for different lengths. Strings are compared as UTF-8 bytes. Use
97
+ it for every comparison of a signature, token, or key.
98
+
99
+ ### Keys
100
+
101
+ Every key can be given in the call or as `{ secret: name }`. A secret key is
102
+ resolved by Cogover and its value never reaches project code; the named secret
103
+ must be readable by `secrets.get` in the same context and counts as one secret
104
+ read. Store every private key and every AES key as a project secret; a key written
105
+ in source code is visible to everyone who can read the project.
106
+
107
+ - **AES keys** are 16, 24, or 32 bytes (AES-128, AES-192, AES-256). A string is
108
+ used as its UTF-8 bytes and a `Uint8Array` as is. For a secret, `encoding` states
109
+ how the secret's value holds the key: `"utf8"` (default) uses the text itself,
110
+ and `"base64"` or `"hex"` decode it first, ignoring surrounding whitespace.
111
+ - **RSA and EC keys** (`AsymmetricKey`) are PEM text, or the base64 body of one
112
+ without the `-----BEGIN` lines (DER as `PUBLIC KEY` for a public key and as
113
+ `PRIVATE KEY` for a private key). Text before the PEM block and an
114
+ `EC PARAMETERS` block are ignored.
115
+
116
+ | Key | Accepted PEM types |
117
+ |---|---|
118
+ | Public key (`rsaEncrypt`, `verify`) | `PUBLIC KEY` (SubjectPublicKeyInfo), `RSA PUBLIC KEY` (PKCS #1), `CERTIFICATE` (X.509; only its public key is used) |
119
+ | Private key (`rsaDecrypt`, `sign`) | `PRIVATE KEY` (PKCS #8), `RSA PRIVATE KEY` (PKCS #1), `EC PRIVATE KEY` (SEC1) |
120
+
121
+ RSA keys must be 2048 to 4096 bits. EC keys must use the P-256, P-384, or P-521
122
+ curve. Encrypted private keys (`ENCRYPTED PRIVATE KEY`, or PEM with
123
+ `Proc-Type` headers) and OpenSSH keys are not supported; store the unencrypted
124
+ PKCS #8 key as a secret instead. Key text is limited to 16,384 characters. A
125
+ certificate is not checked for expiry, revocation, or its issuer: it is only a
126
+ container for the public key.
127
+
128
+ ### `crypto.aesEncrypt(key, data, options?): Promise<AesEncryptResult>`
129
+
130
+ ```typescript
131
+ type AesMode = "GCM" | "CBC";
132
+
133
+ interface AesEncryptOptions {
134
+ readonly mode?: AesMode; // Default "GCM"
135
+ readonly iv?: string | Uint8Array; // Default: random
136
+ readonly aad?: string | Uint8Array; // GCM only
137
+ readonly separateTag?: boolean; // GCM only, default false
138
+ readonly encoding?: BinaryEncoding; // Default "base64"
139
+ }
140
+
141
+ interface AesEncryptResult {
142
+ readonly ciphertext: string;
143
+ readonly iv: string;
144
+ readonly tag?: string; // Only with separateTag
145
+ }
146
+ ```
147
+
148
+ Encrypts `data` (a string is encoded as UTF-8) and returns the ciphertext and IV in
149
+ `encoding`.
150
+
151
+ - `"GCM"` (default) is authenticated encryption: decryption detects any change to
152
+ the ciphertext, IV, tag, or `aad`. `ciphertext` is the encrypted data followed by
153
+ the 16-byte authentication tag, the form used by Java, .NET, and Web Crypto.
154
+ With `separateTag: true` the tag is returned in `tag` instead, as systems built
155
+ on Node.js or OpenSSL usually expect.
156
+ - `"CBC"` uses PKCS #7 padding. It does not detect changes to the ciphertext; use
157
+ it only when an external system requires it, and authenticate the ciphertext
158
+ separately, for example with `hmacSha256`.
159
+ - Without `iv`, a random IV is generated: 12 bytes for GCM and 16 bytes for CBC.
160
+ A given `iv` must be 12 to 16 bytes for GCM and exactly 16 bytes for CBC; a
161
+ string `iv` is decoded with `encoding`. **Never use the same IV twice with the
162
+ same GCM key**: doing so breaks both confidentiality and authentication. Pass
163
+ an IV only when an external system dictates it.
164
+ - `aad` is additional data that is authenticated but not encrypted, such as a
165
+ record ID; a string is encoded as UTF-8. The same `aad` must be given to
166
+ decryption.
167
+
168
+ ### `crypto.aesDecrypt(key, ciphertext, options): Promise<string | Uint8Array>`
169
+
170
+ ```typescript
171
+ interface AesDecryptOptions {
172
+ readonly mode?: AesMode; // Default "GCM"
173
+ readonly iv: string | Uint8Array;
174
+ readonly tag?: string | Uint8Array; // GCM only, when not appended to the ciphertext
175
+ readonly aad?: string | Uint8Array; // GCM only
176
+ readonly encoding?: BinaryEncoding; // Of a string ciphertext, iv, and tag; default "base64"
177
+ readonly output?: DecryptOutput; // Default "utf8"
178
+ }
179
+ ```
180
+
181
+ Decrypts an AES ciphertext. `iv` is required. In GCM mode, the last 16 bytes of
182
+ `ciphertext` are the tag unless `tag` is given. `output` selects the result:
183
+ `"utf8"` (default) decodes the plaintext as UTF-8 text and throws
184
+ `ValidationError` if it is not valid UTF-8, `"bytes"` returns a `Uint8Array`, and
185
+ `"base64"`, `"base64url"`, or `"hex"` return the plaintext bytes in that encoding.
186
+
187
+ A wrong key, IV, tag, or `aad`, a modified ciphertext, or invalid CBC padding
188
+ throws `CogoverApiError` with `code: "DECRYPTION_FAILED"`. The error is the same
189
+ for every cause, so that the result reveals nothing about the key or plaintext.
190
+
191
+ ```typescript
192
+ import { crypto, CogoverApiError, defineScript } from "@cogover/sdk";
193
+
194
+ export default defineScript(async ({ request }) => {
195
+ const { data, iv, tag } = request.body as { data: string; iv: string; tag: string };
196
+ try {
197
+ const json = await crypto.aesDecrypt({ secret: "partner_aes_key", encoding: "base64" }, data, { iv, tag });
198
+ return { payment: JSON.parse(json) };
199
+ } catch (error) {
200
+ if (error instanceof CogoverApiError && error.code === "DECRYPTION_FAILED") {
201
+ return { r: 1001, msg: "The payload could not be decrypted." };
202
+ }
203
+ throw error;
204
+ }
205
+ });
206
+ ```
207
+
208
+ ### `crypto.rsaEncrypt(publicKey, data, options?)` and `crypto.rsaDecrypt(privateKey, ciphertext, options?)`
209
+
210
+ ```typescript
211
+ type RsaPadding = "OAEP-SHA256" | "OAEP-SHA1" | "PKCS1";
212
+
213
+ interface RsaEncryptOptions {
214
+ readonly padding?: RsaPadding; // Default "OAEP-SHA256"
215
+ readonly encoding?: BinaryEncoding; // Of the ciphertext; default "base64"
216
+ }
217
+
218
+ interface RsaDecryptOptions {
219
+ readonly padding?: RsaPadding; // Default "OAEP-SHA256"
220
+ readonly encoding?: BinaryEncoding; // Of a string ciphertext; default "base64"
221
+ readonly output?: DecryptOutput; // Default "utf8"
222
+ }
223
+ ```
224
+
225
+ `rsaEncrypt` encrypts `data` (a string is encoded as UTF-8) with an RSA public key
226
+ and returns the ciphertext in `encoding`. `rsaDecrypt` decrypts it with the
227
+ matching private key and returns the plaintext as `output`, like `aesDecrypt`.
228
+
229
+ - `"OAEP-SHA256"` (default) is RSA-OAEP with SHA-256, and its mask generation
230
+ function MGF1 also uses SHA-256, as in Web Crypto, Node.js, and OpenSSL.
231
+ `"OAEP-SHA1"` uses SHA-1 for both. Some Java code written as
232
+ `OAEPWithSHA-256AndMGF1Padding` keeps MGF1 on SHA-1 and is compatible with
233
+ neither; ask the other system which digest its MGF1 uses.
234
+ - `"PKCS1"` is PKCS #1 v1.5 padding. Use it only when an external system requires
235
+ it.
236
+ - RSA encrypts only a small amount of data: at most the key size in bytes minus
237
+ 66 bytes for `"OAEP-SHA256"`, minus 42 for `"OAEP-SHA1"`, and minus 11 for
238
+ `"PKCS1"` — 190, 214, and 245 bytes for a 2048-bit key. Larger data throws
239
+ `ValidationError`. To send more, encrypt the data with `aesEncrypt` under a
240
+ random key from `randomBytes(32)` and encrypt only that key with `rsaEncrypt`.
241
+ - A decryption that fails for any reason throws `CogoverApiError` with
242
+ `code: "DECRYPTION_FAILED"`.
243
+
244
+ ```typescript
245
+ const cardToken = await crypto.rsaEncrypt({ secret: "bank_public_key" }, "4111111111111111");
246
+ const plain = await crypto.rsaDecrypt({ secret: "our_private_key" }, request.body.data as string);
247
+ ```
248
+
249
+ ### `crypto.sign(algorithm, privateKey, data, options?)` and `crypto.verify(algorithm, publicKey, data, signature, options?)`
250
+
251
+ ```typescript
252
+ type SignatureAlgorithm =
253
+ | "RSA-SHA1" | "RSA-SHA256" | "RSA-SHA384" | "RSA-SHA512"
254
+ | "RSA-PSS-SHA256" | "RSA-PSS-SHA384" | "RSA-PSS-SHA512"
255
+ | "ECDSA-SHA256" | "ECDSA-SHA384" | "ECDSA-SHA512";
256
+
257
+ interface SignatureOptions {
258
+ readonly encoding?: BinaryEncoding; // Of the signature; default "base64"
259
+ readonly signatureFormat?: "der" | "ieee-p1363"; // ECDSA only; default "der"
260
+ }
261
+ ```
262
+
263
+ `sign` signs `data` (a string is encoded as UTF-8) with a private key and returns
264
+ the signature in `encoding`. `verify` returns `true` when `signature` is a valid
265
+ signature of `data` for the public key, and `false` otherwise, including when the
266
+ signature cannot be decoded or has the wrong length; a signature normally comes
267
+ from the party being verified, so a malformed one is not an error. A signature
268
+ longer than 2,048 characters, or 1,024 bytes as a `Uint8Array`, is invalid without
269
+ being sent. An invalid key or algorithm still throws `ValidationError`, whatever the
270
+ signature.
271
+
272
+ - `RSA-SHA*` is RSASSA-PKCS1-v1_5 and requires an RSA key. `RSA-SHA1` exists only
273
+ to verify signatures of systems that still use it; do not use it for new
274
+ signatures.
275
+ - `RSA-PSS-SHA*` is RSASSA-PSS with MGF1 on the same digest and a salt as long as
276
+ the digest (32, 48, or 64 bytes), and requires an RSA key.
277
+ - `ECDSA-SHA*` requires an EC key. `signatureFormat` is `"der"` (ASN.1, used by
278
+ OpenSSL and Java) or `"ieee-p1363"` (the fixed-length `r || s` form used by JWT
279
+ and Web Crypto); it is rejected for RSA algorithms.
280
+
281
+ | JWT `alg` | `algorithm` | Options |
282
+ |---|---|---|
283
+ | `RS256`, `RS384`, `RS512` | `RSA-SHA256`, `RSA-SHA384`, `RSA-SHA512` | `{ encoding: "base64url" }` |
284
+ | `PS256`, `PS384`, `PS512` | `RSA-PSS-SHA256`, `RSA-PSS-SHA384`, `RSA-PSS-SHA512` | `{ encoding: "base64url" }` |
285
+ | `ES256`, `ES384`, `ES512` | `ECDSA-SHA256`, `ECDSA-SHA384`, `ECDSA-SHA512` | `{ encoding: "base64url", signatureFormat: "ieee-p1363" }` |
286
+
287
+ ```typescript
288
+ // Verify an ES256 JWT issued by a partner. Also check its claims (exp, iss, aud) before trusting it.
289
+ const [header, payload, signature] = token.split(".");
290
+ const valid = await crypto.verify("ECDSA-SHA256", { secret: "partner_jwt_public_key" },
291
+ `${header}.${payload}`, signature ?? "", { encoding: "base64url", signatureFormat: "ieee-p1363" });
292
+ if (!valid) return response.empty({ status: 401 });
293
+
294
+ // Sign a request to a bank that expects SHA256withRSA in base64.
295
+ const body = JSON.stringify(order);
296
+ const bankSignature = await crypto.sign("RSA-SHA256", { secret: "bank_signing_key" }, body);
297
+ ```
298
+
299
+ ### Limits and availability
300
+
301
+ `data`, `aad`, and an explicit HMAC key are limited to 256 KiB, and a ciphertext
302
+ to 256 KiB plus its tag; larger values and invalid arguments throw
303
+ `ValidationError` before the call. The whole call must also fit one capability
304
+ request of 262,144 bytes by default (see [Execution limits](overview.md#execution-limits)):
305
+ every argument is sent JSON-encoded in one request, and a `Uint8Array` is sent as
306
+ base64, which is a third larger. Binary data larger than about 190 KiB, or text data
307
+ close to 256 KiB together with other arguments, therefore throws `ValidationError`
308
+ before the call even though each value is within its own limit. The key, algorithm, and option errors that
309
+ Cogover detects, such as a key of the wrong size or type, also throw
310
+ `ValidationError`. Every operation except `timingSafeEqual` is a capability call
311
+ and counts towards the invocation's limits.
312
+
313
+ The operations work in every context, including before-change triggers, with a key
314
+ given in the call. A `{ secret }` key follows the rules of `secrets.get`: a
315
+ before-change trigger is refused with `PermissionDeniedError`
316
+ (`details.reason === "TRIGGER_READ_ONLY"`) and a local development session without
317
+ secret access with `details.reason === "SECRETS_NOT_ALLOWED"`.