@cobol-ts/crypto-packager 0.0.0-stage → 0.0.20
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 +36 -3
- package/dist/index.d.ts +6 -0
- package/dist/index.js +23 -0
- package/dist/index.js.map +1 -0
- package/dist/src/identity.d.ts +7 -0
- package/dist/src/identity.js +42 -0
- package/dist/src/identity.js.map +1 -0
- package/dist/src/identity.spec.d.ts +1 -0
- package/dist/src/identity.spec.js +34 -0
- package/dist/src/identity.spec.js.map +1 -0
- package/dist/src/local.d.ts +31 -0
- package/dist/src/local.js +106 -0
- package/dist/src/local.js.map +1 -0
- package/dist/src/packager.d.ts +16 -0
- package/dist/src/packager.js +297 -0
- package/dist/src/packager.js.map +1 -0
- package/dist/src/packager.spec.d.ts +1 -0
- package/dist/src/packager.spec.js +171 -0
- package/dist/src/packager.spec.js.map +1 -0
- package/dist/src/store.d.ts +16 -0
- package/dist/src/store.js +74 -0
- package/dist/src/store.js.map +1 -0
- package/dist/src/types.d.ts +87 -0
- package/dist/src/types.js +3 -0
- package/dist/src/types.js.map +1 -0
- package/dist/src/zip.d.ts +8 -0
- package/dist/src/zip.js +156 -0
- package/dist/src/zip.js.map +1 -0
- package/index.ts +6 -0
- package/package.json +64 -3
package/README.md
CHANGED
|
@@ -1,3 +1,36 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @cobol-ts/crypto-packager
|
|
2
|
+
|
|
3
|
+
Streaming authenticated file packaging independent of COBOL parsing, compositions, customer identities and storage providers. The CLI adapter is in `@cobol-ts/cobolts` (`crypto` command group).
|
|
4
|
+
|
|
5
|
+
## Security and format
|
|
6
|
+
|
|
7
|
+
Each logical source file becomes `<logical/path>.zip.enc`:
|
|
8
|
+
|
|
9
|
+
1. ZIP exactly one original entry, with the original path and byte content.
|
|
10
|
+
2. Obtain a **fresh independent 32-byte content encryption key** from `FileKeyProvider`.
|
|
11
|
+
3. Encrypt the ZIP stream with libsodium `crypto_secretstream_xchacha20poly1305`. Store its **24-byte stream header** at the beginning of the encrypted object, followed by 4-byte big-endian chunk lengths and authenticated chunks; the final chunk must carry `TAG_FINAL`. The header is also copied into the signed manifest for inspection and identity checking.
|
|
12
|
+
4. SHA-256 hash the full ciphertext object (including its stream header and framing), and record its byte length.
|
|
13
|
+
5. Publish each encrypted object; then publish `crypto.manifest.json`; **publish the detached Ed25519 signature last**. Readers authenticate the exact manifest bytes using independently trusted signing public keys before using any package data.
|
|
14
|
+
|
|
15
|
+
AAD is a canonical UTF-8 JSON array of `cobol-ts:stream-aad:v1`, package kind, package ID, generation and original logical path. It is attached to the first authenticated chunk, including the final empty chunk when applicable.
|
|
16
|
+
|
|
17
|
+
The **local-sealed-box** provider generates a fresh random 32-byte content key for every file and wraps it with the configured X25519 recipient public key using libsodium `crypto_box_seal`. The signed per-file metadata holds the wrapped file key, recipient ID and SHA-256 public-key fingerprint. The recipient **private key never enters the archive**. This is key *wrapping*, not Google key derivation; it does not create a fake per-file salt.
|
|
18
|
+
|
|
19
|
+
The future **google-hsm-hmac-sha256** provider implements the same `FileKeyProvider` interface but derives the content key by calling Google Cloud KMS HSM `macSign` with a canonical length-prefixed identity and a fresh 32-byte salt. Its metadata must identify the exact key version and salt. The master HSM key stays non-exportable. The HMAC result, if returned to the application, is the 32-byte content key and can be shown by the explicit diagnostic `crypto key` operation. A provider performing encryption entirely within a cloud service can instead omit key export capability; that is a separate adapter choice. The Google implementation and live integration tests are **not part of this local phase**.
|
|
20
|
+
|
|
21
|
+
**Cipher naming:** this implementation uses XChaCha20-Poly1305 with a 256-bit key, *not AES-256-GCM*. If the bank requires AES-256-GCM, the authenticated streaming cipher/profile must be replaced by an approved protocol, not just relabelled.
|
|
22
|
+
|
|
23
|
+
## Interfaces
|
|
24
|
+
|
|
25
|
+
`ObjectStore` supplies streaming read/write and file inventory. `FileKeyProvider` creates and recovers per-file content keys from signed metadata and can inspect its public information. `ManifestSigner` signs and verifies using independently trusted keys. `CryptoPackager` handles packaging, signing, decryption, inspection and verification without importing a cloud SDK.
|
|
26
|
+
|
|
27
|
+
## Operational notes
|
|
28
|
+
|
|
29
|
+
- The CLI uses `crypto.yaml`; neither `files.yaml` nor a logical composition is involved.
|
|
30
|
+
- Reading a package requires the trusted signer public key and the matching recipient private key, except for an explicit per-file content-key override.
|
|
31
|
+
- Output and unpacking are staged until **decryption, TAG_FINAL, full ciphertext hash, ZIP framing and ZIP CRC** all succeed. The target must not already exist.
|
|
32
|
+
- Local read operations temporarily spool a decrypted single-entry ZIP to a private OS temporary directory to permit bounded-memory ZIP validation; it is deleted afterwards. This is local development tooling and must not be treated as secure scratch storage for production plaintext without approved controls.
|
|
33
|
+
- `crypto key` and `inspect --show-key` intentionally reveal the file's content key, not the parent/private key. Exposure permits future decryption of that ciphertext without further key-provider access; treat it as an explicit diagnostic privilege.
|
|
34
|
+
- Chunk framing, metadata and the versioned canonical AAD are part of the file format and must remain byte-exact across provider implementations.
|
|
35
|
+
|
|
36
|
+
**Publication retry:** incomplete package objects are removed when a publish operation fails, so an identical package ID can be retried after a handled failure. `StreamingCryptoPackager.remove(id)` is an explicit repository operation that deletes the signature before clearing the remaining objects and must be called only after replacement has been authorised. `sourceFiles()` also accepts an ordinary single file, whose basename becomes its logical path.
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./src/types"), exports);
|
|
18
|
+
__exportStar(require("./src/identity"), exports);
|
|
19
|
+
__exportStar(require("./src/local"), exports);
|
|
20
|
+
__exportStar(require("./src/store"), exports);
|
|
21
|
+
__exportStar(require("./src/zip"), exports);
|
|
22
|
+
__exportStar(require("./src/packager"), exports);
|
|
23
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,8CAA2B;AAC3B,iDAA8B;AAC9B,8CAA2B;AAC3B,8CAA2B;AAC3B,4CAAyB;AACzB,iDAA8B"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { FileKeyIdentity } from './types';
|
|
2
|
+
export declare function safeRelativePath(path: string): string;
|
|
3
|
+
export declare function sha256(bytes: Uint8Array): string;
|
|
4
|
+
/** Canonical AAD used by all key providers and all storage implementations. */
|
|
5
|
+
export declare function fileAad(identity: FileKeyIdentity): Uint8Array;
|
|
6
|
+
/** Unambiguous HMAC input for the future Google HSM provider. Local sealed-box does NOT use it. */
|
|
7
|
+
export declare function googleFileKeyContext(identity: FileKeyIdentity, salt: Uint8Array): Uint8Array;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.safeRelativePath = safeRelativePath;
|
|
4
|
+
exports.sha256 = sha256;
|
|
5
|
+
exports.fileAad = fileAad;
|
|
6
|
+
exports.googleFileKeyContext = googleFileKeyContext;
|
|
7
|
+
const node_crypto_1 = require("node:crypto");
|
|
8
|
+
const node_path_1 = require("node:path");
|
|
9
|
+
function safeRelativePath(path) {
|
|
10
|
+
if (!path || path.includes('\\') || path.includes('\0') || path.startsWith('/') || /^[a-zA-Z]:/.test(path))
|
|
11
|
+
throw new Error(`Unsafe relative path: ${path}`);
|
|
12
|
+
const segments = path.split('/');
|
|
13
|
+
if (segments.some(part => part === '..' || part === '.' || !part))
|
|
14
|
+
throw new Error(`Unsafe relative path: ${path}`);
|
|
15
|
+
const result = node_path_1.posix.normalize(path);
|
|
16
|
+
if (result !== path)
|
|
17
|
+
throw new Error(`Non-canonical relative path: ${path}`);
|
|
18
|
+
return result;
|
|
19
|
+
}
|
|
20
|
+
function sha256(bytes) {
|
|
21
|
+
return (0, node_crypto_1.createHash)('sha256').update(bytes).digest('hex');
|
|
22
|
+
}
|
|
23
|
+
/** Canonical AAD used by all key providers and all storage implementations. */
|
|
24
|
+
function fileAad(identity) {
|
|
25
|
+
return Buffer.from(JSON.stringify(['cobol-ts:stream-aad:v1', identity.packageKind,
|
|
26
|
+
identity.packageId, identity.generation, identity.logicalPath]), 'utf8');
|
|
27
|
+
}
|
|
28
|
+
/** Unambiguous HMAC input for the future Google HSM provider. Local sealed-box does NOT use it. */
|
|
29
|
+
function googleFileKeyContext(identity, salt) {
|
|
30
|
+
if (salt.length !== 32)
|
|
31
|
+
throw new Error('HSM file salt must be exactly 32 bytes');
|
|
32
|
+
const components = ['cobol-ts:file-key:v1', identity.packageKind, identity.packageId,
|
|
33
|
+
identity.generation, identity.logicalPath].map(s => Buffer.from(s, 'utf8'));
|
|
34
|
+
const output = [];
|
|
35
|
+
for (const part of [...components, Buffer.from(salt)]) {
|
|
36
|
+
const length = Buffer.allocUnsafe(4);
|
|
37
|
+
length.writeUInt32BE(part.length);
|
|
38
|
+
output.push(length, part);
|
|
39
|
+
}
|
|
40
|
+
return Buffer.concat(output);
|
|
41
|
+
}
|
|
42
|
+
//# sourceMapping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C,WAAW;QAC7E,QAAQ,CAAC,SAAS,EAAE,QAAQ,CAAC,UAAU,EAAE,QAAQ,CAAC,WAAW,CAAC,CAAC,EAAE,MAAM,CAAC,CAAA;AAChF,CAAC;AAED,mGAAmG;AACnG,SAAgB,oBAAoB,CAAC,QAAyB,EAAE,IAAgB;IAC5E,IAAI,IAAI,CAAC,MAAM,KAAK,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAA;IACjF,MAAM,UAAU,GAAG,CAAC,sBAAsB,EAAE,QAAQ,CAAC,WAAW,EAAE,QAAQ,CAAC,SAAS;QAChF,QAAQ,CAAC,UAAU,EAAE,QAAQ,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAA;IAC/E,MAAM,MAAM,GAAa,EAAE,CAAA;IAC3B,KAAK,MAAM,IAAI,IAAI,CAAC,GAAG,UAAU,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC;QACpD,MAAM,MAAM,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAA;QACpC,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;QACjC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;IAC7B,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;AAChC,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const identity_1 = require("./identity");
|
|
4
|
+
const identity = { packageKind: 'production', packageId: 'daily/2026-05-31',
|
|
5
|
+
generation: 'revision-one', logicalPath: 'customers.fb' };
|
|
6
|
+
describe('Crypto package identity', () => {
|
|
7
|
+
it('uses exact, stable AAD with all four identity components', () => {
|
|
8
|
+
expect(Buffer.from((0, identity_1.fileAad)(identity)).toString('utf8')).toEqual('["cobol-ts:stream-aad:v1","production","daily/2026-05-31","revision-one","customers.fb"]');
|
|
9
|
+
});
|
|
10
|
+
it('domain-separates Google HSM derivation from the local sealed-box strategy', () => {
|
|
11
|
+
const salt = Buffer.alloc(32, 7);
|
|
12
|
+
const expected = Buffer.concat([
|
|
13
|
+
Buffer.from('00000014636f626f6c2d74733a66696c652d6b65793a7631', 'hex'),
|
|
14
|
+
Buffer.from('0000000a70726f64756374696f6e', 'hex'),
|
|
15
|
+
Buffer.from('000000106461696c792f323032362d30352d3331', 'hex'),
|
|
16
|
+
Buffer.from('0000000c7265766973696f6e2d6f6e65', 'hex'),
|
|
17
|
+
Buffer.from('0000000c637573746f6d6572732e6662', 'hex'),
|
|
18
|
+
Buffer.from('00000020', 'hex'), salt
|
|
19
|
+
]);
|
|
20
|
+
expect(Buffer.from((0, identity_1.googleFileKeyContext)(identity, salt))).toEqual(expected);
|
|
21
|
+
expect(Buffer.from((0, identity_1.googleFileKeyContext)({ ...identity, generation: 'revision-two' }, salt)))
|
|
22
|
+
.not.toEqual(expected);
|
|
23
|
+
});
|
|
24
|
+
it('rejects unsafe object/ZIP member paths without normalising them', () => {
|
|
25
|
+
for (const path of ['/etc/secret', '../secret', 'a/../secret', 'a//b', 'a\\b', 'C:/secret']) {
|
|
26
|
+
expect(() => (0, identity_1.safeRelativePath)(path)).toThrow();
|
|
27
|
+
}
|
|
28
|
+
expect((0, identity_1.safeRelativePath)('nested/customer.csv')).toEqual('nested/customer.csv');
|
|
29
|
+
});
|
|
30
|
+
it('hashes the precise supplied bytes', () => {
|
|
31
|
+
expect((0, identity_1.sha256)(Buffer.from('abc'))).toEqual('ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad');
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
//# sourceMappingURL=identity.spec.js.map
|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AAC,IAAI,CAAC,IAAA,+BAAoB,EAAC,EAAC,GAAG,QAAQ,EAAE,UAAU,EAAE,cAAc,EAAC,EAAE,IAAI,CAAC,CAAC,CAAC;aACrF,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAA;IAC9B,CAAC,CAAC,CAAA;IACF,EAAE,CAAC,iEAAiE,EAAE,GAAG,EAAE;QACvE,KAAK,MAAM,IAAI,IAAI,CAAC,aAAa,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,CAAC;YAC1F,MAAM,CAAC,GAAG,EAAE,CAAC,IAAA,2BAAgB,EAAC,IAAI,CAAC,CAAC,CAAC,OAAO,EAAE,CAAA;QAClD,CAAC;QACD,MAAM,CAAC,IAAA,2BAAgB,EAAC,qBAAqB,CAAC,CAAC,CAAC,OAAO,CAAC,qBAAqB,CAAC,CAAA;IAClF,CAAC,CAAC,CAAA;IACF,EAAE,CAAC,mCAAmC,EAAE,GAAG,EAAE;QACzC,MAAM,CAAC,IAAA,iBAAM,EAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CACtC,kEAAkE,CAAC,CAAA;IAC3E,CAAC,CAAC,CAAA;AACN,CAAC,CAAC,CAAA"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { FileKeyIdentity, FileKeyMetadata, FileKeyProvider, ManifestSigner } from './types';
|
|
2
|
+
export interface LocalKeyFiles {
|
|
3
|
+
readonly recipientPublic: string;
|
|
4
|
+
readonly recipientPrivate: string;
|
|
5
|
+
readonly signerPublic: string;
|
|
6
|
+
readonly signerPrivate: string;
|
|
7
|
+
}
|
|
8
|
+
/** Explicit local developer utility; does not create or expose a Google/HSM parent key. */
|
|
9
|
+
export declare function generateLocalKeys(files: LocalKeyFiles): Promise<void>;
|
|
10
|
+
export declare class LocalSealedBoxFileKeyProvider implements FileKeyProvider {
|
|
11
|
+
private readonly publicFile;
|
|
12
|
+
private readonly privateFile;
|
|
13
|
+
private readonly recipientKeyId;
|
|
14
|
+
readonly strategy: "local-sealed-box";
|
|
15
|
+
constructor(publicFile: string, privateFile: string, recipientKeyId: string);
|
|
16
|
+
inspectPublic(): Promise<Readonly<Record<string, string>>>;
|
|
17
|
+
create(_identity: FileKeyIdentity): Promise<{
|
|
18
|
+
key: Uint8Array;
|
|
19
|
+
metadata: FileKeyMetadata;
|
|
20
|
+
}>;
|
|
21
|
+
recover(_identity: FileKeyIdentity, metadata: FileKeyMetadata): Promise<Uint8Array>;
|
|
22
|
+
}
|
|
23
|
+
export declare class LocalEd25519ManifestSigner implements ManifestSigner {
|
|
24
|
+
readonly keyId: string;
|
|
25
|
+
private readonly publicFile;
|
|
26
|
+
private readonly privateFile;
|
|
27
|
+
constructor(keyId: string, publicFile: string, privateFile: string);
|
|
28
|
+
publicKey(): Promise<Uint8Array>;
|
|
29
|
+
sign(message: Uint8Array): Promise<Uint8Array>;
|
|
30
|
+
verify(message: Uint8Array, signature: Uint8Array): Promise<boolean>;
|
|
31
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.LocalEd25519ManifestSigner = exports.LocalSealedBoxFileKeyProvider = void 0;
|
|
7
|
+
exports.generateLocalKeys = generateLocalKeys;
|
|
8
|
+
const promises_1 = require("node:fs/promises");
|
|
9
|
+
const node_path_1 = require("node:path");
|
|
10
|
+
const libsodium_wrappers_sumo_1 = __importDefault(require("libsodium-wrappers-sumo"));
|
|
11
|
+
const identity_1 = require("./identity");
|
|
12
|
+
async function ready() { await libsodium_wrappers_sumo_1.default.ready; }
|
|
13
|
+
async function readB64(filename) {
|
|
14
|
+
return Buffer.from((await (0, promises_1.readFile)(filename, 'utf8')).trim(), 'base64');
|
|
15
|
+
}
|
|
16
|
+
async function writeB64(filename, value, privateKey) {
|
|
17
|
+
await (0, promises_1.mkdir)((0, node_path_1.dirname)(filename), { recursive: true });
|
|
18
|
+
await (0, promises_1.writeFile)(filename, Buffer.from(value).toString('base64') + '\n', { flag: 'wx', mode: privateKey ? 0o600 : 0o644 });
|
|
19
|
+
}
|
|
20
|
+
/** Explicit local developer utility; does not create or expose a Google/HSM parent key. */
|
|
21
|
+
async function generateLocalKeys(files) {
|
|
22
|
+
await ready();
|
|
23
|
+
const recipient = libsodium_wrappers_sumo_1.default.crypto_box_keypair();
|
|
24
|
+
const signer = libsodium_wrappers_sumo_1.default.crypto_sign_keypair();
|
|
25
|
+
if (await Promise.all(Object.values(files).map(async (file) => {
|
|
26
|
+
try {
|
|
27
|
+
await (0, promises_1.readFile)(file);
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
catch (e) {
|
|
31
|
+
if (e.code === 'ENOENT')
|
|
32
|
+
return false;
|
|
33
|
+
throw e;
|
|
34
|
+
}
|
|
35
|
+
})).then(results => results.some(Boolean)))
|
|
36
|
+
throw new Error('Key output already exists; refusing partial replacement');
|
|
37
|
+
await writeB64(files.recipientPublic, recipient.publicKey, false);
|
|
38
|
+
await writeB64(files.recipientPrivate, recipient.privateKey, true);
|
|
39
|
+
await writeB64(files.signerPublic, signer.publicKey, false);
|
|
40
|
+
await writeB64(files.signerPrivate, signer.privateKey, true);
|
|
41
|
+
}
|
|
42
|
+
class LocalSealedBoxFileKeyProvider {
|
|
43
|
+
publicFile;
|
|
44
|
+
privateFile;
|
|
45
|
+
recipientKeyId;
|
|
46
|
+
strategy = 'local-sealed-box';
|
|
47
|
+
constructor(publicFile, privateFile, recipientKeyId) {
|
|
48
|
+
this.publicFile = publicFile;
|
|
49
|
+
this.privateFile = privateFile;
|
|
50
|
+
this.recipientKeyId = recipientKeyId;
|
|
51
|
+
}
|
|
52
|
+
async inspectPublic() {
|
|
53
|
+
const pub = await readB64(this.publicFile);
|
|
54
|
+
return { strategy: this.strategy, recipientKeyId: this.recipientKeyId,
|
|
55
|
+
publicKeyBase64: Buffer.from(pub).toString('base64'), fingerprintSha256: (0, identity_1.sha256)(pub) };
|
|
56
|
+
}
|
|
57
|
+
async create(_identity) {
|
|
58
|
+
await ready();
|
|
59
|
+
const pub = await readB64(this.publicFile);
|
|
60
|
+
if (pub.length !== libsodium_wrappers_sumo_1.default.crypto_box_PUBLICKEYBYTES)
|
|
61
|
+
throw new Error('Invalid recipient public key length');
|
|
62
|
+
const key = libsodium_wrappers_sumo_1.default.randombytes_buf(libsodium_wrappers_sumo_1.default.crypto_secretstream_xchacha20poly1305_KEYBYTES);
|
|
63
|
+
const wrapped = libsodium_wrappers_sumo_1.default.crypto_box_seal(key, pub);
|
|
64
|
+
return { key, metadata: { strategy: this.strategy, recipientKeyId: this.recipientKeyId,
|
|
65
|
+
recipientFingerprintSha256: (0, identity_1.sha256)(pub), wrappedFileKey: Buffer.from(wrapped).toString('base64') } };
|
|
66
|
+
}
|
|
67
|
+
async recover(_identity, metadata) {
|
|
68
|
+
await ready();
|
|
69
|
+
if (metadata.strategy !== this.strategy)
|
|
70
|
+
throw new Error(`Unconfigured key protection: ${metadata.strategy}`);
|
|
71
|
+
const pub = await readB64(this.publicFile);
|
|
72
|
+
if ((0, identity_1.sha256)(pub) !== metadata.recipientFingerprintSha256 || metadata.recipientKeyId !== this.recipientKeyId)
|
|
73
|
+
throw new Error('Recipient key identity does not match signed package');
|
|
74
|
+
const priv = await readB64(this.privateFile);
|
|
75
|
+
const unwrapped = libsodium_wrappers_sumo_1.default.crypto_box_seal_open(Buffer.from(metadata.wrappedFileKey, 'base64'), pub, priv);
|
|
76
|
+
if (!unwrapped || unwrapped.length !== libsodium_wrappers_sumo_1.default.crypto_secretstream_xchacha20poly1305_KEYBYTES)
|
|
77
|
+
throw new Error('Cannot recover file encryption key');
|
|
78
|
+
return unwrapped;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
exports.LocalSealedBoxFileKeyProvider = LocalSealedBoxFileKeyProvider;
|
|
82
|
+
class LocalEd25519ManifestSigner {
|
|
83
|
+
keyId;
|
|
84
|
+
publicFile;
|
|
85
|
+
privateFile;
|
|
86
|
+
constructor(keyId, publicFile, privateFile) {
|
|
87
|
+
this.keyId = keyId;
|
|
88
|
+
this.publicFile = publicFile;
|
|
89
|
+
this.privateFile = privateFile;
|
|
90
|
+
}
|
|
91
|
+
async publicKey() { return readB64(this.publicFile); }
|
|
92
|
+
async sign(message) {
|
|
93
|
+
await ready();
|
|
94
|
+
const secret = await readB64(this.privateFile);
|
|
95
|
+
const publicKey = await this.publicKey();
|
|
96
|
+
if ((0, identity_1.sha256)(libsodium_wrappers_sumo_1.default.crypto_sign_ed25519_sk_to_pk(secret)) !== (0, identity_1.sha256)(publicKey))
|
|
97
|
+
throw new Error('Signing private/public key mismatch');
|
|
98
|
+
return libsodium_wrappers_sumo_1.default.crypto_sign_detached(message, secret);
|
|
99
|
+
}
|
|
100
|
+
async verify(message, signature) {
|
|
101
|
+
await ready();
|
|
102
|
+
return libsodium_wrappers_sumo_1.default.crypto_sign_verify_detached(signature, message, await this.publicKey());
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
exports.LocalEd25519ManifestSigner = LocalEd25519ManifestSigner;
|
|
106
|
+
//# sourceMappingURL=local.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"local.js","sourceRoot":"","sources":["../../src/local.ts"],"names":[],"mappings":";;;;;;AAuBA,8CAWC;AAlCD,+CAA2D;AAC3D,yCAAiC;AACjC,sFAA4C;AAC5C,yCAAiC;AAGjC,KAAK,UAAU,KAAK,KAAK,MAAM,iCAAM,CAAC,KAAK,CAAA,CAAC,CAAC;AAC7C,KAAK,UAAU,OAAO,CAAC,QAAgB;IACnC,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,IAAA,mBAAQ,EAAC,QAAQ,EAAE,MAAM,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A;QACzD,OAAO,SAAS,CAAA;IACpB,CAAC;CACJ;AA9BD,sEA8BC;AAED,MAAa,0BAA0B;IACd;IAAgC;IAAqC;IAA1F,YAAqB,KAAa,EAAmB,UAAkB,EAAmB,WAAmB;QAAxF,UAAK,GAAL,KAAK,CAAQ;QAAmB,eAAU,GAAV,UAAU,CAAQ;QAAmB,gBAAW,GAAX,WAAW,CAAQ;IAAG,CAAC;IACjH,KAAK,CAAC,SAAS,KAA0B,OAAO,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA,CAAC,CAAC;IAC1E,KAAK,CAAC,IAAI,CAAC,OAAmB;QAC1B,MAAM,KAAK,EAAE,CAAA;QACb,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,CAAA;QAC9C,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,SAAS,EAAE,CAAA;QACxC,IAAI,IAAA,iBAAM,EAAC,iCAAM,CAAC,4BAA4B,CAAC,MAAM,CAAC,CAAC,KAAK,IAAA,iBAAM,EAAC,SAAS,CAAC;YACzE,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAA;QAC1D,OAAO,iCAAM,CAAC,oBAAoB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;IACvD,CAAC;IACD,KAAK,CAAC,MAAM,CAAC,OAAmB,EAAE,SAAqB;QACnD,MAAM,KAAK,EAAE,CAAA;QACb,OAAO,iCAAM,CAAC,2BAA2B,CAAC,SAAS,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC,CAAA;IACzF,CAAC;CACJ;AAfD,gEAeC"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { CryptoManifest, CryptoPackager, FileKeyProvider, ManifestSigner, NamedInput, ObjectStore, PackageKind } from './types';
|
|
2
|
+
/** Streaming encrypted-object inventory; the independent signature is the publication marker. */
|
|
3
|
+
export declare class StreamingCryptoPackager implements CryptoPackager {
|
|
4
|
+
readonly store: ObjectStore;
|
|
5
|
+
readonly fileKeys: FileKeyProvider;
|
|
6
|
+
readonly signer: ManifestSigner;
|
|
7
|
+
constructor(store: ObjectStore, fileKeys: FileKeyProvider, signer: ManifestSigner);
|
|
8
|
+
publish(packageId: string, files: AsyncIterable<NamedInput>, kind?: PackageKind): Promise<CryptoManifest>;
|
|
9
|
+
manifest(packageId: string): Promise<CryptoManifest>;
|
|
10
|
+
recoverKey(packageId: string, logicalPath: string): Promise<Uint8Array>;
|
|
11
|
+
private extractFile;
|
|
12
|
+
view(packageId: string, logicalPath: string, output: string, explicitKey?: Uint8Array): Promise<void>;
|
|
13
|
+
verify(packageId: string): Promise<CryptoManifest>;
|
|
14
|
+
remove(packageId: string): Promise<void>;
|
|
15
|
+
unpack(packageId: string, outputDirectory: string): Promise<void>;
|
|
16
|
+
}
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.StreamingCryptoPackager = void 0;
|
|
7
|
+
const node_crypto_1 = require("node:crypto");
|
|
8
|
+
const node_fs_1 = require("node:fs");
|
|
9
|
+
const promises_1 = require("node:fs/promises");
|
|
10
|
+
const node_path_1 = require("node:path");
|
|
11
|
+
const node_os_1 = require("node:os");
|
|
12
|
+
const node_stream_1 = require("node:stream");
|
|
13
|
+
const promises_2 = require("node:stream/promises");
|
|
14
|
+
const libsodium_wrappers_sumo_1 = __importDefault(require("libsodium-wrappers-sumo"));
|
|
15
|
+
const identity_1 = require("./identity");
|
|
16
|
+
const zip_1 = require("./zip");
|
|
17
|
+
const HEADER_BYTES = 24; // libsodium crypto_secretstream_xchacha20poly1305_HEADERBYTES
|
|
18
|
+
const MAX_FRAME = 1024 * 1024;
|
|
19
|
+
const CHUNK_SIZE = 64 * 1024;
|
|
20
|
+
async function assertAbsent(path) {
|
|
21
|
+
try {
|
|
22
|
+
await (0, promises_1.access)(path);
|
|
23
|
+
throw new Error(`Target already exists: ${path}`);
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (error.code !== 'ENOENT')
|
|
27
|
+
throw error;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
async function* encrypted(zip, key, identity, header) {
|
|
31
|
+
await libsodium_wrappers_sumo_1.default.ready;
|
|
32
|
+
if (key.length !== libsodium_wrappers_sumo_1.default.crypto_secretstream_xchacha20poly1305_KEYBYTES)
|
|
33
|
+
throw new Error('Content encryption key must be 32 bytes');
|
|
34
|
+
const state = libsodium_wrappers_sumo_1.default.crypto_secretstream_xchacha20poly1305_init_push(key);
|
|
35
|
+
header(Buffer.from(state.header).toString('base64'));
|
|
36
|
+
yield state.header;
|
|
37
|
+
const aad = (0, identity_1.fileAad)(identity);
|
|
38
|
+
let first = true;
|
|
39
|
+
const frame = (plain, last) => {
|
|
40
|
+
const cipher = libsodium_wrappers_sumo_1.default.crypto_secretstream_xchacha20poly1305_push(state.state, plain, first ? aad : null, last ? libsodium_wrappers_sumo_1.default.crypto_secretstream_xchacha20poly1305_TAG_FINAL : 0);
|
|
41
|
+
first = false;
|
|
42
|
+
const result = Buffer.allocUnsafe(4 + cipher.length);
|
|
43
|
+
result.writeUInt32BE(cipher.length, 0);
|
|
44
|
+
Buffer.from(cipher).copy(result, 4);
|
|
45
|
+
return result;
|
|
46
|
+
};
|
|
47
|
+
let previous;
|
|
48
|
+
for await (const chunk of zip) {
|
|
49
|
+
// Chunk boundaries of Node streams are not necessarily bounded. Split them explicitly.
|
|
50
|
+
for (let i = 0; i < chunk.length; i += CHUNK_SIZE) {
|
|
51
|
+
if (previous)
|
|
52
|
+
yield frame(previous, false);
|
|
53
|
+
previous = Buffer.from(chunk.subarray(i, i + CHUNK_SIZE));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
yield frame(previous ?? Buffer.alloc(0), true);
|
|
57
|
+
}
|
|
58
|
+
class ChunkReader {
|
|
59
|
+
pending = Buffer.alloc(0);
|
|
60
|
+
iterator;
|
|
61
|
+
hash = (0, node_crypto_1.createHash)('sha256');
|
|
62
|
+
bytes = 0;
|
|
63
|
+
constructor(source) { this.iterator = source[Symbol.asyncIterator](); }
|
|
64
|
+
async read(size) {
|
|
65
|
+
if (size < 0 || size > MAX_FRAME)
|
|
66
|
+
throw new Error('Invalid encrypted chunk length');
|
|
67
|
+
while (this.pending.length < size) {
|
|
68
|
+
const chunk = await this.iterator.next();
|
|
69
|
+
if (chunk.done) {
|
|
70
|
+
if (this.pending.length === 0)
|
|
71
|
+
return undefined;
|
|
72
|
+
throw new Error('Truncated encrypted stream');
|
|
73
|
+
}
|
|
74
|
+
this.hash.update(chunk.value);
|
|
75
|
+
this.bytes += chunk.value.length;
|
|
76
|
+
this.pending = Buffer.concat([this.pending, Buffer.from(chunk.value)]);
|
|
77
|
+
}
|
|
78
|
+
const value = this.pending.subarray(0, size);
|
|
79
|
+
this.pending = this.pending.subarray(size);
|
|
80
|
+
return value;
|
|
81
|
+
}
|
|
82
|
+
async exhausted() {
|
|
83
|
+
return (await this.read(1)) === undefined;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
async function* decrypted(store, packagePath, file, key, identity) {
|
|
87
|
+
await libsodium_wrappers_sumo_1.default.ready;
|
|
88
|
+
if (key.length !== libsodium_wrappers_sumo_1.default.crypto_secretstream_xchacha20poly1305_KEYBYTES)
|
|
89
|
+
throw new Error('Content encryption key must be 32 bytes');
|
|
90
|
+
const reader = new ChunkReader(store.read(packagePath));
|
|
91
|
+
const header = await reader.read(HEADER_BYTES);
|
|
92
|
+
if (!header || header.toString('base64') !== file.streamHeaderBase64)
|
|
93
|
+
throw new Error(`Stream header mismatch: ${file.path}`);
|
|
94
|
+
const state = libsodium_wrappers_sumo_1.default.crypto_secretstream_xchacha20poly1305_init_pull(header, key);
|
|
95
|
+
let first = true;
|
|
96
|
+
let ended = false;
|
|
97
|
+
while (!ended) {
|
|
98
|
+
const lengthBytes = await reader.read(4);
|
|
99
|
+
if (!lengthBytes)
|
|
100
|
+
throw new Error(`Missing TAG_FINAL: ${file.path}`);
|
|
101
|
+
const size = lengthBytes.readUInt32BE(0);
|
|
102
|
+
if (size < libsodium_wrappers_sumo_1.default.crypto_secretstream_xchacha20poly1305_ABYTES || size > MAX_FRAME)
|
|
103
|
+
throw new Error(`Invalid encrypted frame size: ${file.path}`);
|
|
104
|
+
const chunk = await reader.read(size);
|
|
105
|
+
if (!chunk)
|
|
106
|
+
throw new Error(`Truncated encrypted frame: ${file.path}`);
|
|
107
|
+
const result = libsodium_wrappers_sumo_1.default.crypto_secretstream_xchacha20poly1305_pull(state, chunk, first ? (0, identity_1.fileAad)(identity) : null);
|
|
108
|
+
if (!result)
|
|
109
|
+
throw new Error(`Failed authenticated decryption: ${file.path}`);
|
|
110
|
+
first = false;
|
|
111
|
+
ended = result.tag === libsodium_wrappers_sumo_1.default.crypto_secretstream_xchacha20poly1305_TAG_FINAL;
|
|
112
|
+
yield result.message;
|
|
113
|
+
}
|
|
114
|
+
if (!await reader.exhausted())
|
|
115
|
+
throw new Error(`Trailing ciphertext after TAG_FINAL: ${file.path}`);
|
|
116
|
+
if (reader.bytes !== file.ciphertextBytes || reader.hash.digest('hex') !== file.ciphertextSha256)
|
|
117
|
+
throw new Error(`Ciphertext hash or length mismatch: ${file.path}`);
|
|
118
|
+
}
|
|
119
|
+
function fileIdentity(manifest, logicalPath) {
|
|
120
|
+
return { packageKind: manifest.packageKind, packageId: manifest.packageId,
|
|
121
|
+
generation: manifest.generation, logicalPath };
|
|
122
|
+
}
|
|
123
|
+
function packagePath(packageId, name) {
|
|
124
|
+
return `${(0, identity_1.safeRelativePath)(packageId)}/${(0, identity_1.safeRelativePath)(name)}`;
|
|
125
|
+
}
|
|
126
|
+
function findFile(manifest, path) {
|
|
127
|
+
const file = manifest.files.find(file => file.path === (0, identity_1.safeRelativePath)(path));
|
|
128
|
+
if (!file)
|
|
129
|
+
throw new Error(`No such file in package: ${path}`);
|
|
130
|
+
return file;
|
|
131
|
+
}
|
|
132
|
+
/** Streaming encrypted-object inventory; the independent signature is the publication marker. */
|
|
133
|
+
class StreamingCryptoPackager {
|
|
134
|
+
store;
|
|
135
|
+
fileKeys;
|
|
136
|
+
signer;
|
|
137
|
+
constructor(store, fileKeys, signer) {
|
|
138
|
+
this.store = store;
|
|
139
|
+
this.fileKeys = fileKeys;
|
|
140
|
+
this.signer = signer;
|
|
141
|
+
}
|
|
142
|
+
async publish(packageId, files, kind = 'standalone') {
|
|
143
|
+
(0, identity_1.safeRelativePath)(packageId);
|
|
144
|
+
if ((await this.store.list(packageId)).length !== 0)
|
|
145
|
+
throw new Error(`Package already exists (or is incomplete): ${packageId}`);
|
|
146
|
+
try {
|
|
147
|
+
const generation = (0, node_crypto_1.randomUUID)();
|
|
148
|
+
const entries = [];
|
|
149
|
+
const seen = new Set();
|
|
150
|
+
for await (const file of files) {
|
|
151
|
+
const path = (0, identity_1.safeRelativePath)(file.path);
|
|
152
|
+
if (seen.has(path))
|
|
153
|
+
throw new Error(`Duplicate source file: ${path}`);
|
|
154
|
+
seen.add(path);
|
|
155
|
+
if (path === 'crypto.manifest.json' || path === 'crypto.manifest.json.sig')
|
|
156
|
+
throw new Error(`Reserved source filename: ${path}`);
|
|
157
|
+
const identity = { packageKind: kind, packageId, generation, logicalPath: path };
|
|
158
|
+
const created = await this.fileKeys.create(identity);
|
|
159
|
+
const encryptedPath = `${path}.zip.enc`;
|
|
160
|
+
let streamHeaderBase64 = '';
|
|
161
|
+
const hash = (0, node_crypto_1.createHash)('sha256');
|
|
162
|
+
let ciphertextBytes = 0;
|
|
163
|
+
const source = encrypted((0, zip_1.zipSingle)(path, file.stream), created.key, identity, value => { streamHeaderBase64 = value; });
|
|
164
|
+
async function* hashing() {
|
|
165
|
+
for await (const chunk of source) {
|
|
166
|
+
hash.update(chunk);
|
|
167
|
+
ciphertextBytes += chunk.length;
|
|
168
|
+
yield chunk;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
await this.store.write(packagePath(packageId, encryptedPath), hashing());
|
|
172
|
+
entries.push({ path, encryptedPath, ciphertextSha256: hash.digest('hex'),
|
|
173
|
+
ciphertextBytes, streamHeaderBase64, keyMetadata: created.metadata });
|
|
174
|
+
}
|
|
175
|
+
const publicKey = await this.signer.publicKey();
|
|
176
|
+
const manifest = { version: 1, packageKind: kind, packageId,
|
|
177
|
+
generation, cipher: 'secretstream-xchacha20poly1305', compression: 'zip-single-entry',
|
|
178
|
+
keyProtection: { strategy: this.fileKeys.strategy },
|
|
179
|
+
signer: { algorithm: 'Ed25519', keyId: this.signer.keyId, fingerprintSha256: (0, identity_1.sha256)(publicKey) }, files: entries };
|
|
180
|
+
const bytes = Buffer.from(JSON.stringify(manifest, null, 2) + '\n', 'utf8');
|
|
181
|
+
await this.store.writeBytes(packagePath(packageId, 'crypto.manifest.json'), bytes);
|
|
182
|
+
await this.store.writeBytes(packagePath(packageId, 'crypto.manifest.json.sig'), await this.signer.sign(bytes));
|
|
183
|
+
return manifest;
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
try {
|
|
187
|
+
await this.store.clear(packageId);
|
|
188
|
+
}
|
|
189
|
+
catch (cleanupError) {
|
|
190
|
+
throw new AggregateError([error, cleanupError], `Package ${packageId}: cleanup failed`);
|
|
191
|
+
}
|
|
192
|
+
throw error;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
async manifest(packageId) {
|
|
196
|
+
// Never parse or use package-supplied metadata before authenticating its exact bytes.
|
|
197
|
+
const raw = await this.store.readBytes(packagePath(packageId, 'crypto.manifest.json'));
|
|
198
|
+
const sig = await this.store.readBytes(packagePath(packageId, 'crypto.manifest.json.sig'));
|
|
199
|
+
if (!await this.signer.verify(raw, sig))
|
|
200
|
+
throw new Error(`Untrusted crypto manifest: ${packageId}`);
|
|
201
|
+
const parsed = JSON.parse(Buffer.from(raw).toString('utf8'));
|
|
202
|
+
if (!parsed || typeof parsed !== 'object' || !parsed.signer ||
|
|
203
|
+
typeof parsed.generation !== 'string' || !parsed.generation ||
|
|
204
|
+
parsed.version !== 1 || parsed.packageId !== packageId ||
|
|
205
|
+
parsed.cipher !== 'secretstream-xchacha20poly1305' || parsed.compression !== 'zip-single-entry' ||
|
|
206
|
+
!parsed.keyProtection || !['local-sealed-box', 'google-hsm-hmac-sha256'].includes(parsed.keyProtection.strategy) ||
|
|
207
|
+
!['standalone', 'production', 'shard'].includes(parsed.packageKind) ||
|
|
208
|
+
!Array.isArray(parsed.files))
|
|
209
|
+
throw new Error('Invalid crypto manifest schema');
|
|
210
|
+
if (parsed.signer.keyId !== this.signer.keyId ||
|
|
211
|
+
parsed.signer.fingerprintSha256 !== (0, identity_1.sha256)(await this.signer.publicKey()))
|
|
212
|
+
throw new Error('Signer identity mismatch');
|
|
213
|
+
const paths = new Set();
|
|
214
|
+
for (const file of parsed.files) {
|
|
215
|
+
if (!file || typeof file.path !== 'string' || typeof file.encryptedPath !== 'string' ||
|
|
216
|
+
file.encryptedPath !== `${file.path}.zip.enc` ||
|
|
217
|
+
typeof file.streamHeaderBase64 !== 'string' || typeof file.ciphertextSha256 !== 'string' ||
|
|
218
|
+
!Number.isSafeInteger(file.ciphertextBytes) || file.ciphertextBytes < HEADER_BYTES ||
|
|
219
|
+
!/^[a-f0-9]{64}$/.test(file.ciphertextSha256) ||
|
|
220
|
+
Buffer.from(file.streamHeaderBase64, 'base64').length !== HEADER_BYTES ||
|
|
221
|
+
!file.keyMetadata || file.keyMetadata.strategy !== parsed.keyProtection.strategy)
|
|
222
|
+
throw new Error('Invalid signed file entry');
|
|
223
|
+
(0, identity_1.safeRelativePath)(file.path);
|
|
224
|
+
if (paths.has(file.path))
|
|
225
|
+
throw new Error(`Duplicate signed file: ${file.path}`);
|
|
226
|
+
paths.add(file.path);
|
|
227
|
+
}
|
|
228
|
+
return parsed;
|
|
229
|
+
}
|
|
230
|
+
async recoverKey(packageId, logicalPath) {
|
|
231
|
+
const manifest = await this.manifest(packageId);
|
|
232
|
+
const file = findFile(manifest, logicalPath);
|
|
233
|
+
return this.fileKeys.recover(fileIdentity(manifest, file.path), file.keyMetadata);
|
|
234
|
+
}
|
|
235
|
+
async extractFile(manifest, file, output, explicitKey) {
|
|
236
|
+
const key = explicitKey ?? await this.fileKeys.recover(fileIdentity(manifest, file.path), file.keyMetadata);
|
|
237
|
+
const temporary = await (0, promises_1.mkdtemp)((0, node_path_1.join)((0, node_os_1.tmpdir)(), 'cobolts-decrypt-'));
|
|
238
|
+
try {
|
|
239
|
+
const zipped = (0, node_path_1.join)(temporary, 'content.zip');
|
|
240
|
+
await (0, promises_2.pipeline)(node_stream_1.Readable.from(decrypted(this.store, packagePath(manifest.packageId, file.encryptedPath), file, key, fileIdentity(manifest, file.path))), (0, node_fs_1.createWriteStream)(zipped, { flags: 'wx' }));
|
|
241
|
+
await (0, zip_1.unzipSingle)(zipped, file.path, output);
|
|
242
|
+
}
|
|
243
|
+
finally {
|
|
244
|
+
await (0, promises_1.rm)(temporary, { recursive: true, force: true });
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
async view(packageId, logicalPath, output, explicitKey) {
|
|
248
|
+
const manifest = await this.manifest(packageId);
|
|
249
|
+
const file = findFile(manifest, logicalPath);
|
|
250
|
+
await (0, promises_1.mkdir)((0, node_path_1.dirname)((0, node_path_1.resolve)(output)), { recursive: true });
|
|
251
|
+
await assertAbsent((0, node_path_1.resolve)(output));
|
|
252
|
+
const temporary = await (0, promises_1.mkdtemp)((0, node_path_1.join)((0, node_path_1.dirname)((0, node_path_1.resolve)(output)), '.cobolts-view-'));
|
|
253
|
+
try {
|
|
254
|
+
const staged = (0, node_path_1.join)(temporary, 'content');
|
|
255
|
+
await this.extractFile(manifest, file, staged, explicitKey);
|
|
256
|
+
await (0, promises_1.rename)(staged, output);
|
|
257
|
+
}
|
|
258
|
+
finally {
|
|
259
|
+
await (0, promises_1.rm)(temporary, { recursive: true, force: true });
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
async verify(packageId) {
|
|
263
|
+
const manifest = await this.manifest(packageId);
|
|
264
|
+
const dir = await (0, promises_1.mkdtemp)((0, node_path_1.join)((0, node_os_1.tmpdir)(), 'cobolts-verify-'));
|
|
265
|
+
try {
|
|
266
|
+
for (const [i, file] of manifest.files.entries())
|
|
267
|
+
await this.extractFile(manifest, file, (0, node_path_1.join)(dir, String(i)));
|
|
268
|
+
}
|
|
269
|
+
finally {
|
|
270
|
+
await (0, promises_1.rm)(dir, { recursive: true, force: true });
|
|
271
|
+
}
|
|
272
|
+
return manifest;
|
|
273
|
+
}
|
|
274
|
+
async remove(packageId) {
|
|
275
|
+
(0, identity_1.safeRelativePath)(packageId);
|
|
276
|
+
// A force replacement must remove the signature before any encrypted object.
|
|
277
|
+
await this.store.delete(packagePath(packageId, 'crypto.manifest.json.sig'));
|
|
278
|
+
await this.store.clear(packageId);
|
|
279
|
+
}
|
|
280
|
+
async unpack(packageId, outputDirectory) {
|
|
281
|
+
const manifest = await this.manifest(packageId);
|
|
282
|
+
const target = (0, node_path_1.resolve)(outputDirectory);
|
|
283
|
+
await (0, promises_1.mkdir)((0, node_path_1.dirname)(target), { recursive: true });
|
|
284
|
+
await assertAbsent(target);
|
|
285
|
+
const temporary = await (0, promises_1.mkdtemp)((0, node_path_1.join)((0, node_path_1.dirname)(target), '.cobolts-unpack-'));
|
|
286
|
+
try {
|
|
287
|
+
for (const file of manifest.files)
|
|
288
|
+
await this.extractFile(manifest, file, (0, node_path_1.join)(temporary, (0, identity_1.safeRelativePath)(file.path)));
|
|
289
|
+
await (0, promises_1.rename)(temporary, target);
|
|
290
|
+
}
|
|
291
|
+
finally {
|
|
292
|
+
await (0, promises_1.rm)(temporary, { recursive: true, force: true });
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
exports.StreamingCryptoPackager = StreamingCryptoPackager;
|
|
297
|
+
//# sourceMappingURL=packager.js.map
|