Write openpgp.encrypt stream to S3 not working - node.js

I'm trying to push the stream from openpgp.encrypt to an S3 bucket.
Typescript reports const encrypted: openpgp.WebStream<Uint8Array> though it should probably be NodeStream as I'm using nodejs v18 within an AWS Lambda. I'm using openpgpjs v5.5.0.
const publicKeyArmored = settings.publicKey
const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored })
const cleartextStream = getS3InputStream({ bucket, objectKey })
const message = await openpgp.createMessage({
text: cleartextStream,
format: 'binary'
})
const encrypted = await openpgp.encrypt({
message,
format: 'binary',
encryptionKeys: publicKey,
config: {
preferredCompressionAlgorithm: openpgp.enums.compression.uncompressed
}
})
const { s3Outstream: ws, s3Promise } = createS3OutputStream(bucket, outKey)
await pipeline(
encrypted,
ws
)
await s3Promise // wait for upload to finish
Typescript errors
No overload matches this call.
Overload 1 of 7, '(source: PipelineSource<any>, destination: PassThrough, options?: PipelineOptions | undefined): Promise<void>', gave the following error.
Argument of type 'WebStream<Uint8Array>' is not assignable to parameter of type 'PipelineSource<any>'.
Overload 2 of 7, '(streams: readonly (WritableStream | ReadableStream | ReadWriteStream)[], options?: PipelineOptions | undefined): Promise<...>', gave the following error.
Argument of type 'WebStream<Uint8Array>' is not assignable to parameter of type 'readonly (WritableStream | ReadableStream | ReadWriteStream)[]'.
Type 'WebStream<Uint8Array>' is missing the following properties from type 'readonly (WritableStream | ReadableStream | ReadWriteStream)[]': length, concat, join, slice, and 18 more.
Overload 3 of 7, '(stream1: ReadableStream, stream2: WritableStream | ReadWriteStream, ...streams: (WritableStream | ReadWriteStream | PipelineOptions)[]): Promise<...>', gave the following error.
Argument of type 'WebStream<Uint8Array>' is not assignable to parameter of type 'ReadableStream'.
Type 'WebStream<Uint8Array>' is missing the following properties from type 'ReadableStream': readable, read, setEncoding, pause, and 22 more.ts(2769)

Related

How to sign requests using opensearch-js?

I need to sign requests to Opensearch. I'm attempting to use opensearch-js and aws-es-connection to do that.
import {
createAWSConnection,
awsGetCredentials,
} from '#acuris/aws-es-connection';
import { Client } from "#opensearch-project/opensearch";
import { esConfig } from "./config";
export const getClient = async () => {
const awsCredentials = await awsGetCredentials();
const AWSConnection = createAWSConnection(awsCredentials);
const client = new Client({
...AWSConnection,
node: esConfig.uri
});
return client;
};
However, this code complains about the types not being compatible with the destructure ... syntax.
S2345: Argument of type '{ node: string; nodes?: string | string[] | NodeOptions | NodeOptions[]; Connection?: typeof Connection; ConnectionPool?: typeof ConnectionPool; ... 26 more ...; caFingerprint?: string; }' is not assignable to parameter of type 'ClientOptions'.   Types of property 'ConnectionPool' are incompatible.     Type 'typeof import("/packages/api/node_modules/#elastic/elasticsearch/lib/pool/index").ConnectionPool' is not assignable to type 'typeof import("/packages/api/node_modules/#opensearch-project/opensearch/lib/pool/index").ConnectionPool'.       Types of parameters 'opts' and 'opts' are incompatible.
...
Perhaps I'm making a dumb mistake with the destructuring? Is there another way of signing requests for opensearch-js?

RxJS Http Server with typescript compile errors

I'm pretty newbie with rxjs, can you please tell what's wrong with below?
interface IHTTP {
req: IncomingMessage;
res: ServerResponse;
handler?: Promise<any>;
}
server = http.createServer();
let request$: Observable<any>;
request$ = fromEvent(server, 'request').pipe(
map(([req, res]: [IncomingMessage, ServerResponse]): IHTTP => {
return { req, res } as IHTTP;
}
)
);
Compile error:
TS2345: Argument of type 'OperatorFunction<[IncomingMessage, ServerResponse], IHTTP>' is not assignable to parameter of type 'OperatorFunction<unknown, IHTTP>'.   Type 'unknown' is not assignable to type '[IncomingMessage, ServerResponse]'.
I found the problem I had to define fromEvent's first argument as:
server as FromEventTarget<[http.IncomingMessage, http.ServerResponse]>
Otherwise Typescript thinks it's FromEventTarget<unknown>

Argument of type '{}' is not assignable to parameter of type 'Uint8Array'

I'm trying to clone and run an opensource project repo and having hard time fixing this issue, npm start fails with "compile failed error' and its states the following reason.
Argument of type '{}' is not assignable to parameter of type 'Uint8Array'
const [encChallenge] = await waitEvent(socket, 'data')
const challenge = decrypt(encChallenge) //This line causes the error
Following in the decrypt function
/** Decrypt data used shared key */
function decrypt(data: Uint8Array) {
if (!sharedKey) return null
const nonce = data.slice(0, sodium.crypto_box_NONCEBYTES)
const box = data.slice(sodium.crypto_box_NONCEBYTES, data.length)
const msg = crypto.decrypt(box, nonce, sharedKey)
return msg
}
Changing the parameter to any solves it but I can't do that,
How can I convert my parameter to Unit8Array?
As long as encChallenge is a typed array represents an array of 8-bit unsigned integers then you should just be able to do:
const [encChallenge] = await waitEvent(socket, 'data')
const challenge = decrypt(new Uint8Array(encChallenge);)
really i would make waitEvent encChallenge be of strongly type Uint8Array in waitEvent method, then it's abstracted away and always that type if you reuse it again.

Typescript error TS2345 Error: TS2345:Argument of type 'Buffer' is not assignable to parameter of type 'string'

new to Typescript. I am reading some data from RabbitMQ channel and am converting it to JSON object. In this line I get the error
let communicationInformation = JSON.parse(newCommunication.content);
TS2345:Argument of type 'Buffer' is not assignable to parameter of type 'string'.
Do I need to cast the data? I am using Typescript 2.4.1
Amqplib.connect(amqpLibUrl, (err, connection) => {
if (!err) {
connection.createChannel((err, channel) => {
channel.consume('QueueName', newCommunication => {
if (newCommunication != null) {
let communicationInformation = JSON.parse(newCommunication.content);
// Code
}
})
})
}
});
I think the error is thrown on the input parameter of JSON.parse. Try to first call toString on it then pass to the function.
let communicationInformation = JSON.parse(newCommunication.content.toString());
I am not sure what is newCommunication.content. In my case it is a file and I had to specify encoding for fs.readFileSync:
const level = JSON.parse(fs.readFileSync('./path/to/file.json', 'utf-8'));
Next Error was error TS2531: Object is possibly 'null'.
You have to disable strictNullChecks in your compiler

TS2345: Argument of type X is not assignable to parameter of type Y

Weird error with TypeScript:
As the image indicates, the error is:
TS2345: Argument of type 'ErrnoException' is not assignable to
parameter of type '(err: ErrnoException) => void'. Type
'ErrnoException' provides no match for the signature '(err:
ErrnoException): void'.
Here is the code that causes the error:
export const bump = function(cb: ErrnoException){
const {pkg, pkgPath} = syncSetup();
fs.writeFile(pkgPath, JSON.stringify(pkg, null, 2), cb);
};
Anybody know what's going on here?
You are sending a value with the type ErrnoException, while the function you are calling expects a function that takes a parameter of type *ErrnoException** and returns void.
You send:
let x = new ErrnoException;
While the function you call expects
let cb = function(e: ErrnoException) {};
You can change your function to receive the correct parameter like this.
export const bump = function(cb: (err: ErrnoException) => void){
const {pkg, pkgPath} = syncSetup();
fs.writeFile(pkgPath, JSON.stringify(pkg, null, 2), cb);
};

Resources