@cogover/sdk 0.12.0 → 0.12.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -9
- package/dist/crypto.js +182 -69
- package/dist/data.js +4 -1
- package/dist/email.js +5 -3
- package/dist/internal/base64.js +92 -28
- package/dist/internal/bridge.js +41 -3
- package/dist/internal/job-config.js +7 -1
- package/dist/internal/utf8.js +18 -53
- package/dist/locks.js +13 -3
- package/dist/logger.js +47 -1
- package/dist/org.js +14 -14
- package/dist/records.d.ts +13 -0
- package/dist/response.js +21 -1
- package/dist/schema.d.ts +1 -0
- package/dist/script.js +7 -3
- package/docs/en/api-reference/background-jobs.md +288 -0
- package/docs/en/api-reference/cryptography.md +321 -0
- package/docs/en/api-reference/fetch-and-secrets.md +184 -0
- package/docs/en/api-reference/inbound-webhooks.md +65 -0
- package/docs/en/api-reference/notifications-and-email.md +317 -0
- package/docs/en/api-reference/organization-structure.md +304 -0
- package/docs/en/api-reference/overview.md +198 -0
- package/docs/en/api-reference/push-messages.md +115 -0
- package/docs/en/api-reference/record-triggers.md +469 -0
- package/docs/en/api-reference/records.md +447 -0
- package/docs/en/api-reference/scripts-and-routes.md +354 -0
- package/docs/en/api-reference/state-and-locks.md +162 -0
- package/docs/en/usage-guide.md +17 -14
- package/package.json +1 -1
- package/docs/en/api-reference.md +0 -2944
|
@@ -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,321 @@
|
|
|
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"`. Random bytes are fetched 1,024 at a
|
|
95
|
+
time, so one capability call covers 64 UUIDs.
|
|
96
|
+
- `timingSafeEqual(a, b)` compares two strings or byte arrays in constant time and
|
|
97
|
+
returns `false` for different lengths. Strings are compared as UTF-8 bytes. Each
|
|
98
|
+
value is limited to 256 KiB, a string measured in UTF-8 bytes; a larger one
|
|
99
|
+
throws `ValidationError`. Use it for every comparison of a signature, token, or
|
|
100
|
+
key.
|
|
101
|
+
|
|
102
|
+
### Keys
|
|
103
|
+
|
|
104
|
+
Every key can be given in the call or as `{ secret: name }`. A secret key is
|
|
105
|
+
resolved by Cogover and its value never reaches project code; the named secret
|
|
106
|
+
must be readable by `secrets.get` in the same context and counts as one secret
|
|
107
|
+
read. Store every private key and every AES key as a project secret; a key written
|
|
108
|
+
in source code is visible to everyone who can read the project.
|
|
109
|
+
|
|
110
|
+
- **AES keys** are 16, 24, or 32 bytes (AES-128, AES-192, AES-256). A string is
|
|
111
|
+
used as its UTF-8 bytes and a `Uint8Array` as is. For a secret, `encoding` states
|
|
112
|
+
how the secret's value holds the key: `"utf8"` (default) uses the text itself,
|
|
113
|
+
and `"base64"` or `"hex"` decode it first, ignoring surrounding whitespace.
|
|
114
|
+
- **RSA and EC keys** (`AsymmetricKey`) are PEM text, or the base64 body of one
|
|
115
|
+
without the `-----BEGIN` lines (DER as `PUBLIC KEY` for a public key and as
|
|
116
|
+
`PRIVATE KEY` for a private key). Text before the PEM block and an
|
|
117
|
+
`EC PARAMETERS` block are ignored.
|
|
118
|
+
|
|
119
|
+
| Key | Accepted PEM types |
|
|
120
|
+
|---|---|
|
|
121
|
+
| Public key (`rsaEncrypt`, `verify`) | `PUBLIC KEY` (SubjectPublicKeyInfo), `RSA PUBLIC KEY` (PKCS #1), `CERTIFICATE` (X.509; only its public key is used) |
|
|
122
|
+
| Private key (`rsaDecrypt`, `sign`) | `PRIVATE KEY` (PKCS #8), `RSA PRIVATE KEY` (PKCS #1), `EC PRIVATE KEY` (SEC1) |
|
|
123
|
+
|
|
124
|
+
RSA keys must be 2048 to 4096 bits. EC keys must use the P-256, P-384, or P-521
|
|
125
|
+
curve. Encrypted private keys (`ENCRYPTED PRIVATE KEY`, or PEM with
|
|
126
|
+
`Proc-Type` headers) and OpenSSH keys are not supported; store the unencrypted
|
|
127
|
+
PKCS #8 key as a secret instead. Key text is limited to 16,384 characters. A
|
|
128
|
+
certificate is not checked for expiry, revocation, or its issuer: it is only a
|
|
129
|
+
container for the public key.
|
|
130
|
+
|
|
131
|
+
### `crypto.aesEncrypt(key, data, options?): Promise<AesEncryptResult>`
|
|
132
|
+
|
|
133
|
+
```typescript
|
|
134
|
+
type AesMode = "GCM" | "CBC";
|
|
135
|
+
|
|
136
|
+
interface AesEncryptOptions {
|
|
137
|
+
readonly mode?: AesMode; // Default "GCM"
|
|
138
|
+
readonly iv?: string | Uint8Array; // Default: random
|
|
139
|
+
readonly aad?: string | Uint8Array; // GCM only
|
|
140
|
+
readonly separateTag?: boolean; // GCM only, default false
|
|
141
|
+
readonly encoding?: BinaryEncoding; // Default "base64"
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
interface AesEncryptResult {
|
|
145
|
+
readonly ciphertext: string;
|
|
146
|
+
readonly iv: string;
|
|
147
|
+
readonly tag?: string; // Only with separateTag
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Encrypts `data` (a string is encoded as UTF-8) and returns the ciphertext and IV in
|
|
152
|
+
`encoding`.
|
|
153
|
+
|
|
154
|
+
- `"GCM"` (default) is authenticated encryption: decryption detects any change to
|
|
155
|
+
the ciphertext, IV, tag, or `aad`. `ciphertext` is the encrypted data followed by
|
|
156
|
+
the 16-byte authentication tag, the form used by Java, .NET, and Web Crypto.
|
|
157
|
+
With `separateTag: true` the tag is returned in `tag` instead, as systems built
|
|
158
|
+
on Node.js or OpenSSL usually expect.
|
|
159
|
+
- `"CBC"` uses PKCS #7 padding. It does not detect changes to the ciphertext; use
|
|
160
|
+
it only when an external system requires it, and authenticate the ciphertext
|
|
161
|
+
separately, for example with `hmacSha256`.
|
|
162
|
+
- Without `iv`, a random IV is generated: 12 bytes for GCM and 16 bytes for CBC.
|
|
163
|
+
A given `iv` must be 12 to 16 bytes for GCM and exactly 16 bytes for CBC; a
|
|
164
|
+
string `iv` is decoded with `encoding`. **Never use the same IV twice with the
|
|
165
|
+
same GCM key**: doing so breaks both confidentiality and authentication. Pass
|
|
166
|
+
an IV only when an external system dictates it.
|
|
167
|
+
- `aad` is additional data that is authenticated but not encrypted, such as a
|
|
168
|
+
record ID; a string is encoded as UTF-8. The same `aad` must be given to
|
|
169
|
+
decryption.
|
|
170
|
+
|
|
171
|
+
### `crypto.aesDecrypt(key, ciphertext, options): Promise<string | Uint8Array>`
|
|
172
|
+
|
|
173
|
+
```typescript
|
|
174
|
+
interface AesDecryptOptions {
|
|
175
|
+
readonly mode?: AesMode; // Default "GCM"
|
|
176
|
+
readonly iv: string | Uint8Array;
|
|
177
|
+
readonly tag?: string | Uint8Array; // GCM only, when not appended to the ciphertext
|
|
178
|
+
readonly aad?: string | Uint8Array; // GCM only
|
|
179
|
+
readonly encoding?: BinaryEncoding; // Of a string ciphertext, iv, and tag; default "base64"
|
|
180
|
+
readonly output?: DecryptOutput; // Default "utf8"
|
|
181
|
+
}
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Decrypts an AES ciphertext. `iv` is required. In GCM mode, the last 16 bytes of
|
|
185
|
+
`ciphertext` are the tag unless `tag` is given. `output` selects the result:
|
|
186
|
+
`"utf8"` (default) decodes the plaintext as UTF-8 text and throws
|
|
187
|
+
`ValidationError` if it is not valid UTF-8, `"bytes"` returns a `Uint8Array`, and
|
|
188
|
+
`"base64"`, `"base64url"`, or `"hex"` return the plaintext bytes in that encoding.
|
|
189
|
+
|
|
190
|
+
A wrong key, IV, tag, or `aad`, a modified ciphertext, or invalid CBC padding
|
|
191
|
+
throws `CogoverApiError` with `code: "DECRYPTION_FAILED"`. The error is the same
|
|
192
|
+
for every cause, so that the result reveals nothing about the key or plaintext.
|
|
193
|
+
|
|
194
|
+
```typescript
|
|
195
|
+
import { crypto, CogoverApiError, defineScript } from "@cogover/sdk";
|
|
196
|
+
|
|
197
|
+
export default defineScript(async ({ request }) => {
|
|
198
|
+
const { data, iv, tag } = request.body as { data: string; iv: string; tag: string };
|
|
199
|
+
try {
|
|
200
|
+
const json = await crypto.aesDecrypt({ secret: "partner_aes_key", encoding: "base64" }, data, { iv, tag });
|
|
201
|
+
return { payment: JSON.parse(json) };
|
|
202
|
+
} catch (error) {
|
|
203
|
+
if (error instanceof CogoverApiError && error.code === "DECRYPTION_FAILED") {
|
|
204
|
+
return { r: 1001, msg: "The payload could not be decrypted." };
|
|
205
|
+
}
|
|
206
|
+
throw error;
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
### `crypto.rsaEncrypt(publicKey, data, options?)` and `crypto.rsaDecrypt(privateKey, ciphertext, options?)`
|
|
212
|
+
|
|
213
|
+
```typescript
|
|
214
|
+
type RsaPadding = "OAEP-SHA256" | "OAEP-SHA1" | "PKCS1";
|
|
215
|
+
|
|
216
|
+
interface RsaEncryptOptions {
|
|
217
|
+
readonly padding?: RsaPadding; // Default "OAEP-SHA256"
|
|
218
|
+
readonly encoding?: BinaryEncoding; // Of the ciphertext; default "base64"
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
interface RsaDecryptOptions {
|
|
222
|
+
readonly padding?: RsaPadding; // Default "OAEP-SHA256"
|
|
223
|
+
readonly encoding?: BinaryEncoding; // Of a string ciphertext; default "base64"
|
|
224
|
+
readonly output?: DecryptOutput; // Default "utf8"
|
|
225
|
+
}
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
`rsaEncrypt` encrypts `data` (a string is encoded as UTF-8) with an RSA public key
|
|
229
|
+
and returns the ciphertext in `encoding`. `rsaDecrypt` decrypts it with the
|
|
230
|
+
matching private key and returns the plaintext as `output`, like `aesDecrypt`.
|
|
231
|
+
|
|
232
|
+
- `"OAEP-SHA256"` (default) is RSA-OAEP with SHA-256, and its mask generation
|
|
233
|
+
function MGF1 also uses SHA-256, as in Web Crypto, Node.js, and OpenSSL.
|
|
234
|
+
`"OAEP-SHA1"` uses SHA-1 for both. Some Java code written as
|
|
235
|
+
`OAEPWithSHA-256AndMGF1Padding` keeps MGF1 on SHA-1 and is compatible with
|
|
236
|
+
neither; ask the other system which digest its MGF1 uses.
|
|
237
|
+
- `"PKCS1"` is PKCS #1 v1.5 padding. Use it only when an external system requires
|
|
238
|
+
it.
|
|
239
|
+
- RSA encrypts only a small amount of data: at most the key size in bytes minus
|
|
240
|
+
66 bytes for `"OAEP-SHA256"`, minus 42 for `"OAEP-SHA1"`, and minus 11 for
|
|
241
|
+
`"PKCS1"` — 190, 214, and 245 bytes for a 2048-bit key. Larger data throws
|
|
242
|
+
`ValidationError`. To send more, encrypt the data with `aesEncrypt` under a
|
|
243
|
+
random key from `randomBytes(32)` and encrypt only that key with `rsaEncrypt`.
|
|
244
|
+
- A decryption that fails for any reason throws `CogoverApiError` with
|
|
245
|
+
`code: "DECRYPTION_FAILED"`.
|
|
246
|
+
|
|
247
|
+
```typescript
|
|
248
|
+
const cardToken = await crypto.rsaEncrypt({ secret: "bank_public_key" }, "4111111111111111");
|
|
249
|
+
const plain = await crypto.rsaDecrypt({ secret: "our_private_key" }, request.body.data as string);
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
### `crypto.sign(algorithm, privateKey, data, options?)` and `crypto.verify(algorithm, publicKey, data, signature, options?)`
|
|
253
|
+
|
|
254
|
+
```typescript
|
|
255
|
+
type SignatureAlgorithm =
|
|
256
|
+
| "RSA-SHA1" | "RSA-SHA256" | "RSA-SHA384" | "RSA-SHA512"
|
|
257
|
+
| "RSA-PSS-SHA256" | "RSA-PSS-SHA384" | "RSA-PSS-SHA512"
|
|
258
|
+
| "ECDSA-SHA256" | "ECDSA-SHA384" | "ECDSA-SHA512";
|
|
259
|
+
|
|
260
|
+
interface SignatureOptions {
|
|
261
|
+
readonly encoding?: BinaryEncoding; // Of the signature; default "base64"
|
|
262
|
+
readonly signatureFormat?: "der" | "ieee-p1363"; // ECDSA only; default "der"
|
|
263
|
+
}
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
`sign` signs `data` (a string is encoded as UTF-8) with a private key and returns
|
|
267
|
+
the signature in `encoding`. `verify` returns `true` when `signature` is a valid
|
|
268
|
+
signature of `data` for the public key, and `false` otherwise, including when the
|
|
269
|
+
signature cannot be decoded or has the wrong length; a signature normally comes
|
|
270
|
+
from the party being verified, so a malformed one is not an error. A signature
|
|
271
|
+
longer than 2,048 characters, or 1,024 bytes as a `Uint8Array`, is invalid without
|
|
272
|
+
being sent. An invalid key or algorithm still throws `ValidationError`, whatever the
|
|
273
|
+
signature.
|
|
274
|
+
|
|
275
|
+
- `RSA-SHA*` is RSASSA-PKCS1-v1_5 and requires an RSA key. `RSA-SHA1` exists only
|
|
276
|
+
to verify signatures of systems that still use it; do not use it for new
|
|
277
|
+
signatures.
|
|
278
|
+
- `RSA-PSS-SHA*` is RSASSA-PSS with MGF1 on the same digest and a salt as long as
|
|
279
|
+
the digest (32, 48, or 64 bytes), and requires an RSA key.
|
|
280
|
+
- `ECDSA-SHA*` requires an EC key. `signatureFormat` is `"der"` (ASN.1, used by
|
|
281
|
+
OpenSSL and Java) or `"ieee-p1363"` (the fixed-length `r || s` form used by JWT
|
|
282
|
+
and Web Crypto); it is rejected for RSA algorithms.
|
|
283
|
+
|
|
284
|
+
| JWT `alg` | `algorithm` | Options |
|
|
285
|
+
|---|---|---|
|
|
286
|
+
| `RS256`, `RS384`, `RS512` | `RSA-SHA256`, `RSA-SHA384`, `RSA-SHA512` | `{ encoding: "base64url" }` |
|
|
287
|
+
| `PS256`, `PS384`, `PS512` | `RSA-PSS-SHA256`, `RSA-PSS-SHA384`, `RSA-PSS-SHA512` | `{ encoding: "base64url" }` |
|
|
288
|
+
| `ES256`, `ES384`, `ES512` | `ECDSA-SHA256`, `ECDSA-SHA384`, `ECDSA-SHA512` | `{ encoding: "base64url", signatureFormat: "ieee-p1363" }` |
|
|
289
|
+
|
|
290
|
+
```typescript
|
|
291
|
+
// Verify an ES256 JWT issued by a partner. Also check its claims (exp, iss, aud) before trusting it.
|
|
292
|
+
const [header, payload, signature] = token.split(".");
|
|
293
|
+
const valid = await crypto.verify("ECDSA-SHA256", { secret: "partner_jwt_public_key" },
|
|
294
|
+
`${header}.${payload}`, signature ?? "", { encoding: "base64url", signatureFormat: "ieee-p1363" });
|
|
295
|
+
if (!valid) return response.empty({ status: 401 });
|
|
296
|
+
|
|
297
|
+
// Sign a request to a bank that expects SHA256withRSA in base64.
|
|
298
|
+
const body = JSON.stringify(order);
|
|
299
|
+
const bankSignature = await crypto.sign("RSA-SHA256", { secret: "bank_signing_key" }, body);
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
### Limits and availability
|
|
303
|
+
|
|
304
|
+
`data`, `aad`, and an explicit HMAC key are limited to 256 KiB, and a ciphertext
|
|
305
|
+
to 256 KiB plus its tag; larger values and invalid arguments throw
|
|
306
|
+
`ValidationError` before the call. The whole call must also fit one capability
|
|
307
|
+
request of 262,144 bytes by default (see [Execution limits](overview.md#execution-limits)):
|
|
308
|
+
every argument is sent JSON-encoded in one request, and a `Uint8Array` is sent as
|
|
309
|
+
base64, which is a third larger. Binary data larger than about 190 KiB, or text data
|
|
310
|
+
close to 256 KiB together with other arguments, therefore throws `ValidationError`
|
|
311
|
+
before the call even though each value is within its own limit. The key, algorithm, and option errors that
|
|
312
|
+
Cogover detects, such as a key of the wrong size or type, also throw
|
|
313
|
+
`ValidationError`. Every operation except `timingSafeEqual` is a capability call
|
|
314
|
+
and counts towards the invocation's limits; `randomUUID` makes one call for every
|
|
315
|
+
64 UUIDs.
|
|
316
|
+
|
|
317
|
+
The operations work in every context, including before-change triggers, with a key
|
|
318
|
+
given in the call. A `{ secret }` key follows the rules of `secrets.get`: a
|
|
319
|
+
before-change trigger is refused with `PermissionDeniedError`
|
|
320
|
+
(`details.reason === "TRIGGER_READ_ONLY"`) and a local development session without
|
|
321
|
+
secret access with `details.reason === "SECRETS_NOT_ALLOWED"`.
|