@cogover/sdk 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -76,6 +76,18 @@ invocations and to `null` for system invocations. Only the documented profile,
76
76
  membership, locale, and workspace fields are included. Raw authentication data
77
77
  and Cogover credentials are never exposed.
78
78
 
79
+ `invocation.user.membership.isSuperAdmin` tells whether the user holds the
80
+ workspace's Super Admin role, and `invocation.user.membership.roles` lists the
81
+ user's roles in the current workspace as `{ id, name }` entries. Compare roles by
82
+ `id`; role permissions are not exposed, and Cogover still enforces record and
83
+ field access for the user, so use these fields for business rules only:
84
+
85
+ ```typescript
86
+ const user = invocation.user;
87
+ const canApprove = user !== null && (user.membership.isSuperAdmin
88
+ || user.membership.roles.some((role) => role.id === APPROVER_ROLE_ID));
89
+ ```
90
+
79
91
  ## Full HTTP routes and responses
80
92
 
81
93
  ```typescript
@@ -318,7 +330,17 @@ export default router.toHandler();
318
330
 
319
331
  `crypto` — also importable from `@cogover/sdk` — provides `sha256`, `hmacSha256`
320
332
  (with a string, byte, or `{ secret }` key), `randomBytes`, `randomUUID`, and the
321
- constant-time `timingSafeEqual`.
333
+ constant-time `timingSafeEqual`. It also encrypts and signs: `aesEncrypt` and
334
+ `aesDecrypt` (AES-GCM or AES-CBC), `rsaEncrypt` and `rsaDecrypt` (RSA-OAEP or
335
+ PKCS #1 v1.5), and `sign` and `verify` (RSA, RSA-PSS, and ECDSA, including the JWT
336
+ signature formats). Keys may be PEM text or `{ secret: name }`, so private keys stay
337
+ in project secrets.
338
+
339
+ ```typescript
340
+ const sealed = await crypto.aesEncrypt({ secret: "partner_aes_key", encoding: "base64" }, JSON.stringify(order));
341
+ const signature = await crypto.sign("RSA-SHA256", { secret: "our_signing_key" }, JSON.stringify(sealed));
342
+ const valid = await crypto.verify("ECDSA-SHA256", { secret: "partner_public_key" }, body, signatureHeader);
343
+ ```
322
344
 
323
345
  ## Record API
324
346
 
package/dist/crypto.d.ts CHANGED
@@ -1,4 +1,93 @@
1
- /** Hashing, message authentication and randomness provided by Cogover. */
1
+ /** Text encoding of binary values such as ciphertexts, IVs, tags and signatures. */
2
+ export type BinaryEncoding = "base64" | "base64url" | "hex";
3
+ /**
4
+ * What a decryption returns: `"utf8"` decodes the plaintext as UTF-8 text, `"bytes"` returns a `Uint8Array`, and
5
+ * a {@link BinaryEncoding} returns the plaintext bytes in that encoding.
6
+ */
7
+ export type DecryptOutput = "utf8" | "bytes" | BinaryEncoding;
8
+ /** A key stored as a project secret, used without reading its value. */
9
+ export interface SecretKeyReference {
10
+ readonly secret: string;
11
+ }
12
+ /**
13
+ * An AES key: 16, 24 or 32 bytes given as a UTF-8 string, as bytes, or as a project secret. For a secret,
14
+ * `encoding` tells how its text encodes the key bytes and defaults to `"utf8"`.
15
+ */
16
+ export type AesKey = string | Uint8Array | (SecretKeyReference & {
17
+ readonly encoding?: "utf8" | "base64" | "hex";
18
+ });
19
+ /**
20
+ * An RSA or EC key as PEM text or base64 DER, or a project secret holding one. Public keys may be
21
+ * SubjectPublicKeyInfo (`PUBLIC KEY`), PKCS #1 (`RSA PUBLIC KEY`) or an X.509 `CERTIFICATE`; private keys may be
22
+ * PKCS #8 (`PRIVATE KEY`), PKCS #1 (`RSA PRIVATE KEY`) or SEC1 (`EC PRIVATE KEY`).
23
+ */
24
+ export type AsymmetricKey = string | SecretKeyReference;
25
+ /** AES block cipher mode. */
26
+ export type AesMode = "GCM" | "CBC";
27
+ /** Options of {@link CryptoApi.aesEncrypt}. */
28
+ export interface AesEncryptOptions {
29
+ /** `"GCM"` (default, authenticated) or `"CBC"` with PKCS #7 padding. */
30
+ readonly mode?: AesMode;
31
+ /** IV to use; a random one is generated when omitted. A string is decoded with `encoding`. */
32
+ readonly iv?: string | Uint8Array;
33
+ /** Additional authenticated data for GCM; a string is encoded as UTF-8. */
34
+ readonly aad?: string | Uint8Array;
35
+ /** GCM only: return the authentication tag in `tag` instead of appending it to `ciphertext`. */
36
+ readonly separateTag?: boolean;
37
+ /** Encoding of the result and of a string `iv`; defaults to `"base64"`. */
38
+ readonly encoding?: BinaryEncoding;
39
+ }
40
+ /** Result of {@link CryptoApi.aesEncrypt}, in the requested encoding. */
41
+ export interface AesEncryptResult {
42
+ /** The ciphertext; in GCM mode it ends with the 16-byte tag unless `separateTag` was set. */
43
+ readonly ciphertext: string;
44
+ readonly iv: string;
45
+ /** The GCM tag, present only when `separateTag` was set. */
46
+ readonly tag?: string;
47
+ }
48
+ /** Options of {@link CryptoApi.aesDecrypt}. */
49
+ export interface AesDecryptOptions {
50
+ /** `"GCM"` (default) or `"CBC"`. */
51
+ readonly mode?: AesMode;
52
+ /** The IV used for encryption. */
53
+ readonly iv: string | Uint8Array;
54
+ /** GCM only: the tag, when it is not appended to the ciphertext. */
55
+ readonly tag?: string | Uint8Array;
56
+ /** GCM only: the additional authenticated data given to encryption. */
57
+ readonly aad?: string | Uint8Array;
58
+ /** Encoding of a string ciphertext, `iv` and `tag`; defaults to `"base64"`. */
59
+ readonly encoding?: BinaryEncoding;
60
+ /** Form of the plaintext; defaults to `"utf8"`. */
61
+ readonly output?: DecryptOutput;
62
+ }
63
+ /** RSA encryption padding: OAEP with SHA-256 or SHA-1 (MGF1 uses the same digest), or PKCS #1 v1.5. */
64
+ export type RsaPadding = "OAEP-SHA256" | "OAEP-SHA1" | "PKCS1";
65
+ /** Options of {@link CryptoApi.rsaEncrypt}. */
66
+ export interface RsaEncryptOptions {
67
+ /** Defaults to `"OAEP-SHA256"`. */
68
+ readonly padding?: RsaPadding;
69
+ /** Encoding of the ciphertext; defaults to `"base64"`. */
70
+ readonly encoding?: BinaryEncoding;
71
+ }
72
+ /** Options of {@link CryptoApi.rsaDecrypt}. */
73
+ export interface RsaDecryptOptions {
74
+ /** Defaults to `"OAEP-SHA256"`. */
75
+ readonly padding?: RsaPadding;
76
+ /** Encoding of a string ciphertext; defaults to `"base64"`. */
77
+ readonly encoding?: BinaryEncoding;
78
+ /** Form of the plaintext; defaults to `"utf8"`. */
79
+ readonly output?: DecryptOutput;
80
+ }
81
+ /** Signature algorithm: RSA PKCS #1 v1.5, RSA-PSS (salt length equal to the digest length) or ECDSA. */
82
+ export type SignatureAlgorithm = "RSA-SHA1" | "RSA-SHA256" | "RSA-SHA384" | "RSA-SHA512" | "RSA-PSS-SHA256" | "RSA-PSS-SHA384" | "RSA-PSS-SHA512" | "ECDSA-SHA256" | "ECDSA-SHA384" | "ECDSA-SHA512";
83
+ /** Options of {@link CryptoApi.sign} and {@link CryptoApi.verify}. */
84
+ export interface SignatureOptions {
85
+ /** Encoding of the signature; defaults to `"base64"`. */
86
+ readonly encoding?: BinaryEncoding;
87
+ /** ECDSA only: `"der"` (default) or `"ieee-p1363"`, the raw `r || s` form that JWT and Web Crypto use. */
88
+ readonly signatureFormat?: "der" | "ieee-p1363";
89
+ }
90
+ /** Hashing, message authentication, randomness, encryption and signatures provided by Cogover. */
2
91
  export interface CryptoApi {
3
92
  /** SHA-256 digest of a string (encoded as UTF-8) or of bytes; `encoding` defaults to `"hex"`. */
4
93
  sha256(data: string | Uint8Array, encoding?: "hex" | "base64"): Promise<string>;
@@ -15,6 +104,30 @@ export interface CryptoApi {
15
104
  randomUUID(): Promise<string>;
16
105
  /** Compares two values in constant time; strings are compared as UTF-8 bytes. */
17
106
  timingSafeEqual(a: string | Uint8Array, b: string | Uint8Array): boolean;
107
+ /** Encrypts `data` (a string is encoded as UTF-8) with AES-GCM or AES-CBC. */
108
+ aesEncrypt(key: AesKey, data: string | Uint8Array, options?: AesEncryptOptions): Promise<AesEncryptResult>;
109
+ /** Decrypts an AES ciphertext; fails with `DECRYPTION_FAILED` when the key, IV, tag or data is wrong. */
110
+ aesDecrypt(key: AesKey, ciphertext: string | Uint8Array, options: AesDecryptOptions & {
111
+ readonly output: "bytes";
112
+ }): Promise<Uint8Array>;
113
+ aesDecrypt(key: AesKey, ciphertext: string | Uint8Array, options: AesDecryptOptions & {
114
+ readonly output?: Exclude<DecryptOutput, "bytes">;
115
+ }): Promise<string>;
116
+ aesDecrypt(key: AesKey, ciphertext: string | Uint8Array, options: AesDecryptOptions): Promise<string | Uint8Array>;
117
+ /** Encrypts `data` (a string is encoded as UTF-8) with an RSA public key. */
118
+ rsaEncrypt(publicKey: AsymmetricKey, data: string | Uint8Array, options?: RsaEncryptOptions): Promise<string>;
119
+ /** Decrypts an RSA ciphertext with the private key; fails with `DECRYPTION_FAILED` when it cannot. */
120
+ rsaDecrypt(privateKey: AsymmetricKey, ciphertext: string | Uint8Array, options: RsaDecryptOptions & {
121
+ readonly output: "bytes";
122
+ }): Promise<Uint8Array>;
123
+ rsaDecrypt(privateKey: AsymmetricKey, ciphertext: string | Uint8Array, options?: RsaDecryptOptions & {
124
+ readonly output?: Exclude<DecryptOutput, "bytes">;
125
+ }): Promise<string>;
126
+ rsaDecrypt(privateKey: AsymmetricKey, ciphertext: string | Uint8Array, options?: RsaDecryptOptions): Promise<string | Uint8Array>;
127
+ /** Signs `data` (a string is encoded as UTF-8) with an RSA or EC private key. */
128
+ sign(algorithm: SignatureAlgorithm, privateKey: AsymmetricKey, data: string | Uint8Array, options?: SignatureOptions): Promise<string>;
129
+ /** Whether `signature` is a valid signature of `data`; a malformed signature is `false`, not an error. */
130
+ verify(algorithm: SignatureAlgorithm, publicKey: AsymmetricKey, data: string | Uint8Array, signature: string | Uint8Array, options?: SignatureOptions): Promise<boolean>;
18
131
  }
19
132
  /** Cryptographic helpers backed by Cogover's managed implementation. */
20
133
  export declare const crypto: CryptoApi;
package/dist/crypto.js CHANGED
@@ -6,7 +6,159 @@ import { requireSecretName } from "./internal/validation.js";
6
6
  import { isRecord } from "./internal/values.js";
7
7
  const MAX_DATA_BYTES = 256 * 1024;
8
8
  const MAX_RANDOM_BYTES = 1024;
9
+ const MAX_KEY_CHARS = 16 * 1024;
10
+ /** Longest text form of a ciphertext: hex of the data limit plus an AES-GCM tag. */
11
+ const MAX_ENCODED_CHARS = 2 * (MAX_DATA_BYTES + 16);
12
+ const MAX_ENCODED_PARAMETER_CHARS = 1024;
9
13
  const ENCODINGS = new Set(["hex", "base64"]);
14
+ const BINARY_ENCODINGS = new Set(["base64", "base64url", "hex"]);
15
+ const DECRYPT_OUTPUTS = new Set(["utf8", "bytes", "base64", "base64url", "hex"]);
16
+ const KEY_ENCODINGS = new Set(["utf8", "base64", "hex"]);
17
+ const AES_MODES = new Set(["GCM", "CBC"]);
18
+ const AES_KEY_BYTES = new Set([16, 24, 32]);
19
+ const RSA_PADDINGS = new Set(["OAEP-SHA256", "OAEP-SHA1", "PKCS1"]);
20
+ const SIGNATURE_ALGORITHMS = new Set([
21
+ "RSA-SHA1", "RSA-SHA256", "RSA-SHA384", "RSA-SHA512",
22
+ "RSA-PSS-SHA256", "RSA-PSS-SHA384", "RSA-PSS-SHA512",
23
+ "ECDSA-SHA256", "ECDSA-SHA384", "ECDSA-SHA512",
24
+ ]);
25
+ const SIGNATURE_FORMATS = new Set(["der", "ieee-p1363"]);
26
+ const AES_ENCRYPT_OPTIONS = new Set(["mode", "iv", "aad", "separateTag", "encoding"]);
27
+ const AES_DECRYPT_OPTIONS = new Set(["mode", "iv", "tag", "aad", "encoding", "output"]);
28
+ const RSA_ENCRYPT_OPTIONS = new Set(["padding", "encoding"]);
29
+ const RSA_DECRYPT_OPTIONS = new Set(["padding", "encoding", "output"]);
30
+ const SIGNATURE_OPTIONS = new Set(["encoding", "signatureFormat"]);
31
+ async function aesEncrypt(key, data, options) {
32
+ const label = "aesEncrypt()";
33
+ const opts = optionsObject(options, AES_ENCRYPT_OPTIONS, label);
34
+ const mode = aesMode(opts.mode, label);
35
+ const encoding = binaryEncoding(opts.encoding, label);
36
+ const payload = {
37
+ algorithm: `AES-${mode}`,
38
+ key: aesKey(key, label),
39
+ ...namedData(bridgeData(data, `${label} data`), "data"),
40
+ encoding,
41
+ };
42
+ if (opts.iv !== undefined)
43
+ addBinary(payload, "iv", binaryInput(opts.iv, encoding, `${label} iv`, MAX_ENCODED_PARAMETER_CHARS));
44
+ if (opts.aad !== undefined)
45
+ addAad(payload, opts.aad, mode, label);
46
+ if (opts.separateTag !== undefined) {
47
+ if (typeof opts.separateTag !== "boolean")
48
+ throw new ValidationError(`${label} separateTag must be a boolean`);
49
+ if (opts.separateTag && mode !== "GCM")
50
+ throw new ValidationError(`${label} separateTag requires mode "GCM"`);
51
+ if (opts.separateTag)
52
+ payload.separateTag = true;
53
+ }
54
+ const result = await callBridge("crypto.encrypt", payload);
55
+ if (!isRecord(result) || typeof result.ciphertext !== "string" || typeof result.iv !== "string"
56
+ || result.iv.length === 0 || (payload.separateTag === true) !== (typeof result.tag === "string")) {
57
+ throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Encryption result is invalid");
58
+ }
59
+ return typeof result.tag === "string"
60
+ ? { ciphertext: result.ciphertext, iv: result.iv, tag: result.tag }
61
+ : { ciphertext: result.ciphertext, iv: result.iv };
62
+ }
63
+ async function aesDecrypt(key, ciphertext, options) {
64
+ const label = "aesDecrypt()";
65
+ if (options === undefined)
66
+ throw new ValidationError(`${label} options.iv is required`);
67
+ const opts = optionsObject(options, AES_DECRYPT_OPTIONS, label);
68
+ const mode = aesMode(opts.mode, label);
69
+ const encoding = binaryEncoding(opts.encoding, label);
70
+ const output = decryptOutput(opts.output, label);
71
+ if (opts.iv === undefined)
72
+ throw new ValidationError(`${label} options.iv is required`);
73
+ const payload = {
74
+ algorithm: `AES-${mode}`,
75
+ key: aesKey(key, label),
76
+ ...namedBinary(binaryInput(ciphertext, encoding, `${label} ciphertext`, MAX_ENCODED_CHARS), "data"),
77
+ ...namedBinary(binaryInput(opts.iv, encoding, `${label} iv`, MAX_ENCODED_PARAMETER_CHARS), "iv"),
78
+ output: output === "bytes" ? "base64" : output,
79
+ };
80
+ if (opts.tag !== undefined) {
81
+ if (mode !== "GCM")
82
+ throw new ValidationError(`${label} tag requires mode "GCM"`);
83
+ addBinary(payload, "tag", binaryInput(opts.tag, encoding, `${label} tag`, MAX_ENCODED_PARAMETER_CHARS));
84
+ }
85
+ if (opts.aad !== undefined)
86
+ addAad(payload, opts.aad, mode, label);
87
+ return plaintext(await callBridge("crypto.decrypt", payload), output);
88
+ }
89
+ async function rsaEncrypt(publicKey, data, options) {
90
+ const label = "rsaEncrypt()";
91
+ const opts = optionsObject(options, RSA_ENCRYPT_OPTIONS, label);
92
+ const result = await callBridge("crypto.encrypt", {
93
+ algorithm: `RSA-${rsaPadding(opts.padding, label)}`,
94
+ key: asymmetricKey(publicKey, `${label} public key`),
95
+ ...namedData(bridgeData(data, `${label} data`), "data"),
96
+ encoding: binaryEncoding(opts.encoding, label),
97
+ });
98
+ if (!isRecord(result) || typeof result.ciphertext !== "string" || result.ciphertext.length === 0) {
99
+ throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Encryption result is invalid");
100
+ }
101
+ return result.ciphertext;
102
+ }
103
+ async function rsaDecrypt(privateKey, ciphertext, options) {
104
+ const label = "rsaDecrypt()";
105
+ const opts = optionsObject(options, RSA_DECRYPT_OPTIONS, label);
106
+ const encoding = binaryEncoding(opts.encoding, label);
107
+ const output = decryptOutput(opts.output, label);
108
+ return plaintext(await callBridge("crypto.decrypt", {
109
+ algorithm: `RSA-${rsaPadding(opts.padding, label)}`,
110
+ key: asymmetricKey(privateKey, `${label} private key`),
111
+ ...namedBinary(binaryInput(ciphertext, encoding, `${label} ciphertext`, MAX_ENCODED_CHARS), "data"),
112
+ output: output === "bytes" ? "base64" : output,
113
+ }), output);
114
+ }
115
+ async function sign(algorithm, privateKey, data, options) {
116
+ const label = "sign()";
117
+ const signatureAlgorithm = requireSignatureAlgorithm(algorithm, label);
118
+ const opts = optionsObject(options, SIGNATURE_OPTIONS, label);
119
+ const payload = {
120
+ algorithm: signatureAlgorithm,
121
+ key: asymmetricKey(privateKey, `${label} private key`),
122
+ ...namedData(bridgeData(data, `${label} data`), "data"),
123
+ encoding: binaryEncoding(opts.encoding, label),
124
+ };
125
+ addSignatureFormat(payload, opts.signatureFormat, signatureAlgorithm, label);
126
+ const result = await callBridge("crypto.sign", payload);
127
+ if (!isRecord(result) || typeof result.signature !== "string" || result.signature.length === 0) {
128
+ throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Signature is invalid");
129
+ }
130
+ return result.signature;
131
+ }
132
+ async function verify(algorithm, publicKey, data, signature, options) {
133
+ const label = "verify()";
134
+ const signatureAlgorithm = requireSignatureAlgorithm(algorithm, label);
135
+ const opts = optionsObject(options, SIGNATURE_OPTIONS, label);
136
+ const encoding = binaryEncoding(opts.encoding, label);
137
+ const key = asymmetricKey(publicKey, `${label} public key`);
138
+ const signed = bridgeData(data, `${label} data`);
139
+ if (typeof signature !== "string" && !(signature instanceof Uint8Array)) {
140
+ throw new ValidationError(`${label} signature must be a string or a Uint8Array`);
141
+ }
142
+ // A signature usually comes from the party being verified, so one that is too long is simply invalid.
143
+ if (typeof signature === "string" ? signature.length > MAX_ENCODED_PARAMETER_CHARS * 2 : signature.length > 1024) {
144
+ addSignatureFormat({}, opts.signatureFormat, signatureAlgorithm, label);
145
+ return false;
146
+ }
147
+ const payload = {
148
+ algorithm: signatureAlgorithm,
149
+ key,
150
+ ...namedData(signed, "data"),
151
+ ...namedBinary(typeof signature === "string"
152
+ ? { value: signature, encoding }
153
+ : { value: encodeBase64(signature), encoding: "base64" }, "signature"),
154
+ };
155
+ addSignatureFormat(payload, opts.signatureFormat, signatureAlgorithm, label);
156
+ const result = await callBridge("crypto.verify", payload);
157
+ if (!isRecord(result) || typeof result.valid !== "boolean") {
158
+ throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Verification result is invalid");
159
+ }
160
+ return result.valid;
161
+ }
10
162
  /** Cryptographic helpers backed by Cogover's managed implementation. */
11
163
  export const crypto = Object.freeze({
12
164
  async sha256(data, encoding = "hex") {
@@ -59,6 +211,12 @@ export const crypto = Object.freeze({
59
211
  }
60
212
  return mismatch === 0;
61
213
  },
214
+ aesEncrypt,
215
+ aesDecrypt: aesDecrypt,
216
+ rsaEncrypt,
217
+ rsaDecrypt: rsaDecrypt,
218
+ sign,
219
+ verify,
62
220
  });
63
221
  function bridgeData(data, label) {
64
222
  if (typeof data === "string") {
@@ -73,6 +231,143 @@ function bridgeData(data, label) {
73
231
  }
74
232
  throw new ValidationError(`${label} must be a string or a Uint8Array`);
75
233
  }
234
+ function namedData(data, name) {
235
+ return { [name]: data.data, [`${name}Encoding`]: data.dataEncoding };
236
+ }
237
+ function namedBinary(input, name) {
238
+ return { [name]: input.value, [`${name}Encoding`]: input.encoding };
239
+ }
240
+ function addBinary(payload, name, input) {
241
+ Object.assign(payload, namedBinary(input, name));
242
+ }
243
+ /** A binary value given as text in `encoding`, or as bytes that cross the bridge as base64. */
244
+ function binaryInput(value, encoding, label, maxChars) {
245
+ if (typeof value === "string") {
246
+ if (value.length > maxChars)
247
+ throw new ValidationError(`${label} must not exceed ${maxChars} characters`);
248
+ return { value, encoding };
249
+ }
250
+ if (value instanceof Uint8Array) {
251
+ const text = encodeBase64(value);
252
+ if (text.length > maxChars)
253
+ throw new ValidationError(`${label} is too large`);
254
+ return { value: text, encoding: "base64" };
255
+ }
256
+ throw new ValidationError(`${label} must be a string or a Uint8Array`);
257
+ }
258
+ function addAad(payload, aad, mode, label) {
259
+ if (mode !== "GCM")
260
+ throw new ValidationError(`${label} aad requires mode "GCM"`);
261
+ Object.assign(payload, namedData(bridgeData(aad, `${label} aad`), "aad"));
262
+ }
263
+ function optionsObject(options, allowed, label) {
264
+ if (options === undefined)
265
+ return {};
266
+ if (!isRecord(options))
267
+ throw new ValidationError(`${label} options must be an object`);
268
+ for (const option of Object.keys(options)) {
269
+ if (!allowed.has(option))
270
+ throw new ValidationError(`${label} has the unknown option '${option}'`);
271
+ }
272
+ return options;
273
+ }
274
+ function aesMode(mode, label) {
275
+ if (mode === undefined)
276
+ return "GCM";
277
+ if (typeof mode !== "string" || !AES_MODES.has(mode))
278
+ throw new ValidationError(`${label} mode must be "GCM" or "CBC"`);
279
+ return mode;
280
+ }
281
+ function rsaPadding(padding, label) {
282
+ if (padding === undefined)
283
+ return "OAEP-SHA256";
284
+ if (typeof padding !== "string" || !RSA_PADDINGS.has(padding)) {
285
+ throw new ValidationError(`${label} padding must be "OAEP-SHA256", "OAEP-SHA1" or "PKCS1"`);
286
+ }
287
+ return padding;
288
+ }
289
+ function binaryEncoding(encoding, label) {
290
+ if (encoding === undefined)
291
+ return "base64";
292
+ if (typeof encoding !== "string" || !BINARY_ENCODINGS.has(encoding)) {
293
+ throw new ValidationError(`${label} encoding must be "base64", "base64url" or "hex"`);
294
+ }
295
+ return encoding;
296
+ }
297
+ function decryptOutput(output, label) {
298
+ if (output === undefined)
299
+ return "utf8";
300
+ if (typeof output !== "string" || !DECRYPT_OUTPUTS.has(output)) {
301
+ throw new ValidationError(`${label} output must be "utf8", "bytes", "base64", "base64url" or "hex"`);
302
+ }
303
+ return output;
304
+ }
305
+ function requireSignatureAlgorithm(algorithm, label) {
306
+ if (typeof algorithm !== "string" || !SIGNATURE_ALGORITHMS.has(algorithm)) {
307
+ throw new ValidationError(`${label} algorithm must be one of ${[...SIGNATURE_ALGORITHMS].join(", ")}`);
308
+ }
309
+ return algorithm;
310
+ }
311
+ function addSignatureFormat(payload, format, algorithm, label) {
312
+ if (format === undefined)
313
+ return;
314
+ if (!algorithm.startsWith("ECDSA-"))
315
+ throw new ValidationError(`${label} signatureFormat applies only to ECDSA`);
316
+ if (typeof format !== "string" || !SIGNATURE_FORMATS.has(format)) {
317
+ throw new ValidationError(`${label} signatureFormat must be "der" or "ieee-p1363"`);
318
+ }
319
+ payload.signatureFormat = format;
320
+ }
321
+ function aesKey(key, label) {
322
+ if (typeof key === "string") {
323
+ if (!AES_KEY_BYTES.has(utf8ByteLength(key)))
324
+ throw aesKeyLength(label);
325
+ return { value: key, encoding: "utf8" };
326
+ }
327
+ if (key instanceof Uint8Array) {
328
+ if (!AES_KEY_BYTES.has(key.length))
329
+ throw aesKeyLength(label);
330
+ return { value: encodeBase64(key), encoding: "base64" };
331
+ }
332
+ if (isRecord(key) && "secret" in key && Object.keys(key).every(name => name === "secret" || name === "encoding")) {
333
+ const reference = { secret: requireSecretName(key.secret, `${label} key.secret`) };
334
+ if (key.encoding !== undefined) {
335
+ if (typeof key.encoding !== "string" || !KEY_ENCODINGS.has(key.encoding)) {
336
+ throw new ValidationError(`${label} key.encoding must be "utf8", "base64" or "hex"`);
337
+ }
338
+ reference.encoding = key.encoding;
339
+ }
340
+ return reference;
341
+ }
342
+ throw new ValidationError(`${label} key must be a string, a Uint8Array or { secret: name }`);
343
+ }
344
+ function asymmetricKey(key, label) {
345
+ if (typeof key === "string") {
346
+ if (key.trim().length === 0)
347
+ throw new ValidationError(`${label} must not be empty`);
348
+ if (key.length > MAX_KEY_CHARS)
349
+ throw new ValidationError(`${label} must not exceed ${MAX_KEY_CHARS} characters`);
350
+ return { value: key };
351
+ }
352
+ if (isRecord(key) && Object.keys(key).length === 1 && "secret" in key) {
353
+ return { secret: requireSecretName(key.secret, `${label}.secret`) };
354
+ }
355
+ throw new ValidationError(`${label} must be PEM text, base64 DER or { secret: name }`);
356
+ }
357
+ function plaintext(payload, output) {
358
+ if (!isRecord(payload) || typeof payload.data !== "string") {
359
+ throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Decryption result is invalid");
360
+ }
361
+ if (output !== "bytes")
362
+ return payload.data;
363
+ const bytes = decodeBase64(payload.data);
364
+ if (bytes === null)
365
+ throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Decryption result is invalid");
366
+ return bytes;
367
+ }
368
+ function aesKeyLength(label) {
369
+ return new ValidationError(`${label} key must be 16, 24 or 32 bytes`);
370
+ }
76
371
  function hmacKey(key) {
77
372
  if (typeof key === "string") {
78
373
  if (key.length === 0)
package/dist/index.d.ts CHANGED
@@ -14,8 +14,8 @@ export { defineJob } from "./jobs.js";
14
14
  export type { JobSchedule, JobConfig, JobManifest, JobDefinition, JobInfo, EnqueueOptions, EnqueueResult, JobsApi, JobContext, JobHandler, } from "./jobs.js";
15
15
  export type { SecretsApi } from "./secrets.js";
16
16
  export { crypto } from "./crypto.js";
17
- export type { CryptoApi } from "./crypto.js";
18
- export type { CurrentWorkspace, CurrentWorkspaceMembership, CurrentUser, UserInvocationContext, SystemInvocationContext, InboundInvocationContext, InvocationContext, } from "./invocation.js";
17
+ export type { CryptoApi, BinaryEncoding, DecryptOutput, SecretKeyReference, AesKey, AsymmetricKey, AesMode, AesEncryptOptions, AesEncryptResult, AesDecryptOptions, RsaPadding, RsaEncryptOptions, RsaDecryptOptions, SignatureAlgorithm, SignatureOptions, } from "./crypto.js";
18
+ export type { CurrentWorkspace, CurrentWorkspaceMembership, CurrentWorkspaceRole, CurrentUser, UserInvocationContext, SystemInvocationContext, InboundInvocationContext, InvocationContext, } from "./invocation.js";
19
19
  export { createRouter } from "./router.js";
20
20
  export type { ScriptRouter } from "./router.js";
21
21
  export type { RequestMethod, ScriptRequest, ScriptQuery, ScriptHeaders, ScriptPathParams, } from "./request.js";
@@ -32,6 +32,8 @@ function userSnapshot(raw) {
32
32
  ...optionalStringFields(membershipRaw, ["personnelId", "language", "timezone"]),
33
33
  ...(membershipRaw.personnelId === undefined && typeof raw.personnelId === "string" && raw.personnelId !== ""
34
34
  ? { personnelId: raw.personnelId } : {}),
35
+ isSuperAdmin: superAdminFlag(membershipRaw.isSuperAdmin),
36
+ roles: roleSnapshots(membershipRaw.roles),
35
37
  });
36
38
  return Object.freeze({
37
39
  accountId: requiredString(raw.accountId, "account id"),
@@ -39,6 +41,28 @@ function userSnapshot(raw) {
39
41
  membership,
40
42
  });
41
43
  }
44
+ // A Runtime or development host that predates these fields omits them; the tolerant
45
+ // defaults keep project code working against it.
46
+ function superAdminFlag(value) {
47
+ if (value === undefined)
48
+ return false;
49
+ if (typeof value !== "boolean")
50
+ throw new ValidationError("Invalid invocation isSuperAdmin");
51
+ return value;
52
+ }
53
+ function roleSnapshots(value) {
54
+ if (value === undefined)
55
+ return Object.freeze([]);
56
+ if (!Array.isArray(value))
57
+ throw new ValidationError("Invalid invocation roles");
58
+ return Object.freeze(value.map((role) => {
59
+ if (!isRecord(role) || typeof role.id !== "string" || role.id === "" || typeof role.name !== "string") {
60
+ throw new ValidationError("Invalid invocation role");
61
+ }
62
+ // Only the documented keys are copied so that no other role metadata reaches project code.
63
+ return Object.freeze({ id: role.id, name: role.name });
64
+ }));
65
+ }
42
66
  function inboundSnapshot(raw) {
43
67
  if (!isRecord(raw))
44
68
  throw new ValidationError("Invalid invocation identity metadata");
@@ -9,11 +9,20 @@ export interface CurrentWorkspace {
9
9
  readonly timeFormat?: string;
10
10
  readonly numberFormat?: string;
11
11
  }
12
+ /** A role assigned to the current user in the current workspace. */
13
+ export interface CurrentWorkspaceRole {
14
+ readonly id: string;
15
+ readonly name: string;
16
+ }
12
17
  /** Public membership metadata for the current user in the current workspace. */
13
18
  export interface CurrentWorkspaceMembership {
14
19
  readonly personnelId?: string;
15
20
  readonly language?: string;
16
21
  readonly timezone?: string;
22
+ /** True when one of the user's roles is the workspace's highest administrator (Super Admin) role. */
23
+ readonly isSuperAdmin: boolean;
24
+ /** Roles assigned to the user in this workspace, sorted by name. Compare roles by `id`. */
25
+ readonly roles: readonly CurrentWorkspaceRole[];
17
26
  }
18
27
  /** Public account metadata for the authenticated user who initiated the invocation. */
19
28
  export interface CurrentUser {
@@ -107,10 +107,17 @@ interface CurrentWorkspace {
107
107
  readonly numberFormat?: string;
108
108
  }
109
109
 
110
+ interface CurrentWorkspaceRole {
111
+ readonly id: string;
112
+ readonly name: string;
113
+ }
114
+
110
115
  interface CurrentWorkspaceMembership {
111
116
  readonly personnelId?: string;
112
117
  readonly language?: string;
113
118
  readonly timezone?: string;
119
+ readonly isSuperAdmin: boolean; // Holds the workspace's Super Admin role
120
+ readonly roles: readonly CurrentWorkspaceRole[]; // Sorted by name
114
121
  }
115
122
 
116
123
  interface CurrentUser {
@@ -178,6 +185,38 @@ the authenticated request context. Raw authentication data, tokens, inbound keys
178
185
  and credentials are not included. A handler called outside Cogover has no
179
186
  authenticated invocation snapshot.
180
187
 
188
+ ### Workspace roles of the current user
189
+
190
+ `user.membership` describes the caller's membership in the current workspace:
191
+
192
+ - `isSuperAdmin` is `true` when one of the user's roles is the workspace's
193
+ highest administrator (Super Admin) role, otherwise `false`.
194
+ - `roles` lists the roles assigned to the user in the current workspace, sorted
195
+ by name. Each `CurrentWorkspaceRole` has only an `id` and a `name`; the list is
196
+ empty when the user has no role. Role permissions are not exposed.
197
+
198
+ Compare roles by `id`: a role can be renamed, and the same role name has a
199
+ different `id` in each workspace. Record and field access is still enforced by
200
+ Cogover under the user's identity, so use these fields for business rules, such
201
+ as who may approve an order, not as a replacement for security rules.
202
+
203
+ ```typescript
204
+ const APPROVER_ROLE_ID = "RO6P2N1K9X4A";
205
+
206
+ export default defineScript(({ invocation }) => {
207
+ const user = invocation.user;
208
+ const canApprove = user !== null && (user.membership.isSuperAdmin
209
+ || user.membership.roles.some((role) => role.id === APPROVER_ROLE_ID));
210
+ return {canApprove};
211
+ });
212
+ ```
213
+
214
+ HTTP invocations reflect the user's roles at the time of the request. Record
215
+ triggers and background jobs may see a role change up to about one minute late.
216
+ In local development with the Cogover Dev CLI, the values are captured when the
217
+ development session starts; restart `cogover-dev` to pick up role changes. A
218
+ `system` or `inbound` invocation has `user: null` and therefore no membership.
219
+
181
220
  ### `createRouter<TSchema = EffectiveWorkspaceObjects>(): ScriptRouter<TSchema>`
182
221
 
183
222
  Creates an independent router. `TSchema extends object` defaults to the effective
@@ -618,11 +657,11 @@ a request that only validates input without saving.
618
657
 
619
658
  - **Read-only.** A before-change trigger may read records and schema, but every
620
659
  record write, `fetch`, lock, state write, push message, `jobs.enqueue`, `secrets.get`,
621
- and `crypto.hmacSha256` with a `{ secret }` key is refused with
660
+ and every `crypto` operation with a `{ secret }` key is refused with
622
661
  `PermissionDeniedError` whose `details.reason` is `"TRIGGER_READ_ONLY"`. This
623
- applies to every identity, including `data.asSystem()`. `crypto.sha256`,
624
- `crypto.hmacSha256` with an explicit key, `crypto.randomBytes`,
625
- `crypto.randomUUID`, and `crypto.timingSafeEqual` remain available.
662
+ applies to every identity, including `data.asSystem()`. Every `crypto` operation
663
+ with a key given in the call remains available, as do `crypto.sha256`,
664
+ `crypto.randomBytes`, `crypto.randomUUID`, and `crypto.timingSafeEqual`.
626
665
  - **Identity.** `data.object()` acts as the user who made the change, with that
627
666
  user's permissions, and `invocation` describes the same user. When a change has
628
667
  no user, `invocation.identity` is `"system"` and `data.object()` works only if the
@@ -1122,18 +1161,32 @@ secrets only when its administrator allowed it, otherwise the reason is
1122
1161
  same name again in the same invocation returns the cached value. When secrets are
1123
1162
  not enabled for the Workspace, the error is `CogoverApiError` with
1124
1163
  `code: "SECRETS_DISABLED"`. Never write a secret value to the log, to a record, to
1125
- state, or to a response. To sign data with a secret without reading it, use
1126
- `crypto.hmacSha256({ secret: name }, data)`.
1164
+ state, or to a response. To sign, encrypt, or decrypt with a secret without
1165
+ reading it, pass `{ secret: name }` as the key of a [`crypto`](#cryptography)
1166
+ operation.
1127
1167
 
1128
1168
  ## Cryptography
1129
1169
 
1130
- `crypto` provides hashing, message authentication, and randomness through
1131
- Cogover's managed implementation. Import it from `@cogover/sdk` or read it from
1132
- `context.crypto`; both are the same frozen object.
1170
+ `crypto` provides hashing, message authentication, randomness, AES and RSA
1171
+ encryption, and RSA and ECDSA signatures through Cogover's managed
1172
+ implementation. Import it from `@cogover/sdk` or read it from `context.crypto`;
1173
+ both are the same frozen object.
1133
1174
 
1134
1175
  ```typescript
1135
1176
  const crypto: CryptoApi;
1136
1177
 
1178
+ type BinaryEncoding = "base64" | "base64url" | "hex";
1179
+ type DecryptOutput = "utf8" | "bytes" | BinaryEncoding;
1180
+
1181
+ interface SecretKeyReference {
1182
+ readonly secret: string;
1183
+ }
1184
+ type AesKey =
1185
+ | string
1186
+ | Uint8Array
1187
+ | (SecretKeyReference & { readonly encoding?: "utf8" | "base64" | "hex" });
1188
+ type AsymmetricKey = string | SecretKeyReference;
1189
+
1137
1190
  interface CryptoApi {
1138
1191
  sha256(data: string | Uint8Array, encoding?: "hex" | "base64"): Promise<string>;
1139
1192
  hmacSha256(
@@ -1144,9 +1197,41 @@ interface CryptoApi {
1144
1197
  randomBytes(length: number): Promise<Uint8Array>;
1145
1198
  randomUUID(): Promise<string>;
1146
1199
  timingSafeEqual(a: string | Uint8Array, b: string | Uint8Array): boolean;
1200
+
1201
+ aesEncrypt(key: AesKey, data: string | Uint8Array, options?: AesEncryptOptions): Promise<AesEncryptResult>;
1202
+ aesDecrypt(key: AesKey, ciphertext: string | Uint8Array, options: AesDecryptOptions): Promise<string>;
1203
+ aesDecrypt(
1204
+ key: AesKey,
1205
+ ciphertext: string | Uint8Array,
1206
+ options: AesDecryptOptions & { readonly output: "bytes" },
1207
+ ): Promise<Uint8Array>;
1208
+ rsaEncrypt(publicKey: AsymmetricKey, data: string | Uint8Array, options?: RsaEncryptOptions): Promise<string>;
1209
+ rsaDecrypt(privateKey: AsymmetricKey, ciphertext: string | Uint8Array, options?: RsaDecryptOptions): Promise<string>;
1210
+ rsaDecrypt(
1211
+ privateKey: AsymmetricKey,
1212
+ ciphertext: string | Uint8Array,
1213
+ options: RsaDecryptOptions & { readonly output: "bytes" },
1214
+ ): Promise<Uint8Array>;
1215
+ sign(
1216
+ algorithm: SignatureAlgorithm,
1217
+ privateKey: AsymmetricKey,
1218
+ data: string | Uint8Array,
1219
+ options?: SignatureOptions,
1220
+ ): Promise<string>;
1221
+ verify(
1222
+ algorithm: SignatureAlgorithm,
1223
+ publicKey: AsymmetricKey,
1224
+ data: string | Uint8Array,
1225
+ signature: string | Uint8Array,
1226
+ options?: SignatureOptions,
1227
+ ): Promise<boolean>;
1147
1228
  }
1148
1229
  ```
1149
1230
 
1231
+ `aesDecrypt` and `rsaDecrypt` return a string unless `output` is `"bytes"`; when
1232
+ `output` is only known as a `DecryptOutput`, the result type is
1233
+ `string | Uint8Array`.
1234
+
1150
1235
  ```typescript
1151
1236
  import { crypto } from "@cogover/sdk";
1152
1237
 
@@ -1158,13 +1243,14 @@ if (!crypto.timingSafeEqual(signature, request.headers["x-signature"] ?? "")) {
1158
1243
  const token = await crypto.randomUUID();
1159
1244
  ```
1160
1245
 
1246
+ ### Hashing, HMAC, and randomness
1247
+
1161
1248
  - `sha256(data, encoding?)` returns the SHA-256 digest of `data`. A string is
1162
1249
  hashed as UTF-8; a `Uint8Array` is hashed as is. `encoding` is `"hex"` (default)
1163
1250
  or `"base64"`.
1164
1251
  - `hmacSha256(key, data, encoding?)` returns the HMAC-SHA256 of `data`. The key is a
1165
1252
  non-empty string (UTF-8), a non-empty `Uint8Array`, or `{ secret: name }` to use
1166
- a project secret without reading its value; the named secret must be readable by
1167
- `secrets.get` in the same context and counts as one secret read.
1253
+ a project secret without reading its value.
1168
1254
  - `randomBytes(length)` returns `length` cryptographically secure random bytes;
1169
1255
  `length` is an integer from 1 through 1024.
1170
1256
  - `randomUUID()` returns a random version 4 UUID such as
@@ -1173,12 +1259,218 @@ const token = await crypto.randomUUID();
1173
1259
  returns `false` for different lengths. Strings are compared as UTF-8 bytes. Use
1174
1260
  it for every comparison of a signature, token, or key.
1175
1261
 
1176
- `data` and an explicit key are limited to 256 KiB; larger values and invalid
1177
- arguments throw `ValidationError` before the call. Every operation except
1178
- `timingSafeEqual` is a capability call and counts towards the invocation's limits.
1179
- The operations work in every context, including before-change triggers, except that
1180
- a `{ secret }` key follows the rules of `secrets.get`. This version supports
1181
- SHA-256 only.
1262
+ ### Keys
1263
+
1264
+ Every key can be given in the call or as `{ secret: name }`. A secret key is
1265
+ resolved by Cogover and its value never reaches project code; the named secret
1266
+ must be readable by `secrets.get` in the same context and counts as one secret
1267
+ read. Store every private key and every AES key as a project secret; a key written
1268
+ in source code is visible to everyone who can read the project.
1269
+
1270
+ - **AES keys** are 16, 24, or 32 bytes (AES-128, AES-192, AES-256). A string is
1271
+ used as its UTF-8 bytes and a `Uint8Array` as is. For a secret, `encoding` states
1272
+ how the secret's value holds the key: `"utf8"` (default) uses the text itself,
1273
+ and `"base64"` or `"hex"` decode it first, ignoring surrounding whitespace.
1274
+ - **RSA and EC keys** (`AsymmetricKey`) are PEM text, or the base64 body of one
1275
+ without the `-----BEGIN` lines (DER as `PUBLIC KEY` for a public key and as
1276
+ `PRIVATE KEY` for a private key). Text before the PEM block and an
1277
+ `EC PARAMETERS` block are ignored.
1278
+
1279
+ | Key | Accepted PEM types |
1280
+ |---|---|
1281
+ | Public key (`rsaEncrypt`, `verify`) | `PUBLIC KEY` (SubjectPublicKeyInfo), `RSA PUBLIC KEY` (PKCS #1), `CERTIFICATE` (X.509; only its public key is used) |
1282
+ | Private key (`rsaDecrypt`, `sign`) | `PRIVATE KEY` (PKCS #8), `RSA PRIVATE KEY` (PKCS #1), `EC PRIVATE KEY` (SEC1) |
1283
+
1284
+ RSA keys must be 2048 to 4096 bits. EC keys must use the P-256, P-384, or P-521
1285
+ curve. Encrypted private keys (`ENCRYPTED PRIVATE KEY`, or PEM with
1286
+ `Proc-Type` headers) and OpenSSH keys are not supported; store the unencrypted
1287
+ PKCS #8 key as a secret instead. Key text is limited to 16,384 characters. A
1288
+ certificate is not checked for expiry, revocation, or its issuer: it is only a
1289
+ container for the public key.
1290
+
1291
+ ### `crypto.aesEncrypt(key, data, options?): Promise<AesEncryptResult>`
1292
+
1293
+ ```typescript
1294
+ type AesMode = "GCM" | "CBC";
1295
+
1296
+ interface AesEncryptOptions {
1297
+ readonly mode?: AesMode; // Default "GCM"
1298
+ readonly iv?: string | Uint8Array; // Default: random
1299
+ readonly aad?: string | Uint8Array; // GCM only
1300
+ readonly separateTag?: boolean; // GCM only, default false
1301
+ readonly encoding?: BinaryEncoding; // Default "base64"
1302
+ }
1303
+
1304
+ interface AesEncryptResult {
1305
+ readonly ciphertext: string;
1306
+ readonly iv: string;
1307
+ readonly tag?: string; // Only with separateTag
1308
+ }
1309
+ ```
1310
+
1311
+ Encrypts `data` (a string is encoded as UTF-8) and returns the ciphertext and IV in
1312
+ `encoding`.
1313
+
1314
+ - `"GCM"` (default) is authenticated encryption: decryption detects any change to
1315
+ the ciphertext, IV, tag, or `aad`. `ciphertext` is the encrypted data followed by
1316
+ the 16-byte authentication tag, the form used by Java, .NET, and Web Crypto.
1317
+ With `separateTag: true` the tag is returned in `tag` instead, as systems built
1318
+ on Node.js or OpenSSL usually expect.
1319
+ - `"CBC"` uses PKCS #7 padding. It does not detect changes to the ciphertext; use
1320
+ it only when an external system requires it, and authenticate the ciphertext
1321
+ separately, for example with `hmacSha256`.
1322
+ - Without `iv`, a random IV is generated: 12 bytes for GCM and 16 bytes for CBC.
1323
+ A given `iv` must be 12 to 16 bytes for GCM and exactly 16 bytes for CBC; a
1324
+ string `iv` is decoded with `encoding`. **Never use the same IV twice with the
1325
+ same GCM key**: doing so breaks both confidentiality and authentication. Pass
1326
+ an IV only when an external system dictates it.
1327
+ - `aad` is additional data that is authenticated but not encrypted, such as a
1328
+ record ID; a string is encoded as UTF-8. The same `aad` must be given to
1329
+ decryption.
1330
+
1331
+ ### `crypto.aesDecrypt(key, ciphertext, options): Promise<string | Uint8Array>`
1332
+
1333
+ ```typescript
1334
+ interface AesDecryptOptions {
1335
+ readonly mode?: AesMode; // Default "GCM"
1336
+ readonly iv: string | Uint8Array;
1337
+ readonly tag?: string | Uint8Array; // GCM only, when not appended to the ciphertext
1338
+ readonly aad?: string | Uint8Array; // GCM only
1339
+ readonly encoding?: BinaryEncoding; // Of a string ciphertext, iv, and tag; default "base64"
1340
+ readonly output?: DecryptOutput; // Default "utf8"
1341
+ }
1342
+ ```
1343
+
1344
+ Decrypts an AES ciphertext. `iv` is required. In GCM mode, the last 16 bytes of
1345
+ `ciphertext` are the tag unless `tag` is given. `output` selects the result:
1346
+ `"utf8"` (default) decodes the plaintext as UTF-8 text and throws
1347
+ `ValidationError` if it is not valid UTF-8, `"bytes"` returns a `Uint8Array`, and
1348
+ `"base64"`, `"base64url"`, or `"hex"` return the plaintext bytes in that encoding.
1349
+
1350
+ A wrong key, IV, tag, or `aad`, a modified ciphertext, or invalid CBC padding
1351
+ throws `CogoverApiError` with `code: "DECRYPTION_FAILED"`. The error is the same
1352
+ for every cause, so that the result reveals nothing about the key or plaintext.
1353
+
1354
+ ```typescript
1355
+ import { crypto, CogoverApiError, defineScript } from "@cogover/sdk";
1356
+
1357
+ export default defineScript(async ({ request }) => {
1358
+ const { data, iv, tag } = request.body as { data: string; iv: string; tag: string };
1359
+ try {
1360
+ const json = await crypto.aesDecrypt({ secret: "partner_aes_key", encoding: "base64" }, data, { iv, tag });
1361
+ return { payment: JSON.parse(json) };
1362
+ } catch (error) {
1363
+ if (error instanceof CogoverApiError && error.code === "DECRYPTION_FAILED") {
1364
+ return { r: 1001, msg: "The payload could not be decrypted." };
1365
+ }
1366
+ throw error;
1367
+ }
1368
+ });
1369
+ ```
1370
+
1371
+ ### `crypto.rsaEncrypt(publicKey, data, options?)` and `crypto.rsaDecrypt(privateKey, ciphertext, options?)`
1372
+
1373
+ ```typescript
1374
+ type RsaPadding = "OAEP-SHA256" | "OAEP-SHA1" | "PKCS1";
1375
+
1376
+ interface RsaEncryptOptions {
1377
+ readonly padding?: RsaPadding; // Default "OAEP-SHA256"
1378
+ readonly encoding?: BinaryEncoding; // Of the ciphertext; default "base64"
1379
+ }
1380
+
1381
+ interface RsaDecryptOptions {
1382
+ readonly padding?: RsaPadding; // Default "OAEP-SHA256"
1383
+ readonly encoding?: BinaryEncoding; // Of a string ciphertext; default "base64"
1384
+ readonly output?: DecryptOutput; // Default "utf8"
1385
+ }
1386
+ ```
1387
+
1388
+ `rsaEncrypt` encrypts `data` (a string is encoded as UTF-8) with an RSA public key
1389
+ and returns the ciphertext in `encoding`. `rsaDecrypt` decrypts it with the
1390
+ matching private key and returns the plaintext as `output`, like `aesDecrypt`.
1391
+
1392
+ - `"OAEP-SHA256"` (default) is RSA-OAEP with SHA-256, and its mask generation
1393
+ function MGF1 also uses SHA-256, as in Web Crypto, Node.js, and OpenSSL.
1394
+ `"OAEP-SHA1"` uses SHA-1 for both. Some Java code written as
1395
+ `OAEPWithSHA-256AndMGF1Padding` keeps MGF1 on SHA-1 and is compatible with
1396
+ neither; ask the other system which digest its MGF1 uses.
1397
+ - `"PKCS1"` is PKCS #1 v1.5 padding. Use it only when an external system requires
1398
+ it.
1399
+ - RSA encrypts only a small amount of data: at most the key size in bytes minus
1400
+ 66 bytes for `"OAEP-SHA256"`, minus 42 for `"OAEP-SHA1"`, and minus 11 for
1401
+ `"PKCS1"` — 190, 214, and 245 bytes for a 2048-bit key. Larger data throws
1402
+ `ValidationError`. To send more, encrypt the data with `aesEncrypt` under a
1403
+ random key from `randomBytes(32)` and encrypt only that key with `rsaEncrypt`.
1404
+ - A decryption that fails for any reason throws `CogoverApiError` with
1405
+ `code: "DECRYPTION_FAILED"`.
1406
+
1407
+ ```typescript
1408
+ const cardToken = await crypto.rsaEncrypt({ secret: "bank_public_key" }, "4111111111111111");
1409
+ const plain = await crypto.rsaDecrypt({ secret: "our_private_key" }, request.body.data as string);
1410
+ ```
1411
+
1412
+ ### `crypto.sign(algorithm, privateKey, data, options?)` and `crypto.verify(algorithm, publicKey, data, signature, options?)`
1413
+
1414
+ ```typescript
1415
+ type SignatureAlgorithm =
1416
+ | "RSA-SHA1" | "RSA-SHA256" | "RSA-SHA384" | "RSA-SHA512"
1417
+ | "RSA-PSS-SHA256" | "RSA-PSS-SHA384" | "RSA-PSS-SHA512"
1418
+ | "ECDSA-SHA256" | "ECDSA-SHA384" | "ECDSA-SHA512";
1419
+
1420
+ interface SignatureOptions {
1421
+ readonly encoding?: BinaryEncoding; // Of the signature; default "base64"
1422
+ readonly signatureFormat?: "der" | "ieee-p1363"; // ECDSA only; default "der"
1423
+ }
1424
+ ```
1425
+
1426
+ `sign` signs `data` (a string is encoded as UTF-8) with a private key and returns
1427
+ the signature in `encoding`. `verify` returns `true` when `signature` is a valid
1428
+ signature of `data` for the public key, and `false` otherwise, including when the
1429
+ signature cannot be decoded or has the wrong length; a signature normally comes
1430
+ from the party being verified, so a malformed one is not an error. An invalid
1431
+ key or algorithm still throws `ValidationError`.
1432
+
1433
+ - `RSA-SHA*` is RSASSA-PKCS1-v1_5 and requires an RSA key. `RSA-SHA1` exists only
1434
+ to verify signatures of systems that still use it; do not use it for new
1435
+ signatures.
1436
+ - `RSA-PSS-SHA*` is RSASSA-PSS with MGF1 on the same digest and a salt as long as
1437
+ the digest (32, 48, or 64 bytes), and requires an RSA key.
1438
+ - `ECDSA-SHA*` requires an EC key. `signatureFormat` is `"der"` (ASN.1, used by
1439
+ OpenSSL and Java) or `"ieee-p1363"` (the fixed-length `r || s` form used by JWT
1440
+ and Web Crypto); it is rejected for RSA algorithms.
1441
+
1442
+ | JWT `alg` | `algorithm` | Options |
1443
+ |---|---|---|
1444
+ | `RS256`, `RS384`, `RS512` | `RSA-SHA256`, `RSA-SHA384`, `RSA-SHA512` | `{ encoding: "base64url" }` |
1445
+ | `PS256`, `PS384`, `PS512` | `RSA-PSS-SHA256`, `RSA-PSS-SHA384`, `RSA-PSS-SHA512` | `{ encoding: "base64url" }` |
1446
+ | `ES256`, `ES384`, `ES512` | `ECDSA-SHA256`, `ECDSA-SHA384`, `ECDSA-SHA512` | `{ encoding: "base64url", signatureFormat: "ieee-p1363" }` |
1447
+
1448
+ ```typescript
1449
+ // Verify an ES256 JWT issued by a partner. Also check its claims (exp, iss, aud) before trusting it.
1450
+ const [header, payload, signature] = token.split(".");
1451
+ const valid = await crypto.verify("ECDSA-SHA256", { secret: "partner_jwt_public_key" },
1452
+ `${header}.${payload}`, signature ?? "", { encoding: "base64url", signatureFormat: "ieee-p1363" });
1453
+ if (!valid) return response.empty({ status: 401 });
1454
+
1455
+ // Sign a request to a bank that expects SHA256withRSA in base64.
1456
+ const body = JSON.stringify(order);
1457
+ const bankSignature = await crypto.sign("RSA-SHA256", { secret: "bank_signing_key" }, body);
1458
+ ```
1459
+
1460
+ ### Limits and availability
1461
+
1462
+ `data`, `aad`, and an explicit HMAC key are limited to 256 KiB, and a ciphertext
1463
+ to 256 KiB plus its tag; larger values and invalid arguments throw
1464
+ `ValidationError` before the call. The key, algorithm, and option errors that
1465
+ Cogover detects, such as a key of the wrong size or type, also throw
1466
+ `ValidationError`. Every operation except `timingSafeEqual` is a capability call
1467
+ and counts towards the invocation's limits.
1468
+
1469
+ The operations work in every context, including before-change triggers, with a key
1470
+ given in the call. A `{ secret }` key follows the rules of `secrets.get`: a
1471
+ before-change trigger is refused with `PermissionDeniedError`
1472
+ (`details.reason === "TRIGGER_READ_ONLY"`) and a local development session without
1473
+ secret access with `details.reason === "SECRETS_NOT_ALLOWED"`.
1182
1474
 
1183
1475
  ## Inbound webhooks
1184
1476
 
@@ -1927,7 +2219,9 @@ that throws it rejects the write like any other failure.
1927
2219
  `jobs.enqueue`, `secrets.get`, and `crypto` fail with `ValidationError`,
1928
2220
  `PermissionDeniedError`, or `RateLimitError` as described in their sections, and
1929
2221
  with `CogoverApiError` whose `code` is `JOBS_DISABLED` or `SECRETS_DISABLED` when
1930
- the feature is not enabled for the Workspace.
2222
+ the feature is not enabled for the Workspace. `crypto.aesDecrypt` and
2223
+ `crypto.rsaDecrypt` throw `CogoverApiError` with `code: "DECRYPTION_FAILED"` when
2224
+ the ciphertext cannot be decrypted.
1931
2225
 
1932
2226
  Scripts can catch `CogoverApiError`, inspect `error.r`, and return their own client
1933
2227
  error, such as `{ r: 1001, msg: "You cannot update this order." }`, without exposing
@@ -92,6 +92,38 @@ Use the Record API only when you need richer, current Personnel business fields
92
92
  such as department, position, manager, or custom fields. The snapshot intentionally
93
93
  contains only documented fields and omits credentials and raw authentication data.
94
94
 
95
+ ### Allow an action by workspace role
96
+
97
+ `invocation.user.membership` also tells whether the caller is a Super Admin of the
98
+ current workspace and which roles the caller holds there. For example, allow an
99
+ approval only for Super Admins or users holding the approver role:
100
+
101
+ ```typescript
102
+ const APPROVER_ROLE_ID = "RO6P2N1K9X4A";
103
+
104
+ export default defineScript(({ invocation }) => {
105
+ const user = invocation.user;
106
+ const canApprove = user !== null && (user.membership.isSuperAdmin
107
+ || user.membership.roles.some((role) => role.id === APPROVER_ROLE_ID));
108
+ if (!canApprove) {
109
+ return {approved: false, reason: "Only approvers can approve this order"};
110
+ }
111
+ return {approved: true};
112
+ });
113
+ ```
114
+
115
+ - The values describe the caller's roles in the current workspace. Each role has
116
+ only an `id` and a `name`; role permissions are not exposed.
117
+ - Compare roles by `id`, not by name: a role can be renamed, and role IDs differ
118
+ between workspaces.
119
+ - Cogover still enforces record and field access under the user's identity. Use
120
+ these fields for business rules, not as a replacement for security rules.
121
+ - HTTP invocations reflect the roles at the time of the request. Record triggers
122
+ and background jobs may see a role change up to about one minute late.
123
+ - In local development with the Cogover Dev CLI, the values are captured when the
124
+ development session starts. Restart `cogover-dev` to pick up role changes.
125
+ - `system` and `inbound` invocations have `user: null`, so there is no membership.
126
+
95
127
  ## Filter and sort records
96
128
 
97
129
  ```typescript
@@ -206,6 +238,58 @@ to state, or to a response, and prefer a credential over `secrets.get` whenever
206
238
  value is only needed for an HTTP header. Secrets and credentials are not available
207
239
  in before-change triggers.
208
240
 
241
+ ## Encrypt, decrypt, and sign data
242
+
243
+ `crypto` also encrypts and signs with keys that stay in project secrets. Pass
244
+ `{ secret: name }` as the key: Cogover resolves it and the value never enters the
245
+ code.
246
+
247
+ ```typescript
248
+ import { createRouter, crypto, fetch } from "@cogover/sdk";
249
+
250
+ const router = createRouter();
251
+ router.post("/payments", async ({ request, response }) => {
252
+ // AES-256-GCM with a random IV; the partner receives the ciphertext and the IV.
253
+ const aesKey = { secret: "partner_aes_key", encoding: "base64" } as const;
254
+ const sealed = await crypto.aesEncrypt(aesKey, JSON.stringify(request.body));
255
+
256
+ // RSA: encrypt a small value with the partner's public key, sign with our private key.
257
+ const cardToken = await crypto.rsaEncrypt({ secret: "partner_public_key" }, "4111111111111111");
258
+ const body = JSON.stringify({ ...sealed, cardToken });
259
+ const signature = await crypto.sign("RSA-SHA256", { secret: "our_signing_key" }, body);
260
+ const reply = await fetch("https://partner.example.com/payments", {
261
+ method: "POST",
262
+ headers: { "content-type": "application/json", "x-signature": signature },
263
+ body,
264
+ });
265
+
266
+ // Verify the partner's ECDSA signature before trusting the reply.
267
+ const replyBody = await reply.text();
268
+ const valid = await crypto.verify("ECDSA-SHA256", { secret: "partner_public_key_ec" }, replyBody,
269
+ reply.headers.get("x-signature") ?? "");
270
+ return valid ? response.json(JSON.parse(replyBody)) : response.empty({ status: 502 });
271
+ });
272
+ export default router.toHandler();
273
+ ```
274
+
275
+ - `aesEncrypt`/`aesDecrypt` use AES-GCM by default; `mode: "CBC"` exists for
276
+ systems that require it. Leave out `iv` so that a new random IV is used every
277
+ time.
278
+ - `rsaEncrypt`/`rsaDecrypt` use RSA-OAEP with SHA-256 by default and encrypt at
279
+ most a few hundred bytes; encrypt larger data with AES and only the AES key
280
+ with RSA.
281
+ - `sign`/`verify` support RSA (PKCS #1 v1.5 and PSS) and ECDSA, including the
282
+ `base64url` and `ieee-p1363` forms used by JWT. `verify` returns `false` for a
283
+ malformed signature instead of throwing.
284
+ - A failed decryption throws `CogoverApiError` with `code: "DECRYPTION_FAILED"`.
285
+ - Keys are PEM text in a secret: store private keys unencrypted in PKCS #8, PKCS #1,
286
+ or SEC1 form; public keys may be a certificate. RSA keys must be 2048 to 4096 bits
287
+ and EC keys P-256, P-384, or P-521.
288
+
289
+ With a key from a secret, these operations follow the rules of secrets and are
290
+ not available in before-change triggers. The API reference describes every option
291
+ and the JWT algorithm names.
292
+
209
293
  ## Permissions and limits
210
294
 
211
295
  - Cogover authentication credentials are never exposed to module code. Access is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cogover/sdk",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "TypeScript SDK for developing Custom Backend Modules on Cogover",
5
5
  "type": "module",
6
6
  "sideEffects": false,