@capsara/sdk 1.0.5 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +110 -28
- package/dist/builder/capsa-builder.d.ts +29 -13
- package/dist/builder/capsa-builder.d.ts.map +1 -1
- package/dist/builder/capsa-builder.js +302 -84
- package/dist/builder/capsa-builder.js.map +1 -1
- package/dist/client/capsara-client.d.ts +30 -26
- package/dist/client/capsara-client.d.ts.map +1 -1
- package/dist/client/capsara-client.js +102 -60
- package/dist/client/capsara-client.js.map +1 -1
- package/dist/errors/account-error.d.ts +5 -70
- package/dist/errors/account-error.d.ts.map +1 -1
- package/dist/errors/account-error.js +8 -146
- package/dist/errors/account-error.js.map +1 -1
- package/dist/errors/audit-error.d.ts +4 -28
- package/dist/errors/audit-error.d.ts.map +1 -1
- package/dist/errors/audit-error.js +9 -82
- package/dist/errors/audit-error.js.map +1 -1
- package/dist/errors/auth-error.d.ts +4 -35
- package/dist/errors/auth-error.d.ts.map +1 -1
- package/dist/errors/auth-error.js +6 -77
- package/dist/errors/auth-error.js.map +1 -1
- package/dist/errors/capsa-error.d.ts +5 -59
- package/dist/errors/capsa-error.d.ts.map +1 -1
- package/dist/errors/capsa-error.js +9 -156
- package/dist/errors/capsa-error.js.map +1 -1
- package/dist/errors/capsara-error.d.ts +24 -24
- package/dist/errors/capsara-error.d.ts.map +1 -1
- package/dist/errors/capsara-error.js +141 -34
- package/dist/errors/capsara-error.js.map +1 -1
- package/dist/errors/index.d.ts +1 -1
- package/dist/errors/index.d.ts.map +1 -1
- package/dist/index.d.ts +8 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/internal/capsa-cache.d.ts +0 -3
- package/dist/internal/capsa-cache.d.ts.map +1 -1
- package/dist/internal/capsa-cache.js +7 -23
- package/dist/internal/capsa-cache.js.map +1 -1
- package/dist/internal/config/http-client.d.ts.map +1 -1
- package/dist/internal/config/http-client.js +48 -21
- package/dist/internal/config/http-client.js.map +1 -1
- package/dist/internal/config/retry-interceptor.d.ts +26 -3
- package/dist/internal/config/retry-interceptor.d.ts.map +1 -1
- package/dist/internal/config/retry-interceptor.js +111 -83
- package/dist/internal/config/retry-interceptor.js.map +1 -1
- package/dist/internal/config/token-refresh.d.ts +12 -0
- package/dist/internal/config/token-refresh.d.ts.map +1 -0
- package/dist/internal/config/token-refresh.js +43 -0
- package/dist/internal/config/token-refresh.js.map +1 -0
- package/dist/internal/crypto/compression.d.ts +12 -0
- package/dist/internal/crypto/compression.d.ts.map +1 -1
- package/dist/internal/crypto/compression.js +14 -1
- package/dist/internal/crypto/compression.js.map +1 -1
- package/dist/internal/crypto/key-generator.d.ts +39 -4
- package/dist/internal/crypto/key-generator.d.ts.map +1 -1
- package/dist/internal/crypto/key-generator.js +93 -24
- package/dist/internal/crypto/key-generator.js.map +1 -1
- package/dist/internal/crypto/primitives.d.ts +1 -2
- package/dist/internal/crypto/primitives.d.ts.map +1 -1
- package/dist/internal/crypto/primitives.js +15 -14
- package/dist/internal/crypto/primitives.js.map +1 -1
- package/dist/internal/crypto/signatures.d.ts +3 -1
- package/dist/internal/crypto/signatures.d.ts.map +1 -1
- package/dist/internal/crypto/signatures.js +14 -6
- package/dist/internal/crypto/signatures.js.map +1 -1
- package/dist/internal/decryptor/capsa-decryptor.d.ts +11 -54
- package/dist/internal/decryptor/capsa-decryptor.d.ts.map +1 -1
- package/dist/internal/decryptor/capsa-decryptor.js +167 -160
- package/dist/internal/decryptor/capsa-decryptor.js.map +1 -1
- package/dist/internal/http-factory.d.ts +3 -47
- package/dist/internal/http-factory.d.ts.map +1 -1
- package/dist/internal/http-factory.js +2 -157
- package/dist/internal/http-factory.js.map +1 -1
- package/dist/internal/logging.d.ts +13 -0
- package/dist/internal/logging.d.ts.map +1 -0
- package/dist/internal/logging.js +22 -0
- package/dist/internal/logging.js.map +1 -0
- package/dist/internal/services/account-service.d.ts +11 -33
- package/dist/internal/services/account-service.d.ts.map +1 -1
- package/dist/internal/services/account-service.js +38 -53
- package/dist/internal/services/account-service.js.map +1 -1
- package/dist/internal/services/audit-service.d.ts.map +1 -1
- package/dist/internal/services/audit-service.js +17 -1
- package/dist/internal/services/audit-service.js.map +1 -1
- package/dist/internal/services/auth-service.d.ts +17 -1
- package/dist/internal/services/auth-service.d.ts.map +1 -1
- package/dist/internal/services/auth-service.js +188 -51
- package/dist/internal/services/auth-service.js.map +1 -1
- package/dist/internal/services/capsa-service.d.ts +8 -26
- package/dist/internal/services/capsa-service.d.ts.map +1 -1
- package/dist/internal/services/capsa-service.js +91 -44
- package/dist/internal/services/capsa-service.js.map +1 -1
- package/dist/internal/services/download-service.d.ts +17 -25
- package/dist/internal/services/download-service.d.ts.map +1 -1
- package/dist/internal/services/download-service.js +30 -56
- package/dist/internal/services/download-service.js.map +1 -1
- package/dist/internal/services/key-service.d.ts +6 -14
- package/dist/internal/services/key-service.d.ts.map +1 -1
- package/dist/internal/services/key-service.js +63 -21
- package/dist/internal/services/key-service.js.map +1 -1
- package/dist/internal/services/limits-service.d.ts +14 -16
- package/dist/internal/services/limits-service.d.ts.map +1 -1
- package/dist/internal/services/limits-service.js +60 -28
- package/dist/internal/services/limits-service.js.map +1 -1
- package/dist/internal/services/upload-service.d.ts +33 -27
- package/dist/internal/services/upload-service.d.ts.map +1 -1
- package/dist/internal/services/upload-service.js +307 -133
- package/dist/internal/services/upload-service.js.map +1 -1
- package/dist/internal/types.d.ts +0 -7
- package/dist/internal/types.d.ts.map +1 -1
- package/dist/internal/upload/multipart-builder.d.ts +0 -15
- package/dist/internal/upload/multipart-builder.d.ts.map +1 -1
- package/dist/internal/upload/multipart-builder.js +0 -26
- package/dist/internal/upload/multipart-builder.js.map +1 -1
- package/dist/internal/utils/filename-check.d.ts +11 -0
- package/dist/internal/utils/filename-check.d.ts.map +1 -0
- package/dist/internal/utils/filename-check.js +28 -0
- package/dist/internal/utils/filename-check.js.map +1 -0
- package/dist/internal/utils/rfc3339.d.ts +15 -0
- package/dist/internal/utils/rfc3339.d.ts.map +1 -0
- package/dist/internal/utils/rfc3339.js +53 -0
- package/dist/internal/utils/rfc3339.js.map +1 -0
- package/dist/internal/utils/safe-filename.d.ts +31 -0
- package/dist/internal/utils/safe-filename.d.ts.map +1 -0
- package/dist/internal/utils/safe-filename.js +126 -0
- package/dist/internal/utils/safe-filename.js.map +1 -0
- package/dist/internal/version.d.ts +18 -14
- package/dist/internal/version.d.ts.map +1 -1
- package/dist/internal/version.js +47 -14
- package/dist/internal/version.js.map +1 -1
- package/dist/types/index.d.ts +26 -10
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/package.json +13 -11
- package/dist/internal/index.d.ts +0 -5
- package/dist/internal/index.d.ts.map +0 -1
- package/dist/internal/index.js +0 -5
- package/dist/internal/index.js.map +0 -1
- package/dist/internal/retry-executor.d.ts +0 -74
- package/dist/internal/retry-executor.d.ts.map +0 -1
- package/dist/internal/retry-executor.js +0 -204
- package/dist/internal/retry-executor.js.map +0 -1
|
@@ -1,14 +1,21 @@
|
|
|
1
1
|
/** Fluent capsa builder for creating encrypted capsas. */
|
|
2
|
+
import * as crypto from 'crypto';
|
|
2
3
|
import * as fs from 'fs';
|
|
3
4
|
import * as path from 'path';
|
|
4
5
|
import { generateId } from '../internal/utils/id-generator.js';
|
|
5
6
|
import { lookupMimeType } from '../internal/utils/mimetype-lookup.js';
|
|
7
|
+
import { filenameSendProblem } from '../internal/utils/filename-check.js';
|
|
8
|
+
import { RFC3339_RULE, parseRfc3339Ms } from '../internal/utils/rfc3339.js';
|
|
9
|
+
import { CapsaraError } from '../errors/capsara-error.js';
|
|
6
10
|
import { generateMasterKey, generateIV, encryptAES, encryptAESRaw, encryptMasterKeyForParty, computeHash, } from '../internal/crypto/primitives.js';
|
|
7
11
|
import { buildCanonicalString, createCapsaSignature, } from '../internal/crypto/signatures.js';
|
|
8
|
-
import {
|
|
12
|
+
import { calculateKeyFingerprint, calculatePrivateKeyFingerprint, FINGERPRINT_MISMATCH_MESSAGE, INVALID_PUBLIC_KEY_MESSAGE, InvalidPublicKeyError, publicKeyBits, REQUIRED_KEY_BITS, unsupportedKeySizeMessage, } from '../internal/crypto/key-generator.js';
|
|
13
|
+
import { compressIfBeneficial } from '../internal/crypto/compression.js';
|
|
14
|
+
/** Refusal for structured data that is not a JSON object; the same text in every sender SDK. */
|
|
15
|
+
export const STRUCTURED_NOT_OBJECT_MESSAGE = 'Structured data must be a JSON object (not an array, string, number or null).';
|
|
9
16
|
/** Server-aligned validation constants. */
|
|
10
17
|
export const SERVER_LIMITS = {
|
|
11
|
-
/** Maximum keychain entries (
|
|
18
|
+
/** Maximum keychain entries (creator + recipient + delegates) */
|
|
12
19
|
MAX_KEYCHAIN_KEYS: 100,
|
|
13
20
|
/** Maximum base64url-encoded encrypted subject length */
|
|
14
21
|
MAX_ENCRYPTED_SUBJECT: 65_536,
|
|
@@ -28,13 +35,89 @@ export const SERVER_LIMITS = {
|
|
|
28
35
|
MAX_RELATED_PACKAGES: 50,
|
|
29
36
|
/** Maximum party ID length */
|
|
30
37
|
MAX_PARTY_ID_LENGTH: 100,
|
|
38
|
+
/** Maximum characters per related package reference */
|
|
39
|
+
MAX_RELATED_PACKAGE_LENGTH: 100,
|
|
40
|
+
/** Maximum MIME type length */
|
|
41
|
+
MAX_MIMETYPE_LENGTH: 255,
|
|
42
|
+
/** Maximum transform reference length */
|
|
43
|
+
MAX_TRANSFORM_LENGTH: 2_048,
|
|
31
44
|
/** Maximum base64url-encoded encrypted filename length */
|
|
32
45
|
MAX_ENCRYPTED_FILENAME: 2_048,
|
|
33
|
-
/** Maximum base64url-encoded signature payload length */
|
|
34
|
-
MAX_SIGNATURE_PAYLOAD:
|
|
35
|
-
/** Maximum
|
|
36
|
-
|
|
46
|
+
/** Maximum base64url-encoded signature payload length (128 KiB; a 500-file capsa signs about 66,200 chars) */
|
|
47
|
+
MAX_SIGNATURE_PAYLOAD: 131_072,
|
|
48
|
+
/** Maximum UTF-8 bytes of one JSON part in the upload request (the serialized capsa) */
|
|
49
|
+
MAX_JSON_FIELD: 1_048_576,
|
|
37
50
|
};
|
|
51
|
+
/** Error message when a capsa is built without a recipient. */
|
|
52
|
+
const NO_RECIPIENT_MESSAGE = 'Capsa has no recipient. Call addRecipient() with the party this capsa is sent to.';
|
|
53
|
+
function validationError(message) {
|
|
54
|
+
return new CapsaraError(message, 'VALIDATION_ERROR', 0);
|
|
55
|
+
}
|
|
56
|
+
/** The server's rule for a file transform: an http(s) URL or a prefixed reference `@partyId/id`. */
|
|
57
|
+
const TRANSFORM_REFERENCE = /^@[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+$/;
|
|
58
|
+
function isTransformUrl(value) {
|
|
59
|
+
try {
|
|
60
|
+
const protocol = new URL(value).protocol;
|
|
61
|
+
return protocol === 'https:' || protocol === 'http:';
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
function fileExpirationFormatProblem(filename, expiresAt) {
|
|
68
|
+
const text = expiresAt instanceof Date ? expiresAt.toString() : expiresAt;
|
|
69
|
+
return `Expiration for "${filename}" is not a valid date: ${text}. ${RFC3339_RULE}`;
|
|
70
|
+
}
|
|
71
|
+
/** Why a file input's optional fields would be refused by the server, or undefined. */
|
|
72
|
+
function fileFieldProblem(input) {
|
|
73
|
+
if (input.mimetype !== undefined && input.mimetype.length > SERVER_LIMITS.MAX_MIMETYPE_LENGTH) {
|
|
74
|
+
return `MIME type (${input.mimetype.length} chars) exceeds server limit of ${SERVER_LIMITS.MAX_MIMETYPE_LENGTH} chars.`;
|
|
75
|
+
}
|
|
76
|
+
if (input.transform) {
|
|
77
|
+
if (input.transform.length > SERVER_LIMITS.MAX_TRANSFORM_LENGTH) {
|
|
78
|
+
return `Transform (${input.transform.length} chars) exceeds server limit of ${SERVER_LIMITS.MAX_TRANSFORM_LENGTH} chars.`;
|
|
79
|
+
}
|
|
80
|
+
if (!TRANSFORM_REFERENCE.test(input.transform) && !isTransformUrl(input.transform)) {
|
|
81
|
+
return 'Transform must be a valid URL (http/https) or a prefixed reference (@partyId/id).';
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
87
|
+
const FALLBACK_MAX_EXPIRATION_DAYS = 3650;
|
|
88
|
+
/** The creator key's RSA modulus size, or undefined when the PEM is not a loadable RSA private key (the signer reports that). */
|
|
89
|
+
function creatorKeyBits(privateKeyPEM) {
|
|
90
|
+
try {
|
|
91
|
+
const keyObject = crypto.createPrivateKey({ key: privateKeyPEM, format: 'pem' });
|
|
92
|
+
return keyObject.asymmetricKeyType === 'rsa' ? keyObject.asymmetricKeyDetails?.modulusLength : undefined;
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function maxExpirationDays(limits) {
|
|
99
|
+
const value = limits.maxExpirationDays;
|
|
100
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : FALLBACK_MAX_EXPIRATION_DAYS;
|
|
101
|
+
}
|
|
102
|
+
function buildFailed(reason, message) {
|
|
103
|
+
return new CapsaraError(message, 'BUILD_FAILED', 0, { reason });
|
|
104
|
+
}
|
|
105
|
+
function readFileAt(filePath) {
|
|
106
|
+
try {
|
|
107
|
+
return fs.readFileSync(filePath);
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
throw buildFailed('FILE_READ_FAILED', `Cannot read file "${filePath}": ${error instanceof Error ? error.message : String(error)}`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function fileSizeAt(filePath) {
|
|
114
|
+
try {
|
|
115
|
+
return fs.statSync(filePath).size;
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
throw validationError(`Cannot read file "${filePath}": ${error instanceof Error ? error.message : String(error)}`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
38
121
|
export class CapsaBuilder {
|
|
39
122
|
subject;
|
|
40
123
|
body;
|
|
@@ -50,7 +133,13 @@ export class CapsaBuilder {
|
|
|
50
133
|
this.#expiresAt = undefined;
|
|
51
134
|
return;
|
|
52
135
|
}
|
|
53
|
-
|
|
136
|
+
// A string must be an RFC 3339 date-time with an explicit UTC offset, the one form the
|
|
137
|
+
// server accepts; `new Date(text)` would also take date-only and local-time forms.
|
|
138
|
+
const ms = typeof value === 'string' ? parseRfc3339Ms(value) : value.getTime();
|
|
139
|
+
if (ms === undefined || Number.isNaN(ms)) {
|
|
140
|
+
throw validationError(`Invalid expiration date: ${String(value)}. ${RFC3339_RULE}`);
|
|
141
|
+
}
|
|
142
|
+
const dateObj = new Date(ms);
|
|
54
143
|
dateObj.setSeconds(0, 0);
|
|
55
144
|
this.#expiresAt = dateObj.toISOString();
|
|
56
145
|
}
|
|
@@ -62,76 +151,135 @@ export class CapsaBuilder {
|
|
|
62
151
|
#limits;
|
|
63
152
|
#expiresAt;
|
|
64
153
|
constructor(creatorId, creatorPrivateKey, limits) {
|
|
154
|
+
if (creatorId.length > SERVER_LIMITS.MAX_PARTY_ID_LENGTH) {
|
|
155
|
+
throw validationError(`Party ID (${creatorId.length} chars) exceeds server limit of ${SERVER_LIMITS.MAX_PARTY_ID_LENGTH} chars.`);
|
|
156
|
+
}
|
|
65
157
|
this.#masterKey = generateMasterKey();
|
|
66
158
|
this.#creatorId = creatorId;
|
|
67
159
|
this.#creatorPrivateKey = creatorPrivateKey;
|
|
68
160
|
this.#limits = limits;
|
|
69
161
|
}
|
|
70
162
|
/**
|
|
71
|
-
*
|
|
163
|
+
* Set the capsa's recipient (its principal).
|
|
164
|
+
*
|
|
165
|
+
* A capsa goes to exactly one recipient. The recipient's registered delegates
|
|
166
|
+
* are added automatically at send time, each acting for this recipient, so
|
|
167
|
+
* several parties can still access the capsa through their own keys. To send
|
|
168
|
+
* to several recipients, use one builder per recipient and send them together
|
|
169
|
+
* in one batch with sendCapsas().
|
|
170
|
+
*
|
|
171
|
+
* The recipient may be the creator itself (a self-send); the creator's own
|
|
172
|
+
* delegates are then added, acting for the creator.
|
|
72
173
|
* @param partyId - Party ID
|
|
174
|
+
* @throws Error if a recipient has already been added
|
|
73
175
|
*/
|
|
74
176
|
addRecipient(partyId) {
|
|
75
177
|
if (!partyId || partyId.length === 0) {
|
|
76
|
-
throw
|
|
178
|
+
throw validationError('Party ID cannot be empty.');
|
|
77
179
|
}
|
|
78
180
|
if (partyId.length > SERVER_LIMITS.MAX_PARTY_ID_LENGTH) {
|
|
79
|
-
throw
|
|
181
|
+
throw validationError(`Party ID (${partyId.length} chars) exceeds server limit of ${SERVER_LIMITS.MAX_PARTY_ID_LENGTH} chars.`);
|
|
80
182
|
}
|
|
81
|
-
|
|
82
|
-
if (
|
|
83
|
-
throw
|
|
183
|
+
const existing = this.#recipients[0];
|
|
184
|
+
if (existing) {
|
|
185
|
+
throw validationError(`Capsa already has a recipient ("${existing.partyId}"). A capsa goes to exactly one recipient; ` +
|
|
186
|
+
`that recipient's delegates are added automatically. To send to several recipients, ` +
|
|
187
|
+
`create one builder per recipient and send them together in one batch.`);
|
|
84
188
|
}
|
|
85
189
|
this.#recipients.push({ partyId, permissions: ['read'] });
|
|
86
190
|
return this;
|
|
87
191
|
}
|
|
88
|
-
/**
|
|
89
|
-
* Add multiple recipients to the capsa
|
|
90
|
-
* @param partyIds - Party IDs
|
|
91
|
-
*/
|
|
92
|
-
addRecipients(...partyIds) {
|
|
93
|
-
for (const partyId of partyIds) {
|
|
94
|
-
if (!partyId || partyId.length === 0) {
|
|
95
|
-
throw new Error('Party ID cannot be empty.');
|
|
96
|
-
}
|
|
97
|
-
if (partyId.length > SERVER_LIMITS.MAX_PARTY_ID_LENGTH) {
|
|
98
|
-
throw new Error(`Party ID (${partyId.length} chars) exceeds server limit of ${SERVER_LIMITS.MAX_PARTY_ID_LENGTH} chars.`);
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
// +1 for the creator who also gets a keychain entry
|
|
102
|
-
if (this.#recipients.length + partyIds.length + 1 > SERVER_LIMITS.MAX_KEYCHAIN_KEYS) {
|
|
103
|
-
throw new Error(`Cannot add ${partyIds.length} recipients: keychain would have ${this.#recipients.length + partyIds.length + 1} entries (max ${SERVER_LIMITS.MAX_KEYCHAIN_KEYS}). Server will reject this capsa.`);
|
|
104
|
-
}
|
|
105
|
-
for (const partyId of partyIds) {
|
|
106
|
-
this.#recipients.push({ partyId, permissions: ['read'] });
|
|
107
|
-
}
|
|
108
|
-
return this;
|
|
109
|
-
}
|
|
110
192
|
/**
|
|
111
193
|
* Add a file to the capsa
|
|
112
194
|
* @param input - File input (path or buffer with filename)
|
|
113
|
-
* @throws
|
|
195
|
+
* @throws CapsaraError (VALIDATION_ERROR) if the file name contains "/", "\" or
|
|
196
|
+
* control characters, is empty or only spaces, or is "." or ".."; if the file
|
|
197
|
+
* exceeds the size limit; or if the capsa already has the maximum number of files
|
|
114
198
|
*/
|
|
115
199
|
addFile(input) {
|
|
200
|
+
const filenameProblem = filenameSendProblem(input.filename);
|
|
201
|
+
if (filenameProblem) {
|
|
202
|
+
throw validationError(filenameProblem);
|
|
203
|
+
}
|
|
204
|
+
const fieldProblem = fileFieldProblem(input);
|
|
205
|
+
if (fieldProblem) {
|
|
206
|
+
throw validationError(fieldProblem);
|
|
207
|
+
}
|
|
208
|
+
// A date format error is VALIDATION_ERROR at input time, like the capsa's own expiration
|
|
209
|
+
if (input.expiresAt !== undefined) {
|
|
210
|
+
const ms = typeof input.expiresAt === 'string' ? parseRfc3339Ms(input.expiresAt) : input.expiresAt.getTime();
|
|
211
|
+
if (ms === undefined || Number.isNaN(ms)) {
|
|
212
|
+
throw validationError(fileExpirationFormatProblem(input.filename, input.expiresAt));
|
|
213
|
+
}
|
|
214
|
+
}
|
|
116
215
|
if (this.#files.length >= this.#limits.maxFilesPerCapsa) {
|
|
117
|
-
throw
|
|
216
|
+
throw validationError(`Cannot add file: capsa already has ${this.#files.length} files (max: ${this.#limits.maxFilesPerCapsa})`);
|
|
118
217
|
}
|
|
119
218
|
let fileSize;
|
|
120
219
|
if (input.buffer) {
|
|
121
220
|
fileSize = input.buffer.length;
|
|
122
221
|
}
|
|
123
222
|
else if (input.path) {
|
|
124
|
-
fileSize =
|
|
223
|
+
fileSize = fileSizeAt(input.path);
|
|
125
224
|
}
|
|
126
225
|
else {
|
|
127
|
-
throw
|
|
226
|
+
throw validationError('File input must have either path or buffer');
|
|
128
227
|
}
|
|
129
228
|
if (fileSize > this.#limits.maxFileSize) {
|
|
130
|
-
throw
|
|
229
|
+
throw validationError(`File "${input.filename}" exceeds maximum size of ${Math.floor(this.#limits.maxFileSize / 1024 / 1024)}MB (${fileSize} bytes)`);
|
|
131
230
|
}
|
|
132
231
|
this.#files.push({ input });
|
|
133
232
|
return this;
|
|
134
233
|
}
|
|
234
|
+
/**
|
|
235
|
+
* The master key wrapped for one party. A public key PEM that cannot be used (not SPKI, not
|
|
236
|
+
* RSA, unparseable, not canonical DER) is `INVALID_PUBLIC_KEY`, status 0, with the party in
|
|
237
|
+
* `details`: the same code every SDK gives a caller for an unusable public key.
|
|
238
|
+
*/
|
|
239
|
+
#wrapMasterKeyFor(partyKey) {
|
|
240
|
+
try {
|
|
241
|
+
return encryptMasterKeyForParty(this.#masterKey, partyKey.publicKey);
|
|
242
|
+
}
|
|
243
|
+
catch (error) {
|
|
244
|
+
if (error instanceof InvalidPublicKeyError) {
|
|
245
|
+
throw new CapsaraError(INVALID_PUBLIC_KEY_MESSAGE, 'INVALID_PUBLIC_KEY', 0, { partyId: partyKey.id });
|
|
246
|
+
}
|
|
247
|
+
throw error;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Checks a party's public key and returns its fingerprint, computed from the PEM, never taken
|
|
252
|
+
* from the record. In one fixed order, the same in every builder: parse (`INVALID_PUBLIC_KEY`),
|
|
253
|
+
* size (`UNSUPPORTED_KEY_SIZE`: exactly 4096 bits, the server's registration rule), then the
|
|
254
|
+
* stated fingerprint (`FINGERPRINT_MISMATCH`, the server's registration code). All status 0 with
|
|
255
|
+
* the party in `details`; the keychain entry is never labelled with a fingerprint the key does
|
|
256
|
+
* not have, and the wrap that follows never sees a key the server would not have registered.
|
|
257
|
+
*/
|
|
258
|
+
#checkPartyKey(partyKey) {
|
|
259
|
+
let computed;
|
|
260
|
+
let bits;
|
|
261
|
+
try {
|
|
262
|
+
computed = calculateKeyFingerprint(partyKey.publicKey);
|
|
263
|
+
bits = publicKeyBits(partyKey.publicKey);
|
|
264
|
+
}
|
|
265
|
+
catch (error) {
|
|
266
|
+
if (error instanceof InvalidPublicKeyError) {
|
|
267
|
+
throw new CapsaraError(INVALID_PUBLIC_KEY_MESSAGE, 'INVALID_PUBLIC_KEY', 0, { partyId: partyKey.id });
|
|
268
|
+
}
|
|
269
|
+
throw error;
|
|
270
|
+
}
|
|
271
|
+
if (bits !== REQUIRED_KEY_BITS) {
|
|
272
|
+
throw new CapsaraError(unsupportedKeySizeMessage(bits), 'UNSUPPORTED_KEY_SIZE', 0, { partyId: partyKey.id });
|
|
273
|
+
}
|
|
274
|
+
if (partyKey.fingerprint && partyKey.fingerprint !== computed) {
|
|
275
|
+
throw new CapsaraError(FINGERPRINT_MISMATCH_MESSAGE, 'FINGERPRINT_MISMATCH', 0, {
|
|
276
|
+
partyId: partyKey.id,
|
|
277
|
+
expected: partyKey.fingerprint,
|
|
278
|
+
actual: computed,
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
return computed;
|
|
282
|
+
}
|
|
135
283
|
/**
|
|
136
284
|
* Add a file from a file path
|
|
137
285
|
* @param filePath - File path on disk
|
|
@@ -195,6 +343,11 @@ export class CapsaBuilder {
|
|
|
195
343
|
this.structured[keyOrData] = value;
|
|
196
344
|
}
|
|
197
345
|
else {
|
|
346
|
+
// Structured data is a JSON object on the wire and every receiver refuses anything else;
|
|
347
|
+
// an array, string, number or null here would be spread into index keys or dropped silently
|
|
348
|
+
if (keyOrData === null || typeof keyOrData !== 'object' || Array.isArray(keyOrData)) {
|
|
349
|
+
throw validationError(STRUCTURED_NOT_OBJECT_MESSAGE);
|
|
350
|
+
}
|
|
198
351
|
Object.assign(this.structured, keyOrData);
|
|
199
352
|
}
|
|
200
353
|
return this;
|
|
@@ -229,22 +382,23 @@ export class CapsaBuilder {
|
|
|
229
382
|
fileData = input.buffer;
|
|
230
383
|
}
|
|
231
384
|
else if (input.path) {
|
|
232
|
-
fileData =
|
|
385
|
+
fileData = readFileAt(input.path);
|
|
233
386
|
}
|
|
234
387
|
else {
|
|
235
|
-
throw
|
|
388
|
+
throw buildFailed('FILE_SOURCE_MISSING', 'File input must have either path or buffer');
|
|
389
|
+
}
|
|
390
|
+
if (fileData.length === 0) {
|
|
391
|
+
throw buildFailed('EMPTY_FILE', `File "${input.filename}" is empty`);
|
|
236
392
|
}
|
|
237
393
|
const originalSize = fileData.length;
|
|
238
|
-
const shouldCompressFile = input.compress !== false && shouldCompress(originalSize);
|
|
239
394
|
let dataToEncrypt = fileData;
|
|
240
395
|
let compressed = false;
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
compressed = true;
|
|
246
|
-
compressionAlgorithm = 'gzip';
|
|
396
|
+
if (input.compress !== false) {
|
|
397
|
+
const compression = await compressIfBeneficial(fileData);
|
|
398
|
+
dataToEncrypt = compression.data;
|
|
399
|
+
compressed = compression.compressed;
|
|
247
400
|
}
|
|
401
|
+
const compressionAlgorithm = compressed ? 'gzip' : undefined;
|
|
248
402
|
const raw = encryptAESRaw(dataToEncrypt, this.#masterKey);
|
|
249
403
|
const hash = computeHash(raw.encryptedData);
|
|
250
404
|
const contentIV = raw.iv.toString('base64url');
|
|
@@ -270,13 +424,43 @@ export class CapsaBuilder {
|
|
|
270
424
|
}
|
|
271
425
|
/**
|
|
272
426
|
* Build the capsa with encryption and signature.
|
|
273
|
-
* @param partyKeys - Public keys for
|
|
427
|
+
* @param partyKeys - Public keys for the creator, the recipient and its delegates
|
|
428
|
+
* (other parties in the list are ignored)
|
|
274
429
|
*/
|
|
275
430
|
async build(partyKeys) {
|
|
431
|
+
const principal = this.#recipients[0];
|
|
432
|
+
if (!principal) {
|
|
433
|
+
throw buildFailed('NO_RECIPIENT', NO_RECIPIENT_MESSAGE);
|
|
434
|
+
}
|
|
276
435
|
// No-content guard: server requires files OR a message (subject/body)
|
|
277
436
|
const hasContent = this.#files.length > 0 || this.subject || this.body;
|
|
278
437
|
if (!hasContent) {
|
|
279
|
-
throw
|
|
438
|
+
throw buildFailed('NO_CONTENT', 'Capsa must contain either files or a message (subject/body). Server will reject empty capsas.');
|
|
439
|
+
}
|
|
440
|
+
if (!this.#expiresAt) {
|
|
441
|
+
throw buildFailed('EXPIRATION_REQUIRED', 'Expiration is required. Call withExpiration() with the date this capsa should ' +
|
|
442
|
+
'expire, based on how long the record needs to be retained.');
|
|
443
|
+
}
|
|
444
|
+
const now = Date.now();
|
|
445
|
+
const maxDays = maxExpirationDays(this.#limits);
|
|
446
|
+
const latestExpiry = now + maxDays * DAY_MS;
|
|
447
|
+
const capsaExpiry = new Date(this.#expiresAt).getTime();
|
|
448
|
+
if (capsaExpiry <= now) {
|
|
449
|
+
throw buildFailed('EXPIRATION_IN_PAST', `Expiration ${this.#expiresAt} is in the past. Set an expiration after the current time.`);
|
|
450
|
+
}
|
|
451
|
+
if (capsaExpiry > latestExpiry) {
|
|
452
|
+
throw buildFailed('EXPIRATION_TOO_FAR', `Expiration ${this.#expiresAt} is more than ${maxDays} days in the future. The latest allowed expiration is ${maxDays} days from now.`);
|
|
453
|
+
}
|
|
454
|
+
const principalKey = partyKeys.find((key) => key.id === principal.partyId);
|
|
455
|
+
if (!principalKey?.publicKey) {
|
|
456
|
+
throw new CapsaraError(`Recipient ${principal.partyId} has no registered public key`, 'RECIPIENT_KEY_NOT_FOUND', 0, { partyId: principal.partyId });
|
|
457
|
+
}
|
|
458
|
+
// The server registers only RSA-4096 keys and verifies with the creator's registered key, and
|
|
459
|
+
// a signature is 512 bytes everywhere: a signing key of any other size can never produce an
|
|
460
|
+
// acceptable capsa. One code and message for a wrong size, in every builder and on the server.
|
|
461
|
+
const creatorBits = creatorKeyBits(this.#creatorPrivateKey);
|
|
462
|
+
if (creatorBits !== undefined && creatorBits !== REQUIRED_KEY_BITS) {
|
|
463
|
+
throw new CapsaraError(unsupportedKeySizeMessage(creatorBits), 'UNSUPPORTED_KEY_SIZE', 0, { partyId: this.#creatorId });
|
|
280
464
|
}
|
|
281
465
|
const packageId = `capsa_${generateId(22)}`;
|
|
282
466
|
const encryptedFiles = [];
|
|
@@ -285,13 +469,34 @@ export class CapsaBuilder {
|
|
|
285
469
|
const encrypted = await this.#encryptFile(file.input);
|
|
286
470
|
const { encryptedData: encryptedFilename, iv: filenameIV, authTag: filenameAuthTag } = encryptAES(Buffer.from(file.input.filename, 'utf-8'), this.#masterKey);
|
|
287
471
|
if (encryptedFilename.length > SERVER_LIMITS.MAX_ENCRYPTED_FILENAME) {
|
|
288
|
-
throw
|
|
472
|
+
throw buildFailed('FILENAME_TOO_LONG', `Encrypted filename for "${file.input.filename.slice(0, 30)}..." (${encryptedFilename.length} chars) exceeds server limit of ${SERVER_LIMITS.MAX_ENCRYPTED_FILENAME} chars. Use a shorter filename.`);
|
|
289
473
|
}
|
|
290
474
|
let normalizedFileExpiresAt;
|
|
291
475
|
if (file.input.expiresAt !== undefined) {
|
|
292
|
-
const
|
|
476
|
+
const fileMs = typeof file.input.expiresAt === 'string'
|
|
477
|
+
? parseRfc3339Ms(file.input.expiresAt)
|
|
478
|
+
: file.input.expiresAt.getTime();
|
|
479
|
+
if (fileMs === undefined || Number.isNaN(fileMs)) {
|
|
480
|
+
// addFile has already refused a malformed date; a date format error is VALIDATION_ERROR
|
|
481
|
+
// everywhere (never a build reason), so this cannot be reached with a checked input
|
|
482
|
+
throw validationError(fileExpirationFormatProblem(file.input.filename, file.input.expiresAt));
|
|
483
|
+
}
|
|
484
|
+
const dateObj = new Date(fileMs);
|
|
293
485
|
dateObj.setSeconds(0, 0);
|
|
294
486
|
normalizedFileExpiresAt = dateObj.toISOString();
|
|
487
|
+
// INVALID_FILE_EXPIRATION means what it means on the server: a file expiry in the past or
|
|
488
|
+
// later than the capsa's (multipart.ts); the format is never this code
|
|
489
|
+
if (dateObj.getTime() <= now) {
|
|
490
|
+
throw buildFailed('INVALID_FILE_EXPIRATION', `Expiration for "${file.input.filename}" (${normalizedFileExpiresAt}) is in the past. Set an expiration after the current time.`);
|
|
491
|
+
}
|
|
492
|
+
if (dateObj.getTime() > latestExpiry) {
|
|
493
|
+
throw buildFailed('FILE_EXPIRATION_TOO_FAR', `Expiration for "${file.input.filename}" (${normalizedFileExpiresAt}) is more than ${maxDays} days in the future. ` +
|
|
494
|
+
`The latest allowed expiration is ${maxDays} days from now.`);
|
|
495
|
+
}
|
|
496
|
+
if (dateObj.getTime() > capsaExpiry) {
|
|
497
|
+
throw buildFailed('INVALID_FILE_EXPIRATION', `Expiration for "${file.input.filename}" (${normalizedFileExpiresAt}) is after the capsa ` +
|
|
498
|
+
`expires (${this.#expiresAt}). A file cannot outlive the capsa that carries it.`);
|
|
499
|
+
}
|
|
295
500
|
}
|
|
296
501
|
const fileMetadata = {
|
|
297
502
|
fileId: `file_${generateId(16)}.enc`,
|
|
@@ -317,7 +522,7 @@ export class CapsaBuilder {
|
|
|
317
522
|
totalSize += encrypted.size;
|
|
318
523
|
}
|
|
319
524
|
if (totalSize > this.#limits.maxTotalSize) {
|
|
320
|
-
throw
|
|
525
|
+
throw buildFailed('TOTAL_SIZE_EXCEEDED', `Total capsa size ${totalSize} bytes exceeds maximum of ${Math.floor(this.#limits.maxTotalSize / 1024 / 1024)}MB`);
|
|
321
526
|
}
|
|
322
527
|
let encryptedSubject;
|
|
323
528
|
let subjectIV;
|
|
@@ -334,7 +539,7 @@ export class CapsaBuilder {
|
|
|
334
539
|
subjectIV = result.iv;
|
|
335
540
|
subjectAuthTag = result.authTag;
|
|
336
541
|
if (encryptedSubject.length > SERVER_LIMITS.MAX_ENCRYPTED_SUBJECT) {
|
|
337
|
-
throw
|
|
542
|
+
throw buildFailed('SUBJECT_TOO_LARGE', `Encrypted subject (${encryptedSubject.length} chars) exceeds server limit of ${SERVER_LIMITS.MAX_ENCRYPTED_SUBJECT} chars. Reduce subject length.`);
|
|
338
543
|
}
|
|
339
544
|
}
|
|
340
545
|
if (this.body) {
|
|
@@ -343,7 +548,7 @@ export class CapsaBuilder {
|
|
|
343
548
|
bodyIV = result.iv;
|
|
344
549
|
bodyAuthTag = result.authTag;
|
|
345
550
|
if (encryptedBody.length > SERVER_LIMITS.MAX_ENCRYPTED_BODY) {
|
|
346
|
-
throw
|
|
551
|
+
throw buildFailed('BODY_TOO_LARGE', `Encrypted body (${encryptedBody.length} chars) exceeds server limit of ${SERVER_LIMITS.MAX_ENCRYPTED_BODY} chars. Reduce body length.`);
|
|
347
552
|
}
|
|
348
553
|
}
|
|
349
554
|
const hasStructured = Object.keys(this.structured).length > 0;
|
|
@@ -353,55 +558,58 @@ export class CapsaBuilder {
|
|
|
353
558
|
structuredIV = result.iv;
|
|
354
559
|
structuredAuthTag = result.authTag;
|
|
355
560
|
if (encryptedStructured.length > SERVER_LIMITS.MAX_ENCRYPTED_STRUCTURED) {
|
|
356
|
-
throw
|
|
561
|
+
throw buildFailed('STRUCTURED_TOO_LARGE', `Encrypted structured data (${encryptedStructured.length} chars) exceeds server limit of ${SERVER_LIMITS.MAX_ENCRYPTED_STRUCTURED} chars. Reduce structured data size.`);
|
|
357
562
|
}
|
|
358
563
|
}
|
|
359
564
|
const keychain = [];
|
|
360
565
|
for (const partyKey of partyKeys) {
|
|
361
|
-
const recipient = this.#recipients.find((r) => r.partyId === partyKey.id);
|
|
362
566
|
const isCreator = partyKey.id === this.#creatorId;
|
|
363
|
-
|
|
567
|
+
const isPrincipal = partyKey.id === principal.partyId;
|
|
568
|
+
// A delegate is included only when it acts for this capsa's recipient, and
|
|
569
|
+
// then only on that recipient's behalf.
|
|
570
|
+
const actsForPrincipal = !isPrincipal &&
|
|
571
|
+
Array.isArray(partyKey.isDelegate) &&
|
|
572
|
+
partyKey.isDelegate.includes(principal.partyId);
|
|
573
|
+
let permissions;
|
|
364
574
|
let actingFor;
|
|
365
|
-
if (
|
|
366
|
-
const recipientIds = this.#recipients.map(r => r.partyId);
|
|
367
|
-
const relevantActingFor = partyKey.isDelegate.filter(id => recipientIds.includes(id));
|
|
368
|
-
if (relevantActingFor.length === 0) {
|
|
369
|
-
continue;
|
|
370
|
-
}
|
|
371
|
-
if (relevantActingFor.length > SERVER_LIMITS.MAX_ACTING_FOR) {
|
|
372
|
-
throw new Error(`Delegate "${partyKey.id}" acting for ${relevantActingFor.length} parties exceeds server limit of ${SERVER_LIMITS.MAX_ACTING_FOR}.`);
|
|
373
|
-
}
|
|
575
|
+
if (actsForPrincipal) {
|
|
374
576
|
permissions = ['delegate'];
|
|
375
|
-
actingFor =
|
|
577
|
+
actingFor = [principal.partyId];
|
|
376
578
|
}
|
|
377
579
|
else if (isCreator) {
|
|
378
580
|
permissions = [];
|
|
379
581
|
}
|
|
380
|
-
else if (
|
|
381
|
-
permissions =
|
|
382
|
-
actingFor = recipient.actingFor;
|
|
582
|
+
else if (isPrincipal) {
|
|
583
|
+
permissions = principal.permissions;
|
|
383
584
|
}
|
|
384
585
|
else {
|
|
385
586
|
continue;
|
|
386
587
|
}
|
|
387
588
|
const isDelegatedRecipient = permissions.length === 0 && !isCreator;
|
|
388
589
|
const keyIV = generateIV();
|
|
590
|
+
// A delegated recipient gets no key and keeps the record's fingerprint; everyone else is
|
|
591
|
+
// checked (parse, size, fingerprint) and labelled with the fingerprint computed from the key
|
|
592
|
+
// the master key is then wrapped with
|
|
593
|
+
const fingerprint = isDelegatedRecipient ? partyKey.fingerprint : this.#checkPartyKey(partyKey);
|
|
594
|
+
const encryptedKey = isDelegatedRecipient ? '' : this.#wrapMasterKeyFor(partyKey);
|
|
389
595
|
keychain.push({
|
|
390
596
|
party: partyKey.id,
|
|
391
|
-
encryptedKey
|
|
392
|
-
? ''
|
|
393
|
-
: encryptMasterKeyForParty(this.#masterKey, partyKey.publicKey),
|
|
597
|
+
encryptedKey,
|
|
394
598
|
iv: keyIV,
|
|
395
|
-
fingerprint
|
|
599
|
+
fingerprint,
|
|
396
600
|
permissions,
|
|
397
601
|
actingFor,
|
|
398
|
-
revoked: false,
|
|
399
602
|
});
|
|
400
603
|
}
|
|
604
|
+
if (keychain.length > SERVER_LIMITS.MAX_KEYCHAIN_KEYS) {
|
|
605
|
+
throw buildFailed('TOO_MANY_KEYCHAIN_ENTRIES', `Keychain has ${keychain.length} entries (creator, recipient and delegates), exceeding the server limit of ${SERVER_LIMITS.MAX_KEYCHAIN_KEYS}.`);
|
|
606
|
+
}
|
|
401
607
|
const canonicalString = buildCanonicalString({
|
|
402
608
|
packageId,
|
|
403
609
|
totalSize,
|
|
404
610
|
algorithm: 'AES-256-GCM',
|
|
611
|
+
creatorPartyId: this.#creatorId,
|
|
612
|
+
creatorKeyFingerprint: calculatePrivateKeyFingerprint(this.#creatorPrivateKey),
|
|
405
613
|
files: encryptedFiles.map((f) => f.metadata),
|
|
406
614
|
structuredIV,
|
|
407
615
|
subjectIV,
|
|
@@ -409,7 +617,7 @@ export class CapsaBuilder {
|
|
|
409
617
|
});
|
|
410
618
|
const signature = createCapsaSignature(canonicalString, this.#creatorPrivateKey);
|
|
411
619
|
if (signature.payload.length > SERVER_LIMITS.MAX_SIGNATURE_PAYLOAD) {
|
|
412
|
-
throw
|
|
620
|
+
throw buildFailed('SIGNATURE_TOO_LARGE', `Signature payload (${signature.payload.length} chars) exceeds server limit of ${SERVER_LIMITS.MAX_SIGNATURE_PAYLOAD} chars.`);
|
|
413
621
|
}
|
|
414
622
|
const capsa = {
|
|
415
623
|
packageId,
|
|
@@ -427,23 +635,28 @@ export class CapsaBuilder {
|
|
|
427
635
|
const hasMetadata = this.metadata.label || this.metadata.tags?.length || this.metadata.notes || this.metadata.relatedPackages?.length;
|
|
428
636
|
if (hasMetadata) {
|
|
429
637
|
if (this.metadata.label && this.metadata.label.length > SERVER_LIMITS.MAX_METADATA_LABEL) {
|
|
430
|
-
throw
|
|
638
|
+
throw buildFailed('METADATA_LABEL_TOO_LONG', `Metadata label (${this.metadata.label.length} chars) exceeds server limit of ${SERVER_LIMITS.MAX_METADATA_LABEL} chars.`);
|
|
431
639
|
}
|
|
432
640
|
if (this.metadata.tags && this.metadata.tags.length > SERVER_LIMITS.MAX_METADATA_TAGS) {
|
|
433
|
-
throw
|
|
641
|
+
throw buildFailed('TOO_MANY_TAGS', `Metadata tags count (${this.metadata.tags.length}) exceeds server limit of ${SERVER_LIMITS.MAX_METADATA_TAGS}.`);
|
|
434
642
|
}
|
|
435
643
|
if (this.metadata.tags) {
|
|
436
644
|
for (const tag of this.metadata.tags) {
|
|
437
645
|
if (tag.length > SERVER_LIMITS.MAX_TAG_LENGTH) {
|
|
438
|
-
throw
|
|
646
|
+
throw buildFailed('TAG_TOO_LONG', `Metadata tag "${tag.slice(0, 20)}..." (${tag.length} chars) exceeds server limit of ${SERVER_LIMITS.MAX_TAG_LENGTH} chars.`);
|
|
439
647
|
}
|
|
440
648
|
}
|
|
441
649
|
}
|
|
442
650
|
if (this.metadata.notes && this.metadata.notes.length > SERVER_LIMITS.MAX_METADATA_NOTES) {
|
|
443
|
-
throw
|
|
651
|
+
throw buildFailed('METADATA_NOTES_TOO_LONG', `Metadata notes (${this.metadata.notes.length} chars) exceeds server limit of ${SERVER_LIMITS.MAX_METADATA_NOTES} chars.`);
|
|
444
652
|
}
|
|
445
653
|
if (this.metadata.relatedPackages && this.metadata.relatedPackages.length > SERVER_LIMITS.MAX_RELATED_PACKAGES) {
|
|
446
|
-
throw
|
|
654
|
+
throw buildFailed('TOO_MANY_RELATED_PACKAGES', `Related packages count (${this.metadata.relatedPackages.length}) exceeds server limit of ${SERVER_LIMITS.MAX_RELATED_PACKAGES}.`);
|
|
655
|
+
}
|
|
656
|
+
for (const related of this.metadata.relatedPackages ?? []) {
|
|
657
|
+
if (related.length > SERVER_LIMITS.MAX_RELATED_PACKAGE_LENGTH) {
|
|
658
|
+
throw buildFailed('RELATED_PACKAGE_TOO_LONG', `Related package reference "${related.substring(0, 20)}..." (${related.length} chars) exceeds server limit of ${SERVER_LIMITS.MAX_RELATED_PACKAGE_LENGTH} chars.`);
|
|
659
|
+
}
|
|
447
660
|
}
|
|
448
661
|
capsa.metadata = this.metadata;
|
|
449
662
|
}
|
|
@@ -462,6 +675,11 @@ export class CapsaBuilder {
|
|
|
462
675
|
capsa.structuredIV = structuredIV;
|
|
463
676
|
capsa.structuredAuthTag = structuredAuthTag;
|
|
464
677
|
}
|
|
678
|
+
const capsaJsonBytes = Buffer.byteLength(JSON.stringify(capsa), 'utf8');
|
|
679
|
+
if (capsaJsonBytes > SERVER_LIMITS.MAX_JSON_FIELD) {
|
|
680
|
+
throw buildFailed('CAPSA_JSON_TOO_LARGE', `Capsa metadata (${capsaJsonBytes} bytes) exceeds the server limit of ${SERVER_LIMITS.MAX_JSON_FIELD} bytes per JSON field. ` +
|
|
681
|
+
'Reduce the body, structured data or metadata.');
|
|
682
|
+
}
|
|
465
683
|
// Defense-in-depth: detect duplicate IVs across all fields.
|
|
466
684
|
// Server performs the same check and will reject duplicates.
|
|
467
685
|
const allIVs = [];
|
|
@@ -481,7 +699,7 @@ export class CapsaBuilder {
|
|
|
481
699
|
}
|
|
482
700
|
const ivSet = new Set(allIVs);
|
|
483
701
|
if (ivSet.size !== allIVs.length) {
|
|
484
|
-
throw
|
|
702
|
+
throw buildFailed('DUPLICATE_IV', 'Duplicate IV detected across capsa fields. This indicates a CSPRNG failure. Do not send this capsa.');
|
|
485
703
|
}
|
|
486
704
|
return { capsa, files: encryptedFiles };
|
|
487
705
|
}
|