UNPKG

@tak-ps/node-tak

Version:

Lightweight JavaScript library for communicating with TAK Server

103 lines 3.04 kB
import fetch from './fetch.js'; import { Type } from '@sinclair/typebox'; import { CookieJar, Cookie } from 'tough-cookie'; import { CookieAgent } from 'http-cookie-agent/undici'; import { Client } from 'undici'; import stream2buffer from './stream.js'; /** * Store the TAK Client Certificate for a connection */ export const TAKAuth = Type.Object({ cert: Type.String(), key: Type.String(), passphrase: Type.Optional(Type.String()), ca: Type.Optional(Type.String()), rejectUnauthorized: Type.Optional(Type.Boolean()) }); export class APIAuth { async init(api) { } async fetch(api, url, opts) { return await fetch(url, opts); } } export class APIAuthPassword extends APIAuth { username; password; jwt; constructor(username, password) { super(); this.username = username; this.password = password; this.jwt = ''; } async init(api) { const { token } = await api.OAuth.login({ username: this.username, password: this.password }); this.jwt = token; } async fetch(api, url, opts) { const jar = new CookieJar(); await jar.setCookie(new Cookie({ key: 'access_token', value: this.jwt }), String(api.url)); opts.credentials = 'include'; if (!opts.nocookies) { const agent = new CookieAgent({ cookies: { jar } }); opts.dispatcher = agent; } return await fetch(url, opts); } } export class APIAuthToken extends APIAuth { jwt; constructor(jwt) { super(); this.jwt = jwt; } async fetch(api, url, opts) { const jar = new CookieJar(); await jar.setCookie(new Cookie({ key: 'access_token', value: this.jwt }), String(api.url)); opts.credentials = 'include'; if (!opts.nocookies) { const agent = new CookieAgent({ cookies: { jar } }); opts.dispatcher = agent; } return await fetch(url, opts); } } export class APIAuthCertificate extends APIAuth { cert; key; constructor(cert, key) { super(); this.cert = cert; this.key = key; } async fetch(api, url, opts) { const client = new Client(api.url.origin, { connect: { key: this.key, cert: this.cert, rejectUnauthorized: false, } }); const res = await client.request({ path: String(url).replace(api.url.origin, ''), ...opts }); return { status: res.statusCode, body: res.body, // Make this similiar to the fetch standard headers: new Map(Object.entries(res.headers)), text: async () => { return String(await stream2buffer(res.body)); }, json: async () => { return JSON.parse(String(await stream2buffer(res.body))); }, }; } } //# sourceMappingURL=auth.js.map