@cogover/sdk 0.7.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 +110 -4
- package/dist/crypto.d.ts +133 -0
- package/dist/crypto.js +418 -0
- package/dist/errors.d.ts +2 -2
- package/dist/errors.js +2 -2
- package/dist/fetch.d.ts +2 -0
- package/dist/fetch.js +6 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.js +2 -0
- package/dist/internal/base64.js +41 -0
- package/dist/internal/invocation.js +15 -0
- package/dist/internal/job-config.js +143 -0
- package/dist/internal/job-runtime.js +90 -0
- package/dist/internal/jobs-api.js +58 -0
- package/dist/internal/request.js +14 -2
- package/dist/internal/trigger-runtime.js +7 -0
- package/dist/internal/utf8.js +55 -0
- package/dist/internal/validation.js +8 -0
- package/dist/invocation.d.ts +14 -1
- package/dist/jobs.d.ts +95 -0
- package/dist/jobs.js +15 -0
- package/dist/request.d.ts +4 -0
- package/dist/response.js +1 -15
- package/dist/router.js +3 -0
- package/dist/script.d.ts +6 -0
- package/dist/script.js +6 -0
- package/dist/secrets.d.ts +8 -0
- package/dist/secrets.js +17 -0
- package/dist/state.js +2 -19
- package/dist/trigger.d.ts +8 -0
- package/docs/en/api-reference.md +775 -27
- package/docs/en/usage-guide.md +253 -4
- package/package.json +1 -1
package/dist/crypto.js
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
import { CogoverApiError, ValidationError } from "./errors.js";
|
|
2
|
+
import { decodeBase64, encodeBase64 } from "./internal/base64.js";
|
|
3
|
+
import { callBridge } from "./internal/bridge.js";
|
|
4
|
+
import { encodeUtf8, utf8ByteLength } from "./internal/utf8.js";
|
|
5
|
+
import { requireSecretName } from "./internal/validation.js";
|
|
6
|
+
import { isRecord } from "./internal/values.js";
|
|
7
|
+
const MAX_DATA_BYTES = 256 * 1024;
|
|
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;
|
|
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
|
+
}
|
|
162
|
+
/** Cryptographic helpers backed by Cogover's managed implementation. */
|
|
163
|
+
export const crypto = Object.freeze({
|
|
164
|
+
async sha256(data, encoding = "hex") {
|
|
165
|
+
const { data: text, dataEncoding } = bridgeData(data, "sha256() data");
|
|
166
|
+
return digest(await callBridge("crypto.hash", {
|
|
167
|
+
algorithm: "SHA-256",
|
|
168
|
+
data: text,
|
|
169
|
+
dataEncoding,
|
|
170
|
+
encoding: digestEncoding(encoding, "sha256()"),
|
|
171
|
+
}));
|
|
172
|
+
},
|
|
173
|
+
async hmacSha256(key, data, encoding = "hex") {
|
|
174
|
+
const keyPayload = hmacKey(key);
|
|
175
|
+
const { data: text, dataEncoding } = bridgeData(data, "hmacSha256() data");
|
|
176
|
+
return digest(await callBridge("crypto.hmac", {
|
|
177
|
+
algorithm: "SHA-256",
|
|
178
|
+
key: keyPayload,
|
|
179
|
+
data: text,
|
|
180
|
+
dataEncoding,
|
|
181
|
+
encoding: digestEncoding(encoding, "hmacSha256()"),
|
|
182
|
+
}));
|
|
183
|
+
},
|
|
184
|
+
async randomBytes(length) {
|
|
185
|
+
if (!Number.isInteger(length) || length < 1 || length > MAX_RANDOM_BYTES) {
|
|
186
|
+
throw new ValidationError(`randomBytes() length must be an integer between 1 and ${MAX_RANDOM_BYTES}`);
|
|
187
|
+
}
|
|
188
|
+
const random = await callBridge("crypto.random", { bytes: length });
|
|
189
|
+
const bytes = isRecord(random) && typeof random.base64 === "string" ? decodeBase64(random.base64) : null;
|
|
190
|
+
if (bytes === null || bytes.length !== length) {
|
|
191
|
+
throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Random bytes are invalid");
|
|
192
|
+
}
|
|
193
|
+
return bytes;
|
|
194
|
+
},
|
|
195
|
+
async randomUUID() {
|
|
196
|
+
const bytes = await crypto.randomBytes(16);
|
|
197
|
+
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40; // version 4
|
|
198
|
+
bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80; // RFC 4122 variant
|
|
199
|
+
const hex = toHex(bytes);
|
|
200
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
201
|
+
},
|
|
202
|
+
timingSafeEqual(a, b) {
|
|
203
|
+
const left = toBytes(a, "timingSafeEqual() first value");
|
|
204
|
+
const right = toBytes(b, "timingSafeEqual() second value");
|
|
205
|
+
// Every byte of the longer value is visited, so the time depends only on the lengths, never on
|
|
206
|
+
// where the first difference is.
|
|
207
|
+
let mismatch = left.length ^ right.length;
|
|
208
|
+
const length = Math.max(left.length, right.length);
|
|
209
|
+
for (let index = 0; index < length; index++) {
|
|
210
|
+
mismatch |= (left[index] ?? 0) ^ (right[index] ?? 0);
|
|
211
|
+
}
|
|
212
|
+
return mismatch === 0;
|
|
213
|
+
},
|
|
214
|
+
aesEncrypt,
|
|
215
|
+
aesDecrypt: aesDecrypt,
|
|
216
|
+
rsaEncrypt,
|
|
217
|
+
rsaDecrypt: rsaDecrypt,
|
|
218
|
+
sign,
|
|
219
|
+
verify,
|
|
220
|
+
});
|
|
221
|
+
function bridgeData(data, label) {
|
|
222
|
+
if (typeof data === "string") {
|
|
223
|
+
if (utf8ByteLength(data) > MAX_DATA_BYTES)
|
|
224
|
+
throw tooLarge(label);
|
|
225
|
+
return { data, dataEncoding: "utf8" };
|
|
226
|
+
}
|
|
227
|
+
if (data instanceof Uint8Array) {
|
|
228
|
+
if (data.length > MAX_DATA_BYTES)
|
|
229
|
+
throw tooLarge(label);
|
|
230
|
+
return { data: encodeBase64(data), dataEncoding: "base64" };
|
|
231
|
+
}
|
|
232
|
+
throw new ValidationError(`${label} must be a string or a Uint8Array`);
|
|
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
|
+
}
|
|
371
|
+
function hmacKey(key) {
|
|
372
|
+
if (typeof key === "string") {
|
|
373
|
+
if (key.length === 0)
|
|
374
|
+
throw new ValidationError("hmacSha256() key must not be empty");
|
|
375
|
+
if (utf8ByteLength(key) > MAX_DATA_BYTES)
|
|
376
|
+
throw tooLarge("hmacSha256() key");
|
|
377
|
+
return { value: key, encoding: "utf8" };
|
|
378
|
+
}
|
|
379
|
+
if (key instanceof Uint8Array) {
|
|
380
|
+
if (key.length === 0)
|
|
381
|
+
throw new ValidationError("hmacSha256() key must not be empty");
|
|
382
|
+
if (key.length > MAX_DATA_BYTES)
|
|
383
|
+
throw tooLarge("hmacSha256() key");
|
|
384
|
+
return { value: encodeBase64(key), encoding: "base64" };
|
|
385
|
+
}
|
|
386
|
+
if (isRecord(key) && Object.keys(key).length === 1 && "secret" in key) {
|
|
387
|
+
return { secret: requireSecretName(key.secret, "hmacSha256() key.secret") };
|
|
388
|
+
}
|
|
389
|
+
throw new ValidationError("hmacSha256() key must be a string, a Uint8Array or { secret: name }");
|
|
390
|
+
}
|
|
391
|
+
function digestEncoding(encoding, label) {
|
|
392
|
+
if (typeof encoding !== "string" || !ENCODINGS.has(encoding)) {
|
|
393
|
+
throw new ValidationError(`${label} encoding must be "hex" or "base64"`);
|
|
394
|
+
}
|
|
395
|
+
return encoding;
|
|
396
|
+
}
|
|
397
|
+
function digest(payload) {
|
|
398
|
+
if (!isRecord(payload) || typeof payload.digest !== "string" || payload.digest.length === 0) {
|
|
399
|
+
throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Digest is invalid");
|
|
400
|
+
}
|
|
401
|
+
return payload.digest;
|
|
402
|
+
}
|
|
403
|
+
function toBytes(value, label) {
|
|
404
|
+
if (typeof value === "string")
|
|
405
|
+
return encodeUtf8(value);
|
|
406
|
+
if (value instanceof Uint8Array)
|
|
407
|
+
return value;
|
|
408
|
+
throw new ValidationError(`${label} must be a string or a Uint8Array`);
|
|
409
|
+
}
|
|
410
|
+
function toHex(bytes) {
|
|
411
|
+
let hex = "";
|
|
412
|
+
for (const byte of bytes)
|
|
413
|
+
hex += (byte < 16 ? "0" : "") + byte.toString(16);
|
|
414
|
+
return hex;
|
|
415
|
+
}
|
|
416
|
+
function tooLarge(label) {
|
|
417
|
+
return new ValidationError(`${label} must not exceed ${MAX_DATA_BYTES} bytes`);
|
|
418
|
+
}
|
package/dist/errors.d.ts
CHANGED
|
@@ -20,8 +20,8 @@ export declare class RateLimitError extends CogoverApiError {
|
|
|
20
20
|
constructor(message: string, details?: unknown);
|
|
21
21
|
}
|
|
22
22
|
/**
|
|
23
|
-
* Thrown by an after-change trigger handler to report a temporary failure. Cogover runs
|
|
24
|
-
* later. Anywhere else it is an ordinary failure.
|
|
23
|
+
* Thrown by an after-change trigger handler or a job handler to report a temporary failure. Cogover runs
|
|
24
|
+
* the handler again later. Anywhere else it is an ordinary failure.
|
|
25
25
|
*/
|
|
26
26
|
export declare class RetryableError extends CogoverApiError {
|
|
27
27
|
constructor(message: string, details?: unknown);
|
package/dist/errors.js
CHANGED
|
@@ -43,8 +43,8 @@ export class RateLimitError extends CogoverApiError {
|
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
45
|
/**
|
|
46
|
-
* Thrown by an after-change trigger handler to report a temporary failure. Cogover runs
|
|
47
|
-
* later. Anywhere else it is an ordinary failure.
|
|
46
|
+
* Thrown by an after-change trigger handler or a job handler to report a temporary failure. Cogover runs
|
|
47
|
+
* the handler again later. Anywhere else it is an ordinary failure.
|
|
48
48
|
*/
|
|
49
49
|
export class RetryableError extends CogoverApiError {
|
|
50
50
|
constructor(message, details) {
|
package/dist/fetch.d.ts
CHANGED
|
@@ -3,6 +3,8 @@ export interface CogoverFetchInit {
|
|
|
3
3
|
readonly headers?: Readonly<Record<string, string>>;
|
|
4
4
|
readonly body?: string;
|
|
5
5
|
readonly timeoutMs?: number;
|
|
6
|
+
/** Name of a project credential; Cogover adds its authentication header to the request. */
|
|
7
|
+
readonly credential?: string;
|
|
6
8
|
}
|
|
7
9
|
export interface CogoverFetchHeaders {
|
|
8
10
|
get(name: string): string | null;
|
package/dist/fetch.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { ValidationError } from "./errors.js";
|
|
2
2
|
import { callBridge } from "./internal/bridge.js";
|
|
3
|
+
import { requireSecretName } from "./internal/validation.js";
|
|
3
4
|
const METHODS = new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]);
|
|
4
|
-
const OPTION_KEYS = new Set(["method", "headers", "body", "timeoutMs"]);
|
|
5
|
+
const OPTION_KEYS = new Set(["method", "headers", "body", "timeoutMs", "credential"]);
|
|
5
6
|
/** Fetch-compatible API using Cogover's managed network layer. */
|
|
6
7
|
export async function fetch(input, init) {
|
|
7
8
|
if (typeof input !== "string" || input.length === 0) {
|
|
@@ -30,6 +31,8 @@ export async function fetch(input, init) {
|
|
|
30
31
|
&& (init.headers === null || typeof init.headers !== "object" || Array.isArray(init.headers))) {
|
|
31
32
|
throw new ValidationError("fetch() headers must be an object");
|
|
32
33
|
}
|
|
34
|
+
if (init?.credential !== undefined)
|
|
35
|
+
requireSecretName(init.credential, "fetch() credential");
|
|
33
36
|
const payload = { url: input, method };
|
|
34
37
|
if (init?.headers !== undefined)
|
|
35
38
|
payload.headers = init.headers;
|
|
@@ -37,6 +40,8 @@ export async function fetch(input, init) {
|
|
|
37
40
|
payload.body = init.body;
|
|
38
41
|
if (init?.timeoutMs !== undefined)
|
|
39
42
|
payload.timeoutMs = init.timeoutMs;
|
|
43
|
+
if (init?.credential !== undefined)
|
|
44
|
+
payload.credential = init.credential;
|
|
40
45
|
const response = await callBridge("http.fetch", payload);
|
|
41
46
|
return createFetchResponse(response);
|
|
42
47
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -10,7 +10,12 @@ export { defineScript } from "./script.js";
|
|
|
10
10
|
export type { ScriptContext, ScriptHandler, SandboxHandler } from "./script.js";
|
|
11
11
|
export { defineTrigger } from "./trigger.js";
|
|
12
12
|
export type { TriggerTiming, TriggerOperation, TriggerRunWhen, TriggerFilterCondition, TriggerFilterGroup, TriggerFilter, TriggerConfig, TriggerManifest, TriggerSandboxHandler, TriggerDefinition, TriggerInfo, TriggerNewValues, TriggerOldValues, TriggerRecord, TriggerContext, TriggerHandler, } from "./trigger.js";
|
|
13
|
-
export
|
|
13
|
+
export { defineJob } from "./jobs.js";
|
|
14
|
+
export type { JobSchedule, JobConfig, JobManifest, JobDefinition, JobInfo, EnqueueOptions, EnqueueResult, JobsApi, JobContext, JobHandler, } from "./jobs.js";
|
|
15
|
+
export type { SecretsApi } from "./secrets.js";
|
|
16
|
+
export { crypto } 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
|
+
export type { CurrentWorkspace, CurrentWorkspaceMembership, CurrentUser, UserInvocationContext, SystemInvocationContext, InboundInvocationContext, InvocationContext, } from "./invocation.js";
|
|
14
19
|
export { createRouter } from "./router.js";
|
|
15
20
|
export type { ScriptRouter } from "./router.js";
|
|
16
21
|
export type { RequestMethod, ScriptRequest, ScriptQuery, ScriptHeaders, ScriptPathParams, } from "./request.js";
|
package/dist/index.js
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
export { and, or } from "./query.js";
|
|
3
3
|
export { defineScript } from "./script.js";
|
|
4
4
|
export { defineTrigger } from "./trigger.js";
|
|
5
|
+
export { defineJob } from "./jobs.js";
|
|
6
|
+
export { crypto } from "./crypto.js";
|
|
5
7
|
export { createRouter } from "./router.js";
|
|
6
8
|
export { fetch } from "./fetch.js";
|
|
7
9
|
export { CogoverApiError, NotFoundError, ValidationError, PermissionDeniedError, RateLimitError, RetryableError, StateConflictError, LockUnavailableError, LockLostError, } from "./errors.js";
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
2
|
+
const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
|
3
|
+
// Sandboxed code has neither Buffer nor atob/btoa, so binary data crosses the bridge through these helpers.
|
|
4
|
+
/** Standard base64 with padding (RFC 4648 section 4). */
|
|
5
|
+
export function encodeBase64(bytes) {
|
|
6
|
+
let result = "";
|
|
7
|
+
for (let index = 0; index < bytes.length; index += 3) {
|
|
8
|
+
const first = bytes[index] ?? 0;
|
|
9
|
+
const second = bytes[index + 1] ?? 0;
|
|
10
|
+
const third = bytes[index + 2] ?? 0;
|
|
11
|
+
const value = (first << 16) | (second << 8) | third;
|
|
12
|
+
result += ALPHABET.charAt((value >>> 18) & 63)
|
|
13
|
+
+ ALPHABET.charAt((value >>> 12) & 63)
|
|
14
|
+
+ (index + 1 < bytes.length ? ALPHABET.charAt((value >>> 6) & 63) : "=")
|
|
15
|
+
+ (index + 2 < bytes.length ? ALPHABET.charAt(value & 63) : "=");
|
|
16
|
+
}
|
|
17
|
+
return result;
|
|
18
|
+
}
|
|
19
|
+
/** Decodes padded standard base64; returns null for text that is not canonical base64. */
|
|
20
|
+
export function decodeBase64(text) {
|
|
21
|
+
if (typeof text !== "string" || !BASE64.test(text))
|
|
22
|
+
return null;
|
|
23
|
+
const padding = text.endsWith("==") ? 2 : text.endsWith("=") ? 1 : 0;
|
|
24
|
+
const bytes = new Uint8Array((text.length / 4) * 3 - padding);
|
|
25
|
+
let position = 0;
|
|
26
|
+
for (let index = 0; index < text.length; index += 4) {
|
|
27
|
+
const value = (digit(text, index) << 18) | (digit(text, index + 1) << 12)
|
|
28
|
+
| (digit(text, index + 2) << 6) | digit(text, index + 3);
|
|
29
|
+
if (position < bytes.length)
|
|
30
|
+
bytes[position++] = (value >>> 16) & 255;
|
|
31
|
+
if (position < bytes.length)
|
|
32
|
+
bytes[position++] = (value >>> 8) & 255;
|
|
33
|
+
if (position < bytes.length)
|
|
34
|
+
bytes[position++] = value & 255;
|
|
35
|
+
}
|
|
36
|
+
return bytes;
|
|
37
|
+
}
|
|
38
|
+
function digit(text, index) {
|
|
39
|
+
const character = text.charAt(index);
|
|
40
|
+
return character === "=" ? 0 : ALPHABET.indexOf(character);
|
|
41
|
+
}
|
|
@@ -8,6 +8,9 @@ export function invocationContext(input) {
|
|
|
8
8
|
if (context.executionIdentity === "system") {
|
|
9
9
|
return Object.freeze({ identity: "system", workspace, user: null });
|
|
10
10
|
}
|
|
11
|
+
if (context.executionIdentity === "inbound") {
|
|
12
|
+
return Object.freeze({ identity: "inbound", workspace, user: null, inbound: inboundSnapshot(context.inbound) });
|
|
13
|
+
}
|
|
11
14
|
if (context.executionIdentity !== "user" || !isRecord(context.user)) {
|
|
12
15
|
throw new ValidationError("Invalid invocation identity metadata");
|
|
13
16
|
}
|
|
@@ -36,6 +39,18 @@ function userSnapshot(raw) {
|
|
|
36
39
|
membership,
|
|
37
40
|
});
|
|
38
41
|
}
|
|
42
|
+
function inboundSnapshot(raw) {
|
|
43
|
+
if (!isRecord(raw))
|
|
44
|
+
throw new ValidationError("Invalid invocation identity metadata");
|
|
45
|
+
const mode = raw.mode;
|
|
46
|
+
if (mode !== "KEY" && mode !== "HMAC")
|
|
47
|
+
throw new ValidationError("Invalid invocation inbound mode");
|
|
48
|
+
return Object.freeze({
|
|
49
|
+
id: requiredString(raw.id, "inbound id"),
|
|
50
|
+
name: requiredString(raw.name, "inbound name"),
|
|
51
|
+
mode,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
39
54
|
function requiredString(value, label) {
|
|
40
55
|
if (typeof value !== "string" || value === "") {
|
|
41
56
|
throw new ValidationError(`Invalid invocation ${label}`);
|