net.connect(address, { tls, trust, timeout })returns a connection, c, to host:port
c.write(data, { timeout })sends text, bytes, a blob or a handle to a secret
c.read({ max, timeout })returns the next bytes, or null
c.readLine({ timeout })returns the next line as text, without its line end, or null
c.startTLS({ trust, timeout })encrypts a plain connection
c.close()closes the connection
Options:
tlstrue encrypts from the first byte; default false
trustcertificates, as PEM text, to trust in place of the computer's
maxthe most bytes a read returns; default 65536
timeoutseconds, or text such as "5m"; default 30s
- read and readLine return null once the other side has closed and nothing is left.
- readLine returns a last line that has no line end.
- TLS always checks the other side's certificate against the host in address.
- For a protocol that starts plain and then upgrades, the script sends the protocol's request, reads the whole answer and calls startTLS.
Errors:
timeoutthe call waited past its timeout; after a read the connection stays open and no bytes are lost
refusedthe connection could not be opened or failed, or the certificate was rejected
not_foundthe host's name could not be resolved
bad_inputstartTLS was called while bytes that arrived unencrypted are unread
failedreadLine read more than 1 MiB with no line end
Needs net:host for the host connected to. To write a handle, the job needs one of these.
secret:NAME@net:hoston an encrypted connection
secret:NAME@net.unencrypted:hoston a plain connection too
This script reads a WHOIS answer line by line until the server closes.
allow: [net:whois.iana.org]
const c = net.connect("whois.iana.org:43")
c.write("example.com\r\n")
const lines = []
for (let line = c.readLine(); line !== null; line = c.readLine()) lines.push(line)
c.close()
return lines
// gives ["% IANA WHOIS server", "domain: EXAMPLE.COM", "status: ACTIVE"]This script writes a secret to a connection encrypted from the first byte.
allow: [net:queue.example.com, "secret:QUEUE_TOKEN@net:queue.example.com"]
const c = net.connect("queue.example.com:6380", { tls: true })
c.write(secrets.text`AUTH ${secrets.get("QUEUE_TOKEN")}\r\n`)
const answer = c.readLine() // gives "+OK"
c.close()
return answerThis script upgrades a plain connection with STARTTLS.
allow: [net:mail.example.com]
const c = net.connect("mail.example.com:587")
c.readLine() // gives "220 mail.example.com ready"
c.write("STARTTLS\r\n")
c.readLine() // gives "220 go ahead"
c.startTLS()
c.write("NOOP\r\n")
c.read({ max: 64 }).length // gives 8
c.close()