1//
2// Common stuff
3// ʕ•ᴥ•ʔ
4
5
6import * as crypto from "../crypto"
7import { db } from "../common"
8
9
10export const SECRET_KEY_LOCATION = "SECRET_KEY"
11
12
13// 🔱
14
15
16export function isLocalHost(url: string) {
17 return (
18 url.startsWith("localhost") ||
19 url.startsWith("localhost") ||
20 url.startsWith("127.0.0.1") ||
21 url.startsWith("127.0.0.1")
22 )
23}
24
25
26export function parseJsonIfNeeded(a: unknown) {
27 if (typeof a === "string") return JSON.parse(a)
28 return a
29}
30
31
32export function reportError(app, event) {
33 return e => {
34 const err = e ? e.message || e : null
35 if (err) {
36 console.error(err, e.stack)
37 app.ports.fromAlien.send({ tag: event.tag, data: null, error: err })
38 }
39 }
40}
41
42
43export function sendData(app, event, opts: any = {}) {
44 return data => {
45 app.ports.fromAlien.send({
46 tag: event.tag,
47 data: (opts && opts.parseJSON && typeof data === "string")
48 ? JSON.parse(data)
49 : (data || null),
50 error: null
51 })
52 }
53}
54
55
56
57// Cache
58// -----
59
60export function removeCache(key: string): Promise<void> {
61 return db().removeItem(key)
62}
63
64
65export function fromCache(key: string): Promise<unknown> {
66 return db().getItem(key)
67}
68
69
70export function toCache(key: string, data: unknown): Promise<unknown> {
71 return db().setItem(key, data)
72}
73
74
75
76// Crypto
77// ------
78
79export function decryptIfNeeded(data: unknown): Promise<unknown | null> {
80 if (typeof data !== "string") {
81 return Promise.resolve(data)
82
83 } else if (typeof data === "string" && (data.startsWith("{") || data.startsWith("["))) {
84 return Promise.resolve(data)
85
86 } else if (data.length < 15 && Number.isInteger(parseInt(data, 10))) {
87 return Promise.resolve(data)
88
89 } else {
90 return data
91 ? getSecretKey().then(secretKey => {
92 if (!secretKey) throw new Error("There seems to be existing data that's encrypted, I will need the passphrase (ie. encryption key) to continue.")
93 return crypto.decrypt(secretKey, data)
94 })
95 : Promise.resolve(null)
96
97 }
98}
99
100
101export async function encryptIfPossible(unencryptedData: string): Promise<string> {
102 return unencryptedData
103 ? getSecretKey().then(secretKey =>
104 secretKey
105 ? crypto.encrypt(secretKey, unencryptedData)
106 : unencryptedData
107 )
108 : unencryptedData
109}
110
111
112export { encryptIfPossible as encryptWithSecretKey }
113
114
115export function getSecretKey(): Promise<CryptoKey | null> {
116 return db().getItem(SECRET_KEY_LOCATION)
117}