@cogover/sdk 0.12.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.
@@ -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"`.
@@ -0,0 +1,184 @@
1
+ # `@cogover/sdk` API reference: Outbound HTTP and secrets
2
+
3
+ This page is part of the [`@cogover/sdk` API reference](overview.md).
4
+
5
+ ## Outbound HTTP `fetch`
6
+
7
+ ```typescript
8
+ function fetch(input: string, init?: CogoverFetchInit): Promise<CogoverFetchResponse>;
9
+
10
+ interface CogoverFetchInit {
11
+ readonly method?: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE";
12
+ readonly headers?: Readonly<Record<string, string>>;
13
+ readonly body?: string;
14
+ readonly timeoutMs?: number;
15
+ readonly credential?: string;
16
+ }
17
+
18
+ interface CogoverFetchHeaders {
19
+ get(name: string): string | null;
20
+ has(name: string): boolean;
21
+ entries(): IterableIterator<[string, string]>;
22
+ [Symbol.iterator](): IterableIterator<[string, string]>;
23
+ }
24
+
25
+ interface CogoverFetchResponse {
26
+ readonly ok: boolean;
27
+ readonly status: number;
28
+ readonly statusText: string;
29
+ readonly url: string;
30
+ readonly redirected: false;
31
+ readonly headers: CogoverFetchHeaders;
32
+ readonly bodyUsed: boolean;
33
+ text(): Promise<string>;
34
+ json<T = unknown>(): Promise<T>;
35
+ }
36
+ ```
37
+
38
+ Cogover installs the global `fetch()` function in the hosted runtime. Import
39
+ `{ fetch }` from `@cogover/sdk` when the dependency should be explicit; this also
40
+ prevents local Node.js from silently using its native, unrestricted `fetch` during
41
+ tests. The SDK function requires the Cogover runtime and always uses Cogover's
42
+ managed network layer. `input` must be an absolute public HTTPS URL without
43
+ userinfo, a fragment, or an IP-literal host, on port 443 or on an origin approved
44
+ for the project (see [Other ports](#other-ports)). `body` accepts only a string;
45
+ use `JSON.stringify()` for JSON. `timeoutMs` must be a positive integer and is
46
+ always clamped by the platform limit. It never extends the execution: an HTTP route
47
+ has 8 seconds in total by default, so there a slower server ends the whole execution
48
+ (see [Execution limits](overview.md#execution-limits)).
49
+
50
+ ```typescript
51
+ import { fetch } from "@cogover/sdk";
52
+
53
+ const response = await fetch("https://api.example.com/v1/orders", {
54
+ method: "POST",
55
+ headers: { "content-type": "application/json" },
56
+ body: JSON.stringify({ id: "ORD-1" }),
57
+ timeoutMs: 5_000,
58
+ });
59
+ ```
60
+
61
+ `CogoverFetchResponse` exposes `ok`, `status`, `statusText`, `url`, `redirected`
62
+ (always `false`), `headers`, `bodyUsed`, `text()`, and `json<T>()`. The bounded,
63
+ buffered body can be consumed once. Header `get(name)`, `has(name)`, `entries()`,
64
+ and iteration are case-insensitive.
65
+
66
+ V1 does not follow redirects, persist or send cookies, stream requests/responses,
67
+ or support WebSocket. It does not accept `signal`, `credentials`, `redirect`, proxy,
68
+ dispatcher, agent, DNS resolver, or TLS configuration. HTTP URLs, ports other than
69
+ 443 that the project has not been approved for, userinfo, and IP-literal hosts are
70
+ unsupported. Framing, hop-by-hop, proxy,
71
+ forwarding, and reserved Cogover request headers are rejected. Request/response sizes,
72
+ headers, time, calls, destinations, and concurrency are bounded by platform quotas.
73
+
74
+ - A `GET` or `HEAD` request with a `body` fails with `FETCH_BLOCKED`.
75
+ - A compressed response, one whose `Content-Encoding` is not `identity`, fails with
76
+ `FETCH_BLOCKED`.
77
+ - The response body is decoded as UTF-8: bytes that are not valid UTF-8 become
78
+ U+FFFD, so binary content cannot be read exactly.
79
+ - A host name that resolves to an address that is not public fails with
80
+ `FETCH_FAILED`.
81
+ - Calls started together, for example with `Promise.all`, are sent one after another.
82
+ - A before-change trigger cannot call `fetch`: it throws `PermissionDeniedError` with
83
+ `details.reason` `"TRIGGER_READ_ONLY"`. A read-only version preview allows only `GET`
84
+ and `HEAD` without `credential` and refuses other calls with `PermissionDeniedError`.
85
+
86
+ Failures are `CogoverApiError` instances with `FETCH_DISABLED`, `FETCH_BLOCKED`,
87
+ `FETCH_REQUEST_TOO_LARGE`, `FETCH_RESPONSE_TOO_LARGE`, `FETCH_TIMEOUT`, or
88
+ `FETCH_FAILED`; quota failures use `RateLimitError`. One execution may make at most 20
89
+ `fetch` calls; an HTTP route or a trigger reaches its budget of 20 capability calls
90
+ first, which is also reported as `RateLimitError` (see
91
+ [Execution limits](overview.md#execution-limits)). When POST, PUT, PATCH, or DELETE
92
+ times out or loses its response, the remote server may already have applied the
93
+ request. Use the remote API's idempotency mechanism and never retry blindly.
94
+
95
+ ### Other ports
96
+
97
+ A system that is only published on another port, such as
98
+ `https://erp.example.com:9899`, can be called once a Workspace administrator approves
99
+ that exact origin in the `fetch` section of the project's identity policy. The
100
+ approval covers only the listed `https://host:port` origins; other ports of the same
101
+ host stay blocked. Everything else in this section still applies to an approved
102
+ origin: HTTPS with a certificate that is valid for the host name, public addresses
103
+ only, no redirects, and the same limits. A URL on a port that is not approved fails
104
+ with `FETCH_BLOCKED`. Requests leave Cogover from outbound addresses shared with other
105
+ Workspaces, so a firewall allowlist of those addresses does not identify your
106
+ Workspace: have the target system authenticate the request, for example with a
107
+ credential.
108
+
109
+ ```typescript
110
+ // Allowed only after "https://erp.example.com:9899" is approved for this project.
111
+ const orders = await fetch("https://erp.example.com:9899/api/orders?status=new");
112
+ ```
113
+
114
+ ### Authenticating with a credential
115
+
116
+ `credential` names a credential that an administrator stored for the project (see
117
+ [Secrets and credentials](#secrets-and-credentials)). Cogover adds the credential's
118
+ authentication header to the request, so project code never handles the value:
119
+
120
+ ```typescript
121
+ const response = await fetch("https://erp.example.com/v1/orders", {
122
+ method: "POST",
123
+ credential: "erp_api",
124
+ headers: { "content-type": "application/json" },
125
+ body: JSON.stringify({ id: "ORD-1" }),
126
+ });
127
+ ```
128
+
129
+ Depending on how the credential was created, Cogover sends `Authorization: Bearer
130
+ <value>`, `Authorization: Basic <base64 of value>`, or a header with the configured
131
+ name. The name must start with a letter and contain at most 64 letters, digits, or
132
+ underscores. A credential can only be sent to the hosts its administrator allowed.
133
+ A host listed without a port allows port 443 only; to use the credential on an
134
+ approved origin on another port, the administrator lists `host:port`, for example
135
+ `erp.example.com:9899`. A request to another host or port, a request that sets the
136
+ same header itself, or a name
137
+ that is not an active credential fails with `FETCH_BLOCKED`. Redirects are never
138
+ followed, so a credential never leaves an allowed host.
139
+
140
+ ## Secrets and credentials
141
+
142
+ An administrator stores secrets for a project through the Cogover management API.
143
+ Each one is either a **secret**, whose value code reads with `secrets.get`, or a
144
+ **credential**, which only `fetch` uses (see
145
+ [Authenticating with a credential](#authenticating-with-a-credential)); the value
146
+ of a credential is never readable by code. Values are stored encrypted and are
147
+ never returned by the management API, logged, or included in error messages.
148
+
149
+ ```typescript
150
+ interface SecretsApi {
151
+ get(name: string): Promise<string>;
152
+ }
153
+ ```
154
+
155
+ ```typescript
156
+ const token = await secrets.get("erp_token");
157
+ const response = await fetch("https://erp.example.com/v1/orders", {
158
+ headers: { authorization: `Bearer ${token}` },
159
+ });
160
+ ```
161
+
162
+ ### `secrets.get(name): Promise<string>`
163
+
164
+ Returns the current value of the secret. `name` starts with a letter and contains
165
+ at most 64 letters, digits, or underscores; other names throw `ValidationError`
166
+ before the call. A secret that does not exist or is disabled throws
167
+ `ValidationError` with the message `Secret '<name>' is not available`, and a
168
+ credential throws `ValidationError` with `Secret '<name>' is a credential and
169
+ cannot be read`.
170
+
171
+ `secrets.get` works in scripts and routes, after-change triggers, jobs, and inbound
172
+ webhook calls. A before-change trigger is refused with `PermissionDeniedError`
173
+ (`details.reason === "TRIGGER_READ_ONLY"`); a local development session reads
174
+ secrets only when its administrator allowed it, otherwise the reason is
175
+ `"SECRETS_NOT_ALLOWED"`. One invocation may read secrets at most 20 times; every
176
+ read counts, including a repeated read of the same name and a `crypto` operation keyed
177
+ by `{ secret: name }`, and the 21st throws `RateLimitError`. In an HTTP route or a
178
+ trigger the budget of 20 capability calls is reached first (see
179
+ [Execution limits](overview.md#execution-limits)). When secrets are
180
+ not enabled for the Workspace, the error is `CogoverApiError` with
181
+ `code: "SECRETS_DISABLED"`. Never write a secret value to the log, to a record, to
182
+ state, or to a response. To sign, encrypt, or decrypt with a secret without
183
+ reading it, pass `{ secret: name }` as the key of a [`crypto`](cryptography.md#cryptography)
184
+ operation.
@@ -0,0 +1,65 @@
1
+ # `@cogover/sdk` API reference: Inbound webhooks
2
+
3
+ This page is part of the [`@cogover/sdk` API reference](overview.md).
4
+
5
+ ## Inbound webhooks
6
+
7
+ An administrator can create an **inbound access** for a project so that an external
8
+ system calls a route without a Cogover user session. The external system receives
9
+ a URL of the form
10
+
11
+ ```text
12
+ https://{WORKSPACE_DOMAIN}/api/v1/ts-projects/{projectSlug}/hooks/{inboundId}/{route}
13
+ ```
14
+
15
+ and authenticates each call with the inbound key or the HMAC signature that was
16
+ configured for the inbound access. Cogover verifies the key or signature, applies
17
+ the rate limit, and rejects the call before any project code runs. A route handler
18
+ sees such a call as `request.path === "/hooks/{route}"`: register webhook routes
19
+ under `/hooks/` and the inbound ID is not part of the path.
20
+
21
+ ```typescript
22
+ import { createRouter } from "@cogover/sdk";
23
+
24
+ const router = createRouter();
25
+ router.post("/hooks/payments", async ({ request, invocation, crypto, jobs, response }) => {
26
+ if (invocation.identity !== "inbound") return response.empty({ status: 403 });
27
+
28
+ // Optional: verify the external system's own signature over the raw body.
29
+ const expected = await crypto.hmacSha256({ secret: "payment_signing_secret" }, request.rawBody ?? "");
30
+ if (!crypto.timingSafeEqual(expected, request.headers["x-payment-signature"] ?? "")) {
31
+ return response.empty({ status: 401 });
32
+ }
33
+
34
+ const event = request.body as { id: string; orderId: string };
35
+ await jobs.enqueue("sync_payment", event, { idempotencyKey: `payment:${event.id}` });
36
+ return response.json({ received: true }, { status: 202 });
37
+ });
38
+ export default router.toHandler();
39
+ ```
40
+
41
+ - **Identity.** `invocation.identity` is `"inbound"`, `invocation.user` is `null`,
42
+ and `invocation.inbound` holds the `id`, `name`, and authentication `mode` of the
43
+ inbound access. `data.object()` acts as the system identity and works only if the
44
+ project's approved identity policy sets `allowInternalSystem: true`; it then has the
45
+ same access as in a scheduled job, which the objects granted to `data.asSystem()` do
46
+ not narrow. Otherwise its calls throw `PermissionDeniedError` with `details.reason`
47
+ `"IDENTITY_NOT_GRANTED"`. `data.asUser()` and `data.asSystem()` follow the grants of
48
+ the identity policy only when `allowInternalSystem` is `true`; otherwise they are
49
+ refused in the same way, even for granted objects.
50
+ - **Body.** The request body is limited to 256 KiB. When it is a JSON object it is
51
+ `request.body`; a form, text, or other body leaves `request.body` empty (`{}`).
52
+ `request.rawBody` always holds the body exactly as received, as a UTF-8 string,
53
+ and `request.contentType` the request's `Content-Type`, so a handler can verify a
54
+ signature or parse another format itself.
55
+ - **Response.** The handler's return value and the `response` helpers work as for
56
+ any route. Keep the handler short: acknowledge the event and enqueue a job for
57
+ the actual work, so that the external system gets a quick answer and retries
58
+ cannot overlap with slow processing.
59
+ - **Retries.** External systems usually retry a webhook that did not receive a
60
+ 2xx response, so a handler may see the same event more than once. Use the event's
61
+ own identifier as the `idempotencyKey` of the job it enqueues, or as a state key.
62
+ An `Idempotency-Key` request header works as for any route. When the inbound access
63
+ checks an HMAC signature with a timestamp, each signature is accepted once, before
64
+ the handler runs: a retry that repeats the same signature is refused with HTTP 401,
65
+ even when the first attempt failed, so the sender must sign each retry again.