Skip to content

Commit

Permalink
fix: utils
Browse files Browse the repository at this point in the history
  • Loading branch information
arpowers committed Feb 14, 2022
1 parent 6b5bfd4 commit d67ee28
Show file tree
Hide file tree
Showing 12 changed files with 201 additions and 13,313 deletions.
13,212 changes: 0 additions & 13,212 deletions @apps/site/package-lock.json

This file was deleted.

2 changes: 1 addition & 1 deletion @apps/site/package.json
Expand Up @@ -21,7 +21,7 @@
"@factor/types": "4.0.29",
"@factor/ui": "4.0.29",
"autoprefixer": "^10.2.4",
"axios": "^0.25.0",
"axios": "^0.26.0",
"dayjs": "^1.9.6",
"deepmerge": "^4.2.2",
"events": "^3.2.0",
Expand Down
12 changes: 11 additions & 1 deletion @core/api/logger.ts
Expand Up @@ -29,6 +29,7 @@ interface LoggerArgs {
context?: string
description?: string
data?: Record<string, any> | unknown
error?: Error
disableOnRestart?: boolean
priority?: number
color?: string
Expand Down Expand Up @@ -74,7 +75,7 @@ class Logger {
}

logBrowser(config: LoggerArgs): void {
const { level, description, context, color, data } = config
const { level, description, context, color, data, error } = config
const shouldLog =
process.env.NODE_ENV == "development" ||
(typeof localStorage !== "undefined" && localStorage.getItem("logger"))
Expand All @@ -90,6 +91,10 @@ class Logger {
description,
data ?? "",
)

if (error) {
console.error(error)
}
}
}

Expand Down Expand Up @@ -124,6 +129,7 @@ class Logger {
color = "#dddddd",
data,
description,
error,
} = config

if (!this.srv.chalk) return
Expand Down Expand Up @@ -158,6 +164,10 @@ class Logger {
),
)
}

if (error) {
this.srv.consola.error(error)
}
}

log(config: LoggerArgs): void {
Expand Down
2 changes: 1 addition & 1 deletion @core/api/package.json
Expand Up @@ -21,7 +21,7 @@
"@types/spark-md5": "^3.0.2",
"@types/validator": "^13.1.3",
"@vueuse/head": "^0.7.0",
"axios": "^0.25.0",
"axios": "^0.26.0",
"blueimp-load-image": "^5.14.0",
"chalk": "^5.0.0",
"consola": "^2.15.3",
Expand Down
5 changes: 3 additions & 2 deletions @core/api/tracking.ts
Expand Up @@ -327,8 +327,9 @@ export const clickId = (
return { hash, selector, position }
}

export const getDeviceType = (): "mobile" | "tablet" | "laptop" | "desktop" => {
const width = screen.width
export const getDeviceType = (
width: number,
): "mobile" | "tablet" | "laptop" | "desktop" => {
if (width < 600) return "mobile"
else if (width < 950) return "tablet"
else if (width <= 1550) return "laptop"
Expand Down
6 changes: 3 additions & 3 deletions @core/api/utils.ts
Expand Up @@ -173,8 +173,8 @@ export const dotSetting = <T = unknown>({
* If the lower priority array has objects with _item or _ attribute,
* then we merge with the higher priority array if it has object w same _item or _
*/
export const deepMerge = <T>(
items: (T | undefined)[],
export const deepMerge = <T extends Record<string, any>>(
items: (T | Partial<T> | undefined)[],
options: { mergeArrays?: boolean } = {},
): T => {
const mergeItems = items.filter((_) => _) as T[]
Expand All @@ -186,7 +186,7 @@ export const deepMerge = <T>(
}
return higherPriority
},
})
}) as T

return merged
}
Expand Down
2 changes: 1 addition & 1 deletion @core/cli/package.json
Expand Up @@ -15,7 +15,7 @@
"@factor/server": "4.0.29",
"@factor/types": "4.0.29",
"@types/nodemon": "^1.19.1",
"axios": "^0.25.0",
"axios": "^0.26.0",
"commander": "^9.0.0",
"deepmerge": "^4.2.2",
"dotenv": "^16.0.0",
Expand Down
15 changes: 4 additions & 11 deletions @core/engine/endpointServer.ts
@@ -1,15 +1,14 @@
/** server-only-file */
import http from "http"
import express from "express"
import bodyParser from "body-parser"
import compression from "compression"
import helmet from "helmet"
import cors from "cors"

import { ErrorConfig, EndpointResponse } from "@factor/types"
import { logger, _stop, decodeClientToken, onEvent } from "@factor/api"
import { Endpoint } from "./endpoint"
import { Queries } from "./user"
import { Query } from "./query"
import { createExpressApp } from "./nodeUtils"

type CustomServerHandler = (
app: express.Express,
) => Promise<http.Server> | http.Server
Expand Down Expand Up @@ -37,13 +36,7 @@ export class EndpointServer {
}

async serverCreate(): Promise<http.Server> {
const app = express()

app.use(helmet({ crossOriginResourcePolicy: { policy: "cross-origin" } }))
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.text())
app.use(compression())
const app = createExpressApp()

this.endpoints.forEach((endpoint) => {
const { basePath, key } = endpoint
Expand Down
1 change: 1 addition & 0 deletions @core/engine/index.ts
Expand Up @@ -4,3 +4,4 @@ export * from "./query"
export * from "./email"
export * from "./user"
export * from "./userInit"
export * from "./nodeUtils"
68 changes: 68 additions & 0 deletions @core/engine/nodeUtils.ts
@@ -1,8 +1,18 @@
/* server-only-file */
import path from "path"
import http from "http"
import { createRequire } from "module"
import fs from "fs"
import glob from "glob"
import requestIp from "request-ip"
import ipUtil from "ipaddr.js"
import { getNetworkIp } from "@factor/api"
import { UserConfigServer, PackageJson } from "@factor/types"
import bodyParser from "body-parser"
import compression from "compression"
import helmet from "helmet"
import cors from "cors"
import express from "express"

const require = createRequire(import.meta.url)
export const cwd = (): string => process.env.FACTOR_CWD ?? process.cwd()
Expand Down Expand Up @@ -145,3 +155,61 @@ export const streamToString = async (
stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")))
})
}

/**
* Is an IP localhost?
*/
export const isLocalhostIp = (ip: string): boolean => {
// https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/ipv6-comparefunction
// 192.168 or c0a8 are local network
return ip == "127.0.0.1" ||
ip == "::1" ||
ip.includes("192.168") ||
ip.includes("c0a8")
? true
: false
}
/**
* Normalize IP address to v6
*/
export const normalizeIpv6 = (rawIp: string): string => {
let ipInstance = ipUtil.parse(rawIp)

if (ipInstance.kind() == "ipv4") {
ipInstance = (ipInstance as ipUtil.IPv4).toIPv4MappedAddress()
}

return ipInstance.toString()
}
/**
* All IPs should be stored and handled in ipv6 format
* https://github.com/ClickHouse/ClickHouse/issues/5462
*/
export const getRequestIpAddress = async (
request: http.IncomingMessage,
): Promise<{ ip: string; rawIp: string }> => {
let rawIp = requestIp.getClientIp(request) ?? undefined

if (!rawIp) {
return { rawIp: "", ip: "" }
}

if (isLocalhostIp(rawIp)) {
rawIp = await getNetworkIp()
}

const ip = normalizeIpv6(rawIp)

return { rawIp, ip }
}

export const createExpressApp = (): express.Express => {
const app = express()

app.use(helmet({ crossOriginResourcePolicy: { policy: "cross-origin" } }))
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.text())
app.use(compression())
return app
}
7 changes: 5 additions & 2 deletions @core/engine/package.json
Expand Up @@ -20,7 +20,7 @@
"@factor/api": "4.0.29",
"@factor/server": "4.0.29",
"@factor/types": "4.0.29",
"axios": "^0.25.0",
"axios": "^0.26.0",
"bcrypt": "^5.0.0",
"body-parser": "^1.19.0",
"compression": "^1.7.4",
Expand All @@ -40,7 +40,10 @@
"nodemailer-html-to-text": "^3.1.0",
"pg": "^8.5.1",
"serve-static": "^1.14.1",
"vue": "^3.0.2"
"vue": "^3.0.2",
"request-ip": "^2.1.3",
"ipaddr.js": "^2.0.1",
"@types/request-ip": "^0.0.37"
},
"devDependencies": {
"vitest": "^0.3.2"
Expand Down

0 comments on commit d67ee28

Please sign in to comment.