@cogover/sdk 0.8.0 → 0.9.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 +11 -1
- package/dist/crypto.d.ts +114 -1
- package/dist/crypto.js +295 -0
- package/dist/index.d.ts +1 -1
- package/docs/en/api-reference.md +273 -18
- package/docs/en/usage-guide.md +52 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -318,7 +318,17 @@ export default router.toHandler();
|
|
|
318
318
|
|
|
319
319
|
`crypto` — also importable from `@cogover/sdk` — provides `sha256`, `hmacSha256`
|
|
320
320
|
(with a string, byte, or `{ secret }` key), `randomBytes`, `randomUUID`, and the
|
|
321
|
-
constant-time `timingSafeEqual`.
|
|
321
|
+
constant-time `timingSafeEqual`. It also encrypts and signs: `aesEncrypt` and
|
|
322
|
+
`aesDecrypt` (AES-GCM or AES-CBC), `rsaEncrypt` and `rsaDecrypt` (RSA-OAEP or
|
|
323
|
+
PKCS #1 v1.5), and `sign` and `verify` (RSA, RSA-PSS, and ECDSA, including the JWT
|
|
324
|
+
signature formats). Keys may be PEM text or `{ secret: name }`, so private keys stay
|
|
325
|
+
in project secrets.
|
|
326
|
+
|
|
327
|
+
```typescript
|
|
328
|
+
const sealed = await crypto.aesEncrypt({ secret: "partner_aes_key", encoding: "base64" }, JSON.stringify(order));
|
|
329
|
+
const signature = await crypto.sign("RSA-SHA256", { secret: "our_signing_key" }, JSON.stringify(sealed));
|
|
330
|
+
const valid = await crypto.verify("ECDSA-SHA256", { secret: "partner_public_key" }, body, signatureHeader);
|
|
331
|
+
```
|
|
322
332
|
|
|
323
333
|
## Record API
|
|
324
334
|
|
package/dist/crypto.d.ts
CHANGED
|
@@ -1,4 +1,93 @@
|
|
|
1
|
-
/**
|
|
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,7 +14,7 @@ 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";
|
|
17
|
+
export type { CryptoApi, BinaryEncoding, DecryptOutput, SecretKeyReference, AesKey, AsymmetricKey, AesMode, AesEncryptOptions, AesEncryptResult, AesDecryptOptions, RsaPadding, RsaEncryptOptions, RsaDecryptOptions, SignatureAlgorithm, SignatureOptions, } from "./crypto.js";
|
|
18
18
|
export type { CurrentWorkspace, CurrentWorkspaceMembership, CurrentUser, UserInvocationContext, SystemInvocationContext, InboundInvocationContext, InvocationContext, } from "./invocation.js";
|
|
19
19
|
export { createRouter } from "./router.js";
|
|
20
20
|
export type { ScriptRouter } from "./router.js";
|
package/docs/en/api-reference.md
CHANGED
|
@@ -618,11 +618,11 @@ a request that only validates input without saving.
|
|
|
618
618
|
|
|
619
619
|
- **Read-only.** A before-change trigger may read records and schema, but every
|
|
620
620
|
record write, `fetch`, lock, state write, push message, `jobs.enqueue`, `secrets.get`,
|
|
621
|
-
and `crypto
|
|
621
|
+
and every `crypto` operation with a `{ secret }` key is refused with
|
|
622
622
|
`PermissionDeniedError` whose `details.reason` is `"TRIGGER_READ_ONLY"`. This
|
|
623
|
-
applies to every identity, including `data.asSystem()`. `crypto
|
|
624
|
-
|
|
625
|
-
`crypto.randomUUID`, and `crypto.timingSafeEqual
|
|
623
|
+
applies to every identity, including `data.asSystem()`. Every `crypto` operation
|
|
624
|
+
with a key given in the call remains available, as do `crypto.sha256`,
|
|
625
|
+
`crypto.randomBytes`, `crypto.randomUUID`, and `crypto.timingSafeEqual`.
|
|
626
626
|
- **Identity.** `data.object()` acts as the user who made the change, with that
|
|
627
627
|
user's permissions, and `invocation` describes the same user. When a change has
|
|
628
628
|
no user, `invocation.identity` is `"system"` and `data.object()` works only if the
|
|
@@ -1122,18 +1122,32 @@ secrets only when its administrator allowed it, otherwise the reason is
|
|
|
1122
1122
|
same name again in the same invocation returns the cached value. When secrets are
|
|
1123
1123
|
not enabled for the Workspace, the error is `CogoverApiError` with
|
|
1124
1124
|
`code: "SECRETS_DISABLED"`. Never write a secret value to the log, to a record, to
|
|
1125
|
-
state, or to a response. To sign
|
|
1126
|
-
`
|
|
1125
|
+
state, or to a response. To sign, encrypt, or decrypt with a secret without
|
|
1126
|
+
reading it, pass `{ secret: name }` as the key of a [`crypto`](#cryptography)
|
|
1127
|
+
operation.
|
|
1127
1128
|
|
|
1128
1129
|
## Cryptography
|
|
1129
1130
|
|
|
1130
|
-
`crypto` provides hashing, message authentication, and
|
|
1131
|
-
|
|
1132
|
-
|
|
1131
|
+
`crypto` provides hashing, message authentication, randomness, AES and RSA
|
|
1132
|
+
encryption, and RSA and ECDSA signatures through Cogover's managed
|
|
1133
|
+
implementation. Import it from `@cogover/sdk` or read it from `context.crypto`;
|
|
1134
|
+
both are the same frozen object.
|
|
1133
1135
|
|
|
1134
1136
|
```typescript
|
|
1135
1137
|
const crypto: CryptoApi;
|
|
1136
1138
|
|
|
1139
|
+
type BinaryEncoding = "base64" | "base64url" | "hex";
|
|
1140
|
+
type DecryptOutput = "utf8" | "bytes" | BinaryEncoding;
|
|
1141
|
+
|
|
1142
|
+
interface SecretKeyReference {
|
|
1143
|
+
readonly secret: string;
|
|
1144
|
+
}
|
|
1145
|
+
type AesKey =
|
|
1146
|
+
| string
|
|
1147
|
+
| Uint8Array
|
|
1148
|
+
| (SecretKeyReference & { readonly encoding?: "utf8" | "base64" | "hex" });
|
|
1149
|
+
type AsymmetricKey = string | SecretKeyReference;
|
|
1150
|
+
|
|
1137
1151
|
interface CryptoApi {
|
|
1138
1152
|
sha256(data: string | Uint8Array, encoding?: "hex" | "base64"): Promise<string>;
|
|
1139
1153
|
hmacSha256(
|
|
@@ -1144,9 +1158,41 @@ interface CryptoApi {
|
|
|
1144
1158
|
randomBytes(length: number): Promise<Uint8Array>;
|
|
1145
1159
|
randomUUID(): Promise<string>;
|
|
1146
1160
|
timingSafeEqual(a: string | Uint8Array, b: string | Uint8Array): boolean;
|
|
1161
|
+
|
|
1162
|
+
aesEncrypt(key: AesKey, data: string | Uint8Array, options?: AesEncryptOptions): Promise<AesEncryptResult>;
|
|
1163
|
+
aesDecrypt(key: AesKey, ciphertext: string | Uint8Array, options: AesDecryptOptions): Promise<string>;
|
|
1164
|
+
aesDecrypt(
|
|
1165
|
+
key: AesKey,
|
|
1166
|
+
ciphertext: string | Uint8Array,
|
|
1167
|
+
options: AesDecryptOptions & { readonly output: "bytes" },
|
|
1168
|
+
): Promise<Uint8Array>;
|
|
1169
|
+
rsaEncrypt(publicKey: AsymmetricKey, data: string | Uint8Array, options?: RsaEncryptOptions): Promise<string>;
|
|
1170
|
+
rsaDecrypt(privateKey: AsymmetricKey, ciphertext: string | Uint8Array, options?: RsaDecryptOptions): Promise<string>;
|
|
1171
|
+
rsaDecrypt(
|
|
1172
|
+
privateKey: AsymmetricKey,
|
|
1173
|
+
ciphertext: string | Uint8Array,
|
|
1174
|
+
options: RsaDecryptOptions & { readonly output: "bytes" },
|
|
1175
|
+
): Promise<Uint8Array>;
|
|
1176
|
+
sign(
|
|
1177
|
+
algorithm: SignatureAlgorithm,
|
|
1178
|
+
privateKey: AsymmetricKey,
|
|
1179
|
+
data: string | Uint8Array,
|
|
1180
|
+
options?: SignatureOptions,
|
|
1181
|
+
): Promise<string>;
|
|
1182
|
+
verify(
|
|
1183
|
+
algorithm: SignatureAlgorithm,
|
|
1184
|
+
publicKey: AsymmetricKey,
|
|
1185
|
+
data: string | Uint8Array,
|
|
1186
|
+
signature: string | Uint8Array,
|
|
1187
|
+
options?: SignatureOptions,
|
|
1188
|
+
): Promise<boolean>;
|
|
1147
1189
|
}
|
|
1148
1190
|
```
|
|
1149
1191
|
|
|
1192
|
+
`aesDecrypt` and `rsaDecrypt` return a string unless `output` is `"bytes"`; when
|
|
1193
|
+
`output` is only known as a `DecryptOutput`, the result type is
|
|
1194
|
+
`string | Uint8Array`.
|
|
1195
|
+
|
|
1150
1196
|
```typescript
|
|
1151
1197
|
import { crypto } from "@cogover/sdk";
|
|
1152
1198
|
|
|
@@ -1158,13 +1204,14 @@ if (!crypto.timingSafeEqual(signature, request.headers["x-signature"] ?? "")) {
|
|
|
1158
1204
|
const token = await crypto.randomUUID();
|
|
1159
1205
|
```
|
|
1160
1206
|
|
|
1207
|
+
### Hashing, HMAC, and randomness
|
|
1208
|
+
|
|
1161
1209
|
- `sha256(data, encoding?)` returns the SHA-256 digest of `data`. A string is
|
|
1162
1210
|
hashed as UTF-8; a `Uint8Array` is hashed as is. `encoding` is `"hex"` (default)
|
|
1163
1211
|
or `"base64"`.
|
|
1164
1212
|
- `hmacSha256(key, data, encoding?)` returns the HMAC-SHA256 of `data`. The key is a
|
|
1165
1213
|
non-empty string (UTF-8), a non-empty `Uint8Array`, or `{ secret: name }` to use
|
|
1166
|
-
a project secret without reading its value
|
|
1167
|
-
`secrets.get` in the same context and counts as one secret read.
|
|
1214
|
+
a project secret without reading its value.
|
|
1168
1215
|
- `randomBytes(length)` returns `length` cryptographically secure random bytes;
|
|
1169
1216
|
`length` is an integer from 1 through 1024.
|
|
1170
1217
|
- `randomUUID()` returns a random version 4 UUID such as
|
|
@@ -1173,12 +1220,218 @@ const token = await crypto.randomUUID();
|
|
|
1173
1220
|
returns `false` for different lengths. Strings are compared as UTF-8 bytes. Use
|
|
1174
1221
|
it for every comparison of a signature, token, or key.
|
|
1175
1222
|
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1223
|
+
### Keys
|
|
1224
|
+
|
|
1225
|
+
Every key can be given in the call or as `{ secret: name }`. A secret key is
|
|
1226
|
+
resolved by Cogover and its value never reaches project code; the named secret
|
|
1227
|
+
must be readable by `secrets.get` in the same context and counts as one secret
|
|
1228
|
+
read. Store every private key and every AES key as a project secret; a key written
|
|
1229
|
+
in source code is visible to everyone who can read the project.
|
|
1230
|
+
|
|
1231
|
+
- **AES keys** are 16, 24, or 32 bytes (AES-128, AES-192, AES-256). A string is
|
|
1232
|
+
used as its UTF-8 bytes and a `Uint8Array` as is. For a secret, `encoding` states
|
|
1233
|
+
how the secret's value holds the key: `"utf8"` (default) uses the text itself,
|
|
1234
|
+
and `"base64"` or `"hex"` decode it first, ignoring surrounding whitespace.
|
|
1235
|
+
- **RSA and EC keys** (`AsymmetricKey`) are PEM text, or the base64 body of one
|
|
1236
|
+
without the `-----BEGIN` lines (DER as `PUBLIC KEY` for a public key and as
|
|
1237
|
+
`PRIVATE KEY` for a private key). Text before the PEM block and an
|
|
1238
|
+
`EC PARAMETERS` block are ignored.
|
|
1239
|
+
|
|
1240
|
+
| Key | Accepted PEM types |
|
|
1241
|
+
|---|---|
|
|
1242
|
+
| Public key (`rsaEncrypt`, `verify`) | `PUBLIC KEY` (SubjectPublicKeyInfo), `RSA PUBLIC KEY` (PKCS #1), `CERTIFICATE` (X.509; only its public key is used) |
|
|
1243
|
+
| Private key (`rsaDecrypt`, `sign`) | `PRIVATE KEY` (PKCS #8), `RSA PRIVATE KEY` (PKCS #1), `EC PRIVATE KEY` (SEC1) |
|
|
1244
|
+
|
|
1245
|
+
RSA keys must be 2048 to 4096 bits. EC keys must use the P-256, P-384, or P-521
|
|
1246
|
+
curve. Encrypted private keys (`ENCRYPTED PRIVATE KEY`, or PEM with
|
|
1247
|
+
`Proc-Type` headers) and OpenSSH keys are not supported; store the unencrypted
|
|
1248
|
+
PKCS #8 key as a secret instead. Key text is limited to 16,384 characters. A
|
|
1249
|
+
certificate is not checked for expiry, revocation, or its issuer: it is only a
|
|
1250
|
+
container for the public key.
|
|
1251
|
+
|
|
1252
|
+
### `crypto.aesEncrypt(key, data, options?): Promise<AesEncryptResult>`
|
|
1253
|
+
|
|
1254
|
+
```typescript
|
|
1255
|
+
type AesMode = "GCM" | "CBC";
|
|
1256
|
+
|
|
1257
|
+
interface AesEncryptOptions {
|
|
1258
|
+
readonly mode?: AesMode; // Default "GCM"
|
|
1259
|
+
readonly iv?: string | Uint8Array; // Default: random
|
|
1260
|
+
readonly aad?: string | Uint8Array; // GCM only
|
|
1261
|
+
readonly separateTag?: boolean; // GCM only, default false
|
|
1262
|
+
readonly encoding?: BinaryEncoding; // Default "base64"
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
interface AesEncryptResult {
|
|
1266
|
+
readonly ciphertext: string;
|
|
1267
|
+
readonly iv: string;
|
|
1268
|
+
readonly tag?: string; // Only with separateTag
|
|
1269
|
+
}
|
|
1270
|
+
```
|
|
1271
|
+
|
|
1272
|
+
Encrypts `data` (a string is encoded as UTF-8) and returns the ciphertext and IV in
|
|
1273
|
+
`encoding`.
|
|
1274
|
+
|
|
1275
|
+
- `"GCM"` (default) is authenticated encryption: decryption detects any change to
|
|
1276
|
+
the ciphertext, IV, tag, or `aad`. `ciphertext` is the encrypted data followed by
|
|
1277
|
+
the 16-byte authentication tag, the form used by Java, .NET, and Web Crypto.
|
|
1278
|
+
With `separateTag: true` the tag is returned in `tag` instead, as systems built
|
|
1279
|
+
on Node.js or OpenSSL usually expect.
|
|
1280
|
+
- `"CBC"` uses PKCS #7 padding. It does not detect changes to the ciphertext; use
|
|
1281
|
+
it only when an external system requires it, and authenticate the ciphertext
|
|
1282
|
+
separately, for example with `hmacSha256`.
|
|
1283
|
+
- Without `iv`, a random IV is generated: 12 bytes for GCM and 16 bytes for CBC.
|
|
1284
|
+
A given `iv` must be 12 to 16 bytes for GCM and exactly 16 bytes for CBC; a
|
|
1285
|
+
string `iv` is decoded with `encoding`. **Never use the same IV twice with the
|
|
1286
|
+
same GCM key**: doing so breaks both confidentiality and authentication. Pass
|
|
1287
|
+
an IV only when an external system dictates it.
|
|
1288
|
+
- `aad` is additional data that is authenticated but not encrypted, such as a
|
|
1289
|
+
record ID; a string is encoded as UTF-8. The same `aad` must be given to
|
|
1290
|
+
decryption.
|
|
1291
|
+
|
|
1292
|
+
### `crypto.aesDecrypt(key, ciphertext, options): Promise<string | Uint8Array>`
|
|
1293
|
+
|
|
1294
|
+
```typescript
|
|
1295
|
+
interface AesDecryptOptions {
|
|
1296
|
+
readonly mode?: AesMode; // Default "GCM"
|
|
1297
|
+
readonly iv: string | Uint8Array;
|
|
1298
|
+
readonly tag?: string | Uint8Array; // GCM only, when not appended to the ciphertext
|
|
1299
|
+
readonly aad?: string | Uint8Array; // GCM only
|
|
1300
|
+
readonly encoding?: BinaryEncoding; // Of a string ciphertext, iv, and tag; default "base64"
|
|
1301
|
+
readonly output?: DecryptOutput; // Default "utf8"
|
|
1302
|
+
}
|
|
1303
|
+
```
|
|
1304
|
+
|
|
1305
|
+
Decrypts an AES ciphertext. `iv` is required. In GCM mode, the last 16 bytes of
|
|
1306
|
+
`ciphertext` are the tag unless `tag` is given. `output` selects the result:
|
|
1307
|
+
`"utf8"` (default) decodes the plaintext as UTF-8 text and throws
|
|
1308
|
+
`ValidationError` if it is not valid UTF-8, `"bytes"` returns a `Uint8Array`, and
|
|
1309
|
+
`"base64"`, `"base64url"`, or `"hex"` return the plaintext bytes in that encoding.
|
|
1310
|
+
|
|
1311
|
+
A wrong key, IV, tag, or `aad`, a modified ciphertext, or invalid CBC padding
|
|
1312
|
+
throws `CogoverApiError` with `code: "DECRYPTION_FAILED"`. The error is the same
|
|
1313
|
+
for every cause, so that the result reveals nothing about the key or plaintext.
|
|
1314
|
+
|
|
1315
|
+
```typescript
|
|
1316
|
+
import { crypto, CogoverApiError, defineScript } from "@cogover/sdk";
|
|
1317
|
+
|
|
1318
|
+
export default defineScript(async ({ request }) => {
|
|
1319
|
+
const { data, iv, tag } = request.body as { data: string; iv: string; tag: string };
|
|
1320
|
+
try {
|
|
1321
|
+
const json = await crypto.aesDecrypt({ secret: "partner_aes_key", encoding: "base64" }, data, { iv, tag });
|
|
1322
|
+
return { payment: JSON.parse(json) };
|
|
1323
|
+
} catch (error) {
|
|
1324
|
+
if (error instanceof CogoverApiError && error.code === "DECRYPTION_FAILED") {
|
|
1325
|
+
return { r: 1001, msg: "The payload could not be decrypted." };
|
|
1326
|
+
}
|
|
1327
|
+
throw error;
|
|
1328
|
+
}
|
|
1329
|
+
});
|
|
1330
|
+
```
|
|
1331
|
+
|
|
1332
|
+
### `crypto.rsaEncrypt(publicKey, data, options?)` and `crypto.rsaDecrypt(privateKey, ciphertext, options?)`
|
|
1333
|
+
|
|
1334
|
+
```typescript
|
|
1335
|
+
type RsaPadding = "OAEP-SHA256" | "OAEP-SHA1" | "PKCS1";
|
|
1336
|
+
|
|
1337
|
+
interface RsaEncryptOptions {
|
|
1338
|
+
readonly padding?: RsaPadding; // Default "OAEP-SHA256"
|
|
1339
|
+
readonly encoding?: BinaryEncoding; // Of the ciphertext; default "base64"
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
interface RsaDecryptOptions {
|
|
1343
|
+
readonly padding?: RsaPadding; // Default "OAEP-SHA256"
|
|
1344
|
+
readonly encoding?: BinaryEncoding; // Of a string ciphertext; default "base64"
|
|
1345
|
+
readonly output?: DecryptOutput; // Default "utf8"
|
|
1346
|
+
}
|
|
1347
|
+
```
|
|
1348
|
+
|
|
1349
|
+
`rsaEncrypt` encrypts `data` (a string is encoded as UTF-8) with an RSA public key
|
|
1350
|
+
and returns the ciphertext in `encoding`. `rsaDecrypt` decrypts it with the
|
|
1351
|
+
matching private key and returns the plaintext as `output`, like `aesDecrypt`.
|
|
1352
|
+
|
|
1353
|
+
- `"OAEP-SHA256"` (default) is RSA-OAEP with SHA-256, and its mask generation
|
|
1354
|
+
function MGF1 also uses SHA-256, as in Web Crypto, Node.js, and OpenSSL.
|
|
1355
|
+
`"OAEP-SHA1"` uses SHA-1 for both. Some Java code written as
|
|
1356
|
+
`OAEPWithSHA-256AndMGF1Padding` keeps MGF1 on SHA-1 and is compatible with
|
|
1357
|
+
neither; ask the other system which digest its MGF1 uses.
|
|
1358
|
+
- `"PKCS1"` is PKCS #1 v1.5 padding. Use it only when an external system requires
|
|
1359
|
+
it.
|
|
1360
|
+
- RSA encrypts only a small amount of data: at most the key size in bytes minus
|
|
1361
|
+
66 bytes for `"OAEP-SHA256"`, minus 42 for `"OAEP-SHA1"`, and minus 11 for
|
|
1362
|
+
`"PKCS1"` — 190, 214, and 245 bytes for a 2048-bit key. Larger data throws
|
|
1363
|
+
`ValidationError`. To send more, encrypt the data with `aesEncrypt` under a
|
|
1364
|
+
random key from `randomBytes(32)` and encrypt only that key with `rsaEncrypt`.
|
|
1365
|
+
- A decryption that fails for any reason throws `CogoverApiError` with
|
|
1366
|
+
`code: "DECRYPTION_FAILED"`.
|
|
1367
|
+
|
|
1368
|
+
```typescript
|
|
1369
|
+
const cardToken = await crypto.rsaEncrypt({ secret: "bank_public_key" }, "4111111111111111");
|
|
1370
|
+
const plain = await crypto.rsaDecrypt({ secret: "our_private_key" }, request.body.data as string);
|
|
1371
|
+
```
|
|
1372
|
+
|
|
1373
|
+
### `crypto.sign(algorithm, privateKey, data, options?)` and `crypto.verify(algorithm, publicKey, data, signature, options?)`
|
|
1374
|
+
|
|
1375
|
+
```typescript
|
|
1376
|
+
type SignatureAlgorithm =
|
|
1377
|
+
| "RSA-SHA1" | "RSA-SHA256" | "RSA-SHA384" | "RSA-SHA512"
|
|
1378
|
+
| "RSA-PSS-SHA256" | "RSA-PSS-SHA384" | "RSA-PSS-SHA512"
|
|
1379
|
+
| "ECDSA-SHA256" | "ECDSA-SHA384" | "ECDSA-SHA512";
|
|
1380
|
+
|
|
1381
|
+
interface SignatureOptions {
|
|
1382
|
+
readonly encoding?: BinaryEncoding; // Of the signature; default "base64"
|
|
1383
|
+
readonly signatureFormat?: "der" | "ieee-p1363"; // ECDSA only; default "der"
|
|
1384
|
+
}
|
|
1385
|
+
```
|
|
1386
|
+
|
|
1387
|
+
`sign` signs `data` (a string is encoded as UTF-8) with a private key and returns
|
|
1388
|
+
the signature in `encoding`. `verify` returns `true` when `signature` is a valid
|
|
1389
|
+
signature of `data` for the public key, and `false` otherwise, including when the
|
|
1390
|
+
signature cannot be decoded or has the wrong length; a signature normally comes
|
|
1391
|
+
from the party being verified, so a malformed one is not an error. An invalid
|
|
1392
|
+
key or algorithm still throws `ValidationError`.
|
|
1393
|
+
|
|
1394
|
+
- `RSA-SHA*` is RSASSA-PKCS1-v1_5 and requires an RSA key. `RSA-SHA1` exists only
|
|
1395
|
+
to verify signatures of systems that still use it; do not use it for new
|
|
1396
|
+
signatures.
|
|
1397
|
+
- `RSA-PSS-SHA*` is RSASSA-PSS with MGF1 on the same digest and a salt as long as
|
|
1398
|
+
the digest (32, 48, or 64 bytes), and requires an RSA key.
|
|
1399
|
+
- `ECDSA-SHA*` requires an EC key. `signatureFormat` is `"der"` (ASN.1, used by
|
|
1400
|
+
OpenSSL and Java) or `"ieee-p1363"` (the fixed-length `r || s` form used by JWT
|
|
1401
|
+
and Web Crypto); it is rejected for RSA algorithms.
|
|
1402
|
+
|
|
1403
|
+
| JWT `alg` | `algorithm` | Options |
|
|
1404
|
+
|---|---|---|
|
|
1405
|
+
| `RS256`, `RS384`, `RS512` | `RSA-SHA256`, `RSA-SHA384`, `RSA-SHA512` | `{ encoding: "base64url" }` |
|
|
1406
|
+
| `PS256`, `PS384`, `PS512` | `RSA-PSS-SHA256`, `RSA-PSS-SHA384`, `RSA-PSS-SHA512` | `{ encoding: "base64url" }` |
|
|
1407
|
+
| `ES256`, `ES384`, `ES512` | `ECDSA-SHA256`, `ECDSA-SHA384`, `ECDSA-SHA512` | `{ encoding: "base64url", signatureFormat: "ieee-p1363" }` |
|
|
1408
|
+
|
|
1409
|
+
```typescript
|
|
1410
|
+
// Verify an ES256 JWT issued by a partner. Also check its claims (exp, iss, aud) before trusting it.
|
|
1411
|
+
const [header, payload, signature] = token.split(".");
|
|
1412
|
+
const valid = await crypto.verify("ECDSA-SHA256", { secret: "partner_jwt_public_key" },
|
|
1413
|
+
`${header}.${payload}`, signature ?? "", { encoding: "base64url", signatureFormat: "ieee-p1363" });
|
|
1414
|
+
if (!valid) return response.empty({ status: 401 });
|
|
1415
|
+
|
|
1416
|
+
// Sign a request to a bank that expects SHA256withRSA in base64.
|
|
1417
|
+
const body = JSON.stringify(order);
|
|
1418
|
+
const bankSignature = await crypto.sign("RSA-SHA256", { secret: "bank_signing_key" }, body);
|
|
1419
|
+
```
|
|
1420
|
+
|
|
1421
|
+
### Limits and availability
|
|
1422
|
+
|
|
1423
|
+
`data`, `aad`, and an explicit HMAC key are limited to 256 KiB, and a ciphertext
|
|
1424
|
+
to 256 KiB plus its tag; larger values and invalid arguments throw
|
|
1425
|
+
`ValidationError` before the call. The key, algorithm, and option errors that
|
|
1426
|
+
Cogover detects, such as a key of the wrong size or type, also throw
|
|
1427
|
+
`ValidationError`. Every operation except `timingSafeEqual` is a capability call
|
|
1428
|
+
and counts towards the invocation's limits.
|
|
1429
|
+
|
|
1430
|
+
The operations work in every context, including before-change triggers, with a key
|
|
1431
|
+
given in the call. A `{ secret }` key follows the rules of `secrets.get`: a
|
|
1432
|
+
before-change trigger is refused with `PermissionDeniedError`
|
|
1433
|
+
(`details.reason === "TRIGGER_READ_ONLY"`) and a local development session without
|
|
1434
|
+
secret access with `details.reason === "SECRETS_NOT_ALLOWED"`.
|
|
1182
1435
|
|
|
1183
1436
|
## Inbound webhooks
|
|
1184
1437
|
|
|
@@ -1927,7 +2180,9 @@ that throws it rejects the write like any other failure.
|
|
|
1927
2180
|
`jobs.enqueue`, `secrets.get`, and `crypto` fail with `ValidationError`,
|
|
1928
2181
|
`PermissionDeniedError`, or `RateLimitError` as described in their sections, and
|
|
1929
2182
|
with `CogoverApiError` whose `code` is `JOBS_DISABLED` or `SECRETS_DISABLED` when
|
|
1930
|
-
the feature is not enabled for the Workspace.
|
|
2183
|
+
the feature is not enabled for the Workspace. `crypto.aesDecrypt` and
|
|
2184
|
+
`crypto.rsaDecrypt` throw `CogoverApiError` with `code: "DECRYPTION_FAILED"` when
|
|
2185
|
+
the ciphertext cannot be decrypted.
|
|
1931
2186
|
|
|
1932
2187
|
Scripts can catch `CogoverApiError`, inspect `error.r`, and return their own client
|
|
1933
2188
|
error, such as `{ r: 1001, msg: "You cannot update this order." }`, without exposing
|
package/docs/en/usage-guide.md
CHANGED
|
@@ -206,6 +206,58 @@ to state, or to a response, and prefer a credential over `secrets.get` whenever
|
|
|
206
206
|
value is only needed for an HTTP header. Secrets and credentials are not available
|
|
207
207
|
in before-change triggers.
|
|
208
208
|
|
|
209
|
+
## Encrypt, decrypt, and sign data
|
|
210
|
+
|
|
211
|
+
`crypto` also encrypts and signs with keys that stay in project secrets. Pass
|
|
212
|
+
`{ secret: name }` as the key: Cogover resolves it and the value never enters the
|
|
213
|
+
code.
|
|
214
|
+
|
|
215
|
+
```typescript
|
|
216
|
+
import { createRouter, crypto, fetch } from "@cogover/sdk";
|
|
217
|
+
|
|
218
|
+
const router = createRouter();
|
|
219
|
+
router.post("/payments", async ({ request, response }) => {
|
|
220
|
+
// AES-256-GCM with a random IV; the partner receives the ciphertext and the IV.
|
|
221
|
+
const aesKey = { secret: "partner_aes_key", encoding: "base64" } as const;
|
|
222
|
+
const sealed = await crypto.aesEncrypt(aesKey, JSON.stringify(request.body));
|
|
223
|
+
|
|
224
|
+
// RSA: encrypt a small value with the partner's public key, sign with our private key.
|
|
225
|
+
const cardToken = await crypto.rsaEncrypt({ secret: "partner_public_key" }, "4111111111111111");
|
|
226
|
+
const body = JSON.stringify({ ...sealed, cardToken });
|
|
227
|
+
const signature = await crypto.sign("RSA-SHA256", { secret: "our_signing_key" }, body);
|
|
228
|
+
const reply = await fetch("https://partner.example.com/payments", {
|
|
229
|
+
method: "POST",
|
|
230
|
+
headers: { "content-type": "application/json", "x-signature": signature },
|
|
231
|
+
body,
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
// Verify the partner's ECDSA signature before trusting the reply.
|
|
235
|
+
const replyBody = await reply.text();
|
|
236
|
+
const valid = await crypto.verify("ECDSA-SHA256", { secret: "partner_public_key_ec" }, replyBody,
|
|
237
|
+
reply.headers.get("x-signature") ?? "");
|
|
238
|
+
return valid ? response.json(JSON.parse(replyBody)) : response.empty({ status: 502 });
|
|
239
|
+
});
|
|
240
|
+
export default router.toHandler();
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
- `aesEncrypt`/`aesDecrypt` use AES-GCM by default; `mode: "CBC"` exists for
|
|
244
|
+
systems that require it. Leave out `iv` so that a new random IV is used every
|
|
245
|
+
time.
|
|
246
|
+
- `rsaEncrypt`/`rsaDecrypt` use RSA-OAEP with SHA-256 by default and encrypt at
|
|
247
|
+
most a few hundred bytes; encrypt larger data with AES and only the AES key
|
|
248
|
+
with RSA.
|
|
249
|
+
- `sign`/`verify` support RSA (PKCS #1 v1.5 and PSS) and ECDSA, including the
|
|
250
|
+
`base64url` and `ieee-p1363` forms used by JWT. `verify` returns `false` for a
|
|
251
|
+
malformed signature instead of throwing.
|
|
252
|
+
- A failed decryption throws `CogoverApiError` with `code: "DECRYPTION_FAILED"`.
|
|
253
|
+
- Keys are PEM text in a secret: store private keys unencrypted in PKCS #8, PKCS #1,
|
|
254
|
+
or SEC1 form; public keys may be a certificate. RSA keys must be 2048 to 4096 bits
|
|
255
|
+
and EC keys P-256, P-384, or P-521.
|
|
256
|
+
|
|
257
|
+
With a key from a secret, these operations follow the rules of secrets and are
|
|
258
|
+
not available in before-change triggers. The API reference describes every option
|
|
259
|
+
and the JWT algorithm names.
|
|
260
|
+
|
|
209
261
|
## Permissions and limits
|
|
210
262
|
|
|
211
263
|
- Cogover authentication credentials are never exposed to module code. Access is
|