Setting up HTTPS on Deno , with self signed certificate? - deno

I was setting up a Deno server to handle HTTPS request, I used self signed certificates to do the job.
Used below code for this:
import { serveTLS } from "https://deno.land/std/http/server.ts";
const body = new TextEncoder().encode("Hello HTTPS");
const options = {
hostname: "localhost",
port: 443,
certFile: "./path/to/localhost.crt",
keyFile: "./path/to/localhost.key",
};
// Top-level await supported
for await (const req of serveTLS(options)) {
req.respond({ body });
}
I ran this code as: deno --allow-net --allow-read app.ts
I get following error:
ERROR RS - rustls::session:571 - TLS alert received: Message {
typ: Alert,
version: TLSv1_3,
payload: Alert(
AlertMessagePayload {
level: Fatal,
description: BadCertificate,
},
),
}
error: Uncaught InvalidData: received fatal alert: BadCertificate
► $deno$/errors.ts:57:13
at InvalidData ($deno$/errors.ts:135:5)
at constructError ($deno$/errors.ts:57:13)
at unwrapResponse ($deno$/dispatch_json.ts:41:12)
at sendAsync ($deno$/dispatch_json.ts:96:10)
Is it possible to use self signed certificates with Deno ?
What went wrong and how to fix it ?

It was a problem with my certificate files, strangly the same certificates were working with nodejs.
I created local certificates and key than using this mkcert, then it worked!

If you're on MacOS, the best way to fix this is to instruct Deno to look at the system as the CA store.
Run this, then try again to see if you still get a warning/error:
export DENO_TLS_CA_STORE=system
You probably also want this in your .bash_profile as well.

Related

Fail to connect to socket.io server on Window Server in dotnet core

I host a very simple node socket IO application on my Window Server, below are the code sample.
// socket.io 3.1.2"
const port = 30080;
const httpServer = require("http").createServer();
const io = require("socket.io")(httpServer, {
cors: {
origin: '*',
methods: ["GET", "POST"],
allowedHeaders: ["Access-Control-Allow-Origin"],
credentials: false
}
});
io.on("connection", socket => {
console.log('On Connection');
io.emit("message", 'Welcome to Socket Io.');
});
And I wrote some code to try connect to my socket IO server in a HTML File and work well. below are the code sample.
// <script src="https://cdn.socket.io/3.1.3/socket.io.min.js"></script>
const socket = io("http://myserverip:30080", {
withCredentials: false,
extraHeaders: {
"Access-Control-Allow-Origin": "*"
}
});
socket.on("connect", () => {
console.log('connect');
});
socket.on("message", (message) => {
console.log(message);
});
But when I try to use those above code in my .NET Core web application, I get the error "ERR_SSL_PROTOCOL_ERROR". Even I publish my web application on the Window Server still getting the same error message.
I have tried http, https, ws and wss protocol. None of these work. How can I get this possibly working?
I do not see the following in your server side code:
httpServer.listen()
Do you have a reverse proxy between your client and the server?
I would expect no SSL related error based on you code.
I would also use socket.io version 4 just for future maintenance reasons.

Deno web workers - Cannot find name "window"

I'm trying to run a Deno app with a deno_webview and an http server but for some reason I cannot run both at the same time, calling webview.run() seems to block something and I can no longer reach my http server.
In order to prevent the blocking, I'm trying running either the server or the webview in a webworker, but in both scenarios I get the same error "Cannot find name 'window'"
What is the issue here?
api.webworker.ts
import { Application } from 'https://deno.land/x/oak/mod.ts';
const app = new Application();
await app.listen({ port: 8080 });
webview.webworker.ts
import { WebView } from 'https://deno.land/x/webview/mod.ts';
const webview = new WebView({ url: 'http://localhost:4200' });
await webview.run();
server.ts
const webviewWorker = new Worker(
'./workers/webview.worker.ts', {
type: 'module',
deno: true
});
Error:
const apiWorker = new Worker(
'./workers/api.worker.ts', {
type: 'module',
deno: true
});
Error:
Web Workers don't have window object, you have to use self or globalThis
So https://deno.land/x/webview/mod.ts doesn't support being called from a Web Worker.
The library will need to change window usage to globalThis so it will work int the main process and inside workers.

Deno run is not working properly also drun

After created an index.ts and wrote a simple code for listening to port 3000 and printing hello world on the body, I'm also not able to run or get the output from deno's drun module.
import { Application, Router } from "https://deno.land/x/denotrain#v0.5.0/mod.ts";
const app = new Application();
const router = new Router();
// Middleware
app.use((ctx) => {
ctx.cookies["user.session"] = "qwertz";
ctx.cookies["a"] = "123";
ctx.cookies["b"] = "456";
delete ctx.cookies["user.session"];
return;
});
router.get("/", (ctx) => {
return new Promise((resolve) => resolve("This is the admin interface!"));
});
router.get("/edit", async (ctx) => {
return "This is an edit mode!";
});
app.get("/", (ctx) => {
return {"hello": "world"};
});
app.use("/admin", router);
app.get("/:id", (ctx) => {
// Use url parameters
return "Hello World with ID: " + ctx.req.params.id
});
return ctx.req.body;
});
await app.run()
Development Environment:- Windows 10
The problem seems to be the address 0.0.0.0 is specific to mac only.Windows Doesn't use 0.0.0.0 address.
After going to localhost:3000 / 127.0.0.1:3000. I was able to get the output.I think maybe Windows redirects the 0.0.0.0 to localhost. Anyway it solved my problem!
I am on windows. I faced with the same problem. Then,
const app = new Application({hostname:"127.0.0.1"});
I created the app in typescript giving parameter hostname like above.
And run deno like this:
deno run --allow-net=127.0.0.1 index.ts
it worked.
Run your server with the following command:
drun watch --entryPoint=./server.ts --runtimeOptions=--allow-net
In any case most Deno tools for watching changes are still bugged, I recommend to use nodemon, with --exec flag
nodemon --exec deno run --allow-net server.ts
For convenience you can use nodemon.json with the following content:
{
"execMap": {
"js": "deno run --allow-net",
"ts": "deno run --allow-net"
},
"ext": "js,json,ts"
}
And now just use: nodemon server.ts
It seems that you have an error in your code snippet, with the last
return ctx.req.body;
});
If you fix that and use the last deno (v1.0.1) and drun(v1.1.0) versions it should works with the following command:
drun --entryPoint=index.ts --runtimeOptions=--allow-net

Unable to access URLs other than googleapis.com from Firebase emulator using fetch()

I'm trying to create some Firebase Cloud Functions and test them locally using
firebase emulators:start --only functions
These functions supposed to call some external services using fetch.
I find that I can call these external services when the functions are deployed to the Firebase cloud, but cannot invoke them when running locally in the emulator:
import 'cross-fetch/polyfill';
export const fetchTest = functions
.region(config.firebaseRegion)
.https.onRequest((request: Request, response: Response) => {
fetch("https://www.wikipedia.org/", {
method: 'GET',
}).then(value => {
console.log("Fetched: ", value);
}).catch(reason => {
console.log("Fetch failed: ", reason);
});
fetch("https://googleapis.com/foo", {
method: 'GET',
}).then(value => {
console.log("Fetched: ", value);
}).catch(reason => {
console.log("Fetch failed: ", reason);
});
response.send("Done");
});
This is the output I get when invoking fetchTest in the emulator:
⚠ Unknown network resource requested!
- URL: "https://www.wikipedia.org/"
⚠ Google API requested!
- URL: "https://googleapis.com/foo"
- Be careful, this may be a production service.
Looking at the source code there seems to be some filtering implemented in the emulator:
https://github.com/firebase/firebase-tools/blob/0586ee1e23adc64b0fe8607a026ba472a6bd7d2e/src/emulator/functionsEmulatorRuntime.ts
if (href && !history[href]) {
history[href] = true;
if (href.indexOf("googleapis.com") !== -1) {
new EmulatorLog("SYSTEM", "googleapis-network-access", "", {
href,
module: bundle.name,
}).log();
} else {
new EmulatorLog("SYSTEM", "unidentified-network-access", "", {
href,
module: bundle.name,
}).log();
}
}
Are there any reason for such restrictions? And is there a workaround for this?
Thanks!
When you see "Unknown network requested" logs like this one:
⚠ Unknown network resource requested!
- URL: "https://www.wikipedia.org/"
They are just warnings. The actual request is allowed through. The log is meant to tell you that the emulators are accessing resources outside your machine. This is normally something people want to avoid because local testing is meant to be hermetic, but sometimes it's what you want to do and you can ignore the warnings safely!

Connection to Azure Cosmosdb failed using web socket

I have a script that connects to CosmosDB to make some operations, am using CosmosDB as graphDB, however, am using a node module called gremlin-secure which connects to cosmosDB through web sockets, however, recently, I could not connect to the Database as below error
events.js:160
throw er; // Unhandled 'error' event
^
Error: unexpected server response (200)
at ClientRequest._req.on (/Users/abshahin/dev/azure-cosmos-db-graph-nodejs-getting-started/node_modules/ws/lib/WebSocket.js:656:26)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:473:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
at TLSSocket.socketOnData (_http_client.js:362:20)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at TLSSocket.Readable.push (_stream_readable.js:134:10)
my code looks like this
"use strict";
var Gremlin = require('gremlin-secure');
var config = require("./config");
const client = Gremlin.createClient(
443,
config.endpoint,
{
"session": false,
"ssl": true,
"user": `/dbs/${config.database}/colls/${config.collection}`,
"password": config.primaryKey
});
client.execute("g.addV('employee').property('id', 'abshahin')", { }, (err, results) => {
if (err) return console.error(err);
console.log(JSON.stringify(results));
});
and this is my config
var config = {}
config.endpoint = "xxxxxxxx.graphs.azure.com";
config.primaryKey = "super secret key";
config.database = "dbname"
config.collection = "collectionName"
module.exports = config;
I contacted Microsoft and they advised to post here, any help.
Check to make sure that the url of the db looks like xxx.graphs.azure.com the ulr displayed in the azure portal was not correct in my case.
This looks a bit similar to a problem I faced recently. Make sure you have latest OpenSSL version
openssl version -a
Azure CosmosDB enforces SSL/TLS 1.2 which is not supported by older versions of OpenSSL

Resources