@progressive-development/pd-provider-firebase-functions 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/visits.js CHANGED
@@ -1,105 +1,147 @@
1
- import { createHash } from 'node:crypto';
2
- import { Timestamp, FieldValue } from 'firebase-admin/firestore';
3
- import { getDb } from './firestore.js';
4
-
5
- const DEVICES = ["phone", "tablet", "desktop"];
6
- const BOTS = /bot|crawl|spider|slurp|preview|monitor|headless|lighthouse|curl|wget/i;
7
- const ALREADY_EXISTS = 6;
1
+ import { getDb } from "./firestore.js";
2
+ import { FieldValue, Timestamp } from "firebase-admin/firestore";
3
+ import { createHash } from "node:crypto";
4
+ //#region src/visits.ts
5
+ var DEVICES = [
6
+ "phone",
7
+ "tablet",
8
+ "desktop"
9
+ ];
10
+ /** Deliberately short: this keeps out the loudest noise, it is not a bot list. */
11
+ var BOTS = /bot|crawl|spider|slurp|preview|monitor|headless|lighthouse|curl|wget/i;
12
+ /** Firestore ALREADY_EXISTS — a gRPC status code, not an HTTP one. */
13
+ var ALREADY_EXISTS = 6;
14
+ /**
15
+ * The day as YYYY-MM-DD in the given zone.
16
+ *
17
+ * "sv-SE" is the shortest way to an ISO-shaped date: `toISOString()` would be
18
+ * UTC, and building it by hand from parts is where off-by-one bugs live.
19
+ */
8
20
  function visitDay(now, timeZone) {
9
- return new Intl.DateTimeFormat("sv-SE", { timeZone }).format(now);
21
+ return new Intl.DateTimeFormat("sv-SE", { timeZone }).format(now);
10
22
  }
23
+ /** The stretch of time a visitor key stays the same. */
11
24
  function visitPeriod(day, rotate) {
12
- return rotate === "month" ? day.slice(0, 7) : day;
25
+ return rotate === "month" ? day.slice(0, 7) : day;
13
26
  }
27
+ /** The technical key — short enough to read, long enough not to collide. */
14
28
  function visitorKey(period, ip, userAgent, secret = "") {
15
- return createHash("sha256").update(`${secret}|${period}|${ip}|${userAgent}`).digest("hex").slice(0, 16);
29
+ return createHash("sha256").update(`${secret}|${period}|${ip}|${userAgent}`).digest("hex").slice(0, 16);
16
30
  }
31
+ /** Unknown values are dropped, never guessed and never stored raw. */
17
32
  function cleanDevice(value) {
18
- return typeof value === "string" && DEVICES.includes(value) ? value : void 0;
33
+ return typeof value === "string" && DEVICES.includes(value) ? value : void 0;
19
34
  }
35
+ /** A host, nothing else — no path, no query, no room for someone else's data. */
20
36
  function cleanReferrer(value) {
21
- if (typeof value !== "string") return void 0;
22
- const host = value.trim().toLowerCase();
23
- return /^[a-z0-9.\-:]{1,60}$/.test(host) ? host : void 0;
37
+ if (typeof value !== "string") return void 0;
38
+ const host = value.trim().toLowerCase();
39
+ return /^[a-z0-9.\-:]{1,60}$/.test(host) ? host : void 0;
24
40
  }
25
41
  function isBot(userAgent) {
26
- return BOTS.test(userAgent);
42
+ return BOTS.test(userAgent);
27
43
  }
44
+ /**
45
+ * Browser family and major version.
46
+ *
47
+ * ORDER IS THE WHOLE TRICK, because these strings quote each other: Edge says
48
+ * Edg AND Chrome AND Safari, Chrome says Chrome AND Safari. So the most
49
+ * specific claim wins, and Safari is asked last. On iOS every engine is
50
+ * Safari's, but the browsers name themselves (CriOS, FxiOS) — reported as what
51
+ * the user sees, since that is what the question is about.
52
+ *
53
+ * Unclassified traffic becomes "other" rather than nothing: an unreadable
54
+ * agent is a fact worth seeing, missing data is a different fact.
55
+ */
28
56
  function browserOf(userAgent) {
29
- const rules = [
30
- ["Edge", /Edg(?:iOS|A)?\/(\d+)/],
31
- ["Opera", /OPR\/(\d+)/],
32
- ["Samsung Internet", /SamsungBrowser\/(\d+)/],
33
- ["Chrome", /CriOS\/(\d+)/],
34
- ["Firefox", /FxiOS\/(\d+)/],
35
- ["Firefox", /Firefox\/(\d+)/],
36
- ["Chrome", /Chrome\/(\d+)/],
37
- ["Safari", /Version\/(\d+)[\d.]*\s+(?:Mobile\/\S+\s+)?Safari/]
38
- ];
39
- for (const [browser, pattern] of rules) {
40
- const hit = pattern.exec(userAgent);
41
- if (hit) return { browser, version: hit[1] };
42
- }
43
- return { browser: "other" };
57
+ for (const [browser, pattern] of [
58
+ ["Edge", /Edg(?:iOS|A)?\/(\d+)/],
59
+ ["Opera", /OPR\/(\d+)/],
60
+ ["Samsung Internet", /SamsungBrowser\/(\d+)/],
61
+ ["Chrome", /CriOS\/(\d+)/],
62
+ ["Firefox", /FxiOS\/(\d+)/],
63
+ ["Firefox", /Firefox\/(\d+)/],
64
+ ["Chrome", /Chrome\/(\d+)/],
65
+ ["Safari", /Version\/(\d+)[\d.]*\s+(?:Mobile\/\S+\s+)?Safari/]
66
+ ]) {
67
+ const hit = pattern.exec(userAgent);
68
+ if (hit) return {
69
+ browser,
70
+ version: hit[1]
71
+ };
72
+ }
73
+ return { browser: "other" };
44
74
  }
75
+ /**
76
+ * Operating system family, never a version.
77
+ *
78
+ * Android carries "Linux" in its agent and an iPad in desktop mode calls
79
+ * itself a Macintosh — so the order matters here too, and the iPad stays
80
+ * wrong. That is a limit of the source, not something to guess around.
81
+ */
45
82
  function osOf(userAgent) {
46
- if (/iPhone|iPad|iPod/.test(userAgent)) return "iOS";
47
- if (/Android/.test(userAgent)) return "Android";
48
- if (/CrOS/.test(userAgent)) return "ChromeOS";
49
- if (/Windows/.test(userAgent)) return "Windows";
50
- if (/Macintosh|Mac OS X/.test(userAgent)) return "macOS";
51
- if (/Linux/.test(userAgent)) return "Linux";
52
- return "other";
83
+ if (/iPhone|iPad|iPod/.test(userAgent)) return "iOS";
84
+ if (/Android/.test(userAgent)) return "Android";
85
+ if (/CrOS/.test(userAgent)) return "ChromeOS";
86
+ if (/Windows/.test(userAgent)) return "Windows";
87
+ if (/Macintosh|Mac OS X/.test(userAgent)) return "macOS";
88
+ if (/Linux/.test(userAgent)) return "Linux";
89
+ return "other";
53
90
  }
91
+ /** No list means no restriction; an empty match means this call does not count. */
54
92
  function originAllowed(origin, allowed) {
55
- if (!allowed) return true;
56
- const list = Array.isArray(allowed) ? allowed : [allowed];
57
- return typeof origin === "string" && list.includes(origin);
93
+ if (!allowed) return true;
94
+ return typeof origin === "string" && (Array.isArray(allowed) ? allowed : [allowed]).includes(origin);
58
95
  }
96
+ /** First entry of x-forwarded-for; the rest are proxies. */
59
97
  function clientIp(headers) {
60
- const raw = headers["x-forwarded-for"];
61
- const value = Array.isArray(raw) ? raw[0] : raw;
62
- if (typeof value !== "string") return void 0;
63
- const first = value.split(",")[0]?.trim();
64
- return first || void 0;
98
+ const raw = headers["x-forwarded-for"];
99
+ const value = Array.isArray(raw) ? raw[0] : raw;
100
+ if (typeof value !== "string") return void 0;
101
+ return value.split(",")[0]?.trim() || void 0;
65
102
  }
103
+ /**
104
+ * Count one visit — or recognise that this visitor was already counted today.
105
+ *
106
+ * Never throws for the ordinary "does not count" cases (wrong origin, bot, no
107
+ * address, already seen): the caller is a fire-and-forget call from a page
108
+ * that must not care.
109
+ */
66
110
  async function countVisit(request, visit = {}, options = {}) {
67
- const headers = request.rawRequest?.headers ?? {};
68
- const day = visitDay(/* @__PURE__ */ new Date(), options.timeZone ?? "UTC");
69
- const skip = { counted: false, day };
70
- if (!originAllowed(headers.origin, options.origin)) return skip;
71
- const userAgent = typeof headers["user-agent"] === "string" ? headers["user-agent"] : "";
72
- if (!userAgent || isBot(userAgent)) return skip;
73
- const ip = clientIp(headers);
74
- if (!ip) return skip;
75
- const { browser, version } = browserOf(userAgent);
76
- const period = visitPeriod(day, options.rotate ?? "day");
77
- const visitor = visitorKey(period, ip, userAgent, options.secret);
78
- try {
79
- await getDb(options.databaseId).collection(options.collection ?? "visits").doc(`${day}_${visitor}`).create({
80
- day,
81
- visitor,
82
- at: FieldValue.serverTimestamp(),
83
- // Missing is missing: getDb ignores undefined, so an absent value
84
- // leaves no empty field behind.
85
- device: cleanDevice(visit.device),
86
- standalone: visit.standalone === true,
87
- referrer: cleanReferrer(visit.referrer),
88
- // Read from the agent the server already has — the client sends
89
- // nothing for these. Family and MAJOR version only; the full string
90
- // stays where it cannot be read back, in the key.
91
- browser,
92
- browserVersion: version,
93
- os: osOf(userAgent),
94
- expires: options.retentionDays ? Timestamp.fromMillis(
95
- Date.now() + options.retentionDays * 864e5
96
- ) : void 0
97
- });
98
- return { counted: true, day };
99
- } catch (e) {
100
- if (e?.code === ALREADY_EXISTS) return skip;
101
- throw e;
102
- }
111
+ const headers = request.rawRequest?.headers ?? {};
112
+ const day = visitDay(/* @__PURE__ */ new Date(), options.timeZone ?? "UTC");
113
+ const skip = {
114
+ counted: false,
115
+ day
116
+ };
117
+ if (!originAllowed(headers.origin, options.origin)) return skip;
118
+ const userAgent = typeof headers["user-agent"] === "string" ? headers["user-agent"] : "";
119
+ if (!userAgent || isBot(userAgent)) return skip;
120
+ const ip = clientIp(headers);
121
+ if (!ip) return skip;
122
+ const { browser, version } = browserOf(userAgent);
123
+ const visitor = visitorKey(visitPeriod(day, options.rotate ?? "day"), ip, userAgent, options.secret);
124
+ try {
125
+ await getDb(options.databaseId).collection(options.collection ?? "visits").doc(`${day}_${visitor}`).create({
126
+ day,
127
+ visitor,
128
+ at: FieldValue.serverTimestamp(),
129
+ device: cleanDevice(visit.device),
130
+ standalone: visit.standalone === true,
131
+ referrer: cleanReferrer(visit.referrer),
132
+ browser,
133
+ browserVersion: version,
134
+ os: osOf(userAgent),
135
+ expires: options.retentionDays ? Timestamp.fromMillis(Date.now() + options.retentionDays * 864e5) : void 0
136
+ });
137
+ return {
138
+ counted: true,
139
+ day
140
+ };
141
+ } catch (e) {
142
+ if (e?.code === ALREADY_EXISTS) return skip;
143
+ throw e;
144
+ }
103
145
  }
104
-
146
+ //#endregion
105
147
  export { browserOf, cleanDevice, cleanReferrer, clientIp, countVisit, isBot, originAllowed, osOf, visitDay, visitPeriod, visitorKey };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@progressive-development/pd-provider-firebase-functions",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Firebase Functions v2 utilities for pd-spa-helper backend",
5
5
  "author": "PD Progressive Development",
6
6
  "license": "SEE LICENSE IN LICENSE",
@@ -11,19 +11,22 @@
11
11
  "exports": {
12
12
  ".": "./dist/index.js"
13
13
  },
14
+ "bin": {
15
+ "pd-prepare-functions-deploy": "./bin/prepare-functions-deploy.mjs"
16
+ },
14
17
  "files": [
15
18
  "dist/",
19
+ "bin/",
16
20
  "package.json",
17
21
  "README.md",
18
22
  "LICENSE"
19
23
  ],
20
- "dependencies": {
21
- "firebase-admin": "^12.6.0",
22
- "firebase-functions": "^6.0.0"
24
+ "engines": {
25
+ "node": "22"
23
26
  },
24
27
  "peerDependencies": {
25
- "firebase-admin": "^12.6.0",
26
- "firebase-functions": "^6.0.0"
28
+ "firebase-admin": ">=12.6.0 <15",
29
+ "firebase-functions": ">=6 <8"
27
30
  },
28
31
  "keywords": [
29
32
  "pd",
@@ -33,12 +36,16 @@
33
36
  "functions",
34
37
  "backend"
35
38
  ],
39
+ "devDependencies": {
40
+ "firebase-admin": "^14.3.0",
41
+ "firebase-functions": "^7.3.2"
42
+ },
36
43
  "scripts": {
37
44
  "build": "vite build",
38
45
  "clean": "rm -rf dist",
39
46
  "clean:all": "rm -rf dist node_modules pnpm-lock.yaml",
40
- "lint": "eslint --ext .ts src --ignore-path ../../.eslintignore && prettier \"**/*.ts\" --check --ignore-path ../../.eslintignore",
41
- "format": "eslint --ext .ts src --fix --ignore-path ../../.eslintignore && prettier \"**/*.ts\" --write --ignore-path ../../.eslintignore",
47
+ "lint": "eslint src && prettier \"**/*.ts\" --check --ignore-path ../../.eslintignore",
48
+ "format": "eslint src --fix && prettier \"**/*.ts\" --write --ignore-path ../../.eslintignore",
42
49
  "check": "pnpm run lint && pnpm run build",
43
50
  "test": "vitest run"
44
51
  }