@comify.art/thuli-link 0.0.0-stage → 1.0.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/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or exemplary damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 comify.art
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,74 @@
1
- # Temporary Holding Version
1
+ # `@comify.art/thuli-link`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
4
+
5
+ Backend Firebase Cloud Functions v2, Admin SDK, anti-spam form gateway, outbound mail worker, and dynamic OG metadata helpers for `@comify.art/thuli` applications.
6
+
7
+ ## Subpaths
8
+
9
+ | Subpath | Runtime | Highlights |
10
+ | :--- | :--- | :--- |
11
+ | `@comify.art/thuli-link/contracts` | Browser & Node.js | Zero-dependency `CONTRACT_VERSION`, `FormGuardPayload`, `isValidEmail`, `isLikelyGibberishText` |
12
+ | `@comify.art/thuli-link/forms` | Node.js (Cloud Functions v2) | `createFormHandler`, `runSubmissionGuards`, `checkRateLimit` (salted IP hash + TTL), `sanitizeHeaderValue` |
13
+ | `@comify.art/thuli-link/mail` | Node.js (Cloud Functions v2) | `createQueuedMailHandler` (`onDocumentCreated` SMTP worker with `delivery.state` tracking) |
14
+ | `@comify.art/thuli-link/meta` | Node.js (Cloud Functions v2) | `createDynamicMetaRenderer`, `injectMetaTags`, `escapeHtml` |
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install @comify.art/thuli-link firebase-admin firebase-functions
20
+ ```
21
+
22
+ If using `@comify.art/thuli-link/mail`, also install `nodemailer`:
23
+
24
+ ```bash
25
+ npm install nodemailer
26
+ ```
27
+
28
+ ## Quick Start
29
+
30
+ ```ts
31
+ import { initializeApp } from 'firebase-admin/app';
32
+ import { getFirestore } from 'firebase-admin/firestore';
33
+ import { createFormHandler } from '@comify.art/thuli-link/forms';
34
+ import { createQueuedMailHandler } from '@comify.art/thuli-link/mail';
35
+ import { createDynamicMetaRenderer } from '@comify.art/thuli-link/meta';
36
+ import { isLikelyGibberishText, isValidEmail } from '@comify.art/thuli-link/contracts';
37
+
38
+ initializeApp();
39
+
40
+ export const sendQueuedMail = createQueuedMailHandler({
41
+ region: 'us-west1',
42
+ defaultFrom: 'Example App <noreply@example.com>',
43
+ });
44
+
45
+ export const submitContact = createFormHandler({
46
+ scope: 'contact',
47
+ cors: ['https://example.com'],
48
+ onSubmit: async (body) => {
49
+ const email = String(body.email ?? '').trim();
50
+ const message = String(body.message ?? '').trim();
51
+ if (!isValidEmail(email)) {
52
+ return { status: 400, payload: { ok: false, error: 'Invalid email.' } };
53
+ }
54
+ if (isLikelyGibberishText(message)) {
55
+ return { status: 400, payload: { ok: false, error: 'Message too short.' } };
56
+ }
57
+ await getFirestore().collection('mail').add({
58
+ to: ['team@example.com'],
59
+ replyTo: email,
60
+ message: { subject: 'Contact Inquiry', text: message },
61
+ });
62
+ },
63
+ });
64
+
65
+ export const renderMeta = createDynamicMetaRenderer({
66
+ defaultOrigin: 'https://example.com',
67
+ defaultTitle: 'Example App',
68
+ defaultDescription: 'Example description',
69
+ });
70
+ ```
71
+
72
+ ## Firestore Rules Template
73
+
74
+ See [rules/firestore.rules.template](./rules/firestore.rules.template) for a baseline ruleset locking `mail` and `rate_limits` to Admin SDK access only.
@@ -0,0 +1,25 @@
1
+ export declare const CONTRACT_VERSION: 1;
2
+ export interface FormGuardPayload {
3
+ website?: string;
4
+ startedAt?: number;
5
+ }
6
+ export interface FormSubmissionResponse {
7
+ ok: boolean;
8
+ error?: string;
9
+ }
10
+ export interface SpamGuardConfig {
11
+ minElapsedMs: number;
12
+ minMessageLength: number;
13
+ minWordCount: number;
14
+ maxGmailDots: number;
15
+ }
16
+ export declare const DEFAULT_SPAM_GUARD_CONFIG: SpamGuardConfig;
17
+ /**
18
+ * Validates email format and rejects heavily dot-stuffed Gmail addresses.
19
+ */
20
+ export declare function isValidEmail(email: string, config?: Pick<SpamGuardConfig, 'maxGmailDots'>): boolean;
21
+ /**
22
+ * Detects empty, single-token, or mixed-case random gibberish text.
23
+ */
24
+ export declare function isLikelyGibberishText(text: string, config?: Pick<SpamGuardConfig, 'minMessageLength' | 'minWordCount'>): boolean;
25
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/contracts/index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,gBAAgB,EAAG,CAAU,CAAC;AAE3C,MAAM,WAAW,gBAAgB;IAC7B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,sBAAsB;IACnC,EAAE,EAAE,OAAO,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,eAAe;IAC5B,YAAY,EAAE,MAAM,CAAC;IACrB,gBAAgB,EAAE,MAAM,CAAC;IACzB,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;CACxB;AAED,eAAO,MAAM,yBAAyB,EAAE,eAKvC,CAAC;AAEF;;GAEG;AACH,wBAAgB,YAAY,CACxB,KAAK,EAAE,MAAM,EACb,MAAM,GAAE,IAAI,CAAC,eAAe,EAAE,cAAc,CAA6B,GAC1E,OAAO,CAWT;AAiBD;;GAEG;AACH,wBAAgB,qBAAqB,CACjC,IAAI,EAAE,MAAM,EACZ,MAAM,GAAE,IAAI,CAAC,eAAe,EAAE,kBAAkB,GAAG,cAAc,CAA6B,GAC/F,OAAO,CAiBT"}
@@ -0,0 +1,62 @@
1
+ export const CONTRACT_VERSION = 1;
2
+ export const DEFAULT_SPAM_GUARD_CONFIG = {
3
+ minElapsedMs: 1500,
4
+ minMessageLength: 10,
5
+ minWordCount: 2,
6
+ maxGmailDots: 5,
7
+ };
8
+ /**
9
+ * Validates email format and rejects heavily dot-stuffed Gmail addresses.
10
+ */
11
+ export function isValidEmail(email, config = DEFAULT_SPAM_GUARD_CONFIG) {
12
+ const trimmed = email.trim();
13
+ if (trimmed.length < 3 || trimmed.length > 200)
14
+ return false;
15
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(trimmed))
16
+ return false;
17
+ const [localPart, domain] = trimmed.toLowerCase().split('@');
18
+ if ((domain === 'gmail.com' || domain === 'googlemail.com') && localPart) {
19
+ const dotCount = (localPart.match(/\./g) || []).length;
20
+ if (dotCount >= config.maxGmailDots)
21
+ return false;
22
+ }
23
+ return true;
24
+ }
25
+ function countCaseTransitions(token) {
26
+ let transitions = 0;
27
+ let prevUpper = null;
28
+ for (const ch of token) {
29
+ if (ch >= 'a' && ch <= 'z') {
30
+ if (prevUpper === true)
31
+ transitions += 1;
32
+ prevUpper = false;
33
+ }
34
+ else if (ch >= 'A' && ch <= 'Z') {
35
+ if (prevUpper === false)
36
+ transitions += 1;
37
+ prevUpper = true;
38
+ }
39
+ }
40
+ return transitions;
41
+ }
42
+ /**
43
+ * Detects empty, single-token, or mixed-case random gibberish text.
44
+ */
45
+ export function isLikelyGibberishText(text, config = DEFAULT_SPAM_GUARD_CONFIG) {
46
+ const trimmed = text.trim();
47
+ if (trimmed.length < config.minMessageLength)
48
+ return true;
49
+ const words = trimmed.split(/\s+/).filter(Boolean);
50
+ if (words.length < config.minWordCount)
51
+ return true;
52
+ for (const word of words) {
53
+ if (word.length >= 16 &&
54
+ !word.startsWith('http://') &&
55
+ !word.startsWith('https://') &&
56
+ countCaseTransitions(word) >= 5) {
57
+ return true;
58
+ }
59
+ }
60
+ return false;
61
+ }
62
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/contracts/index.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAU,CAAC;AAmB3C,MAAM,CAAC,MAAM,yBAAyB,GAAoB;IACtD,YAAY,EAAE,IAAI;IAClB,gBAAgB,EAAE,EAAE;IACpB,YAAY,EAAE,CAAC;IACf,YAAY,EAAE,CAAC;CAClB,CAAC;AAEF;;GAEG;AACH,MAAM,UAAU,YAAY,CACxB,KAAa,EACb,SAAgD,yBAAyB;IAEzE,MAAM,OAAO,GAAG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SAAqE,yBAAyB;IAE9F,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;IAC5B,IAAI,OAAO,CAAC,MAAM,GAAG,MAAM,CAAC,gBAAgB;QAAE,OAAO,IAAI,CAAC;IAC1D,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IACnD,IAAI,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,YAAY;QAAE,OAAO,IAAI,CAAC;IAEpD,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACvB,IACI,IAAI,CAAC,MAAM,IAAI,EAAE;YACjB,CAAC,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC;YAC3B,CAAC,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC;YAC5B,oBAAoB,CAAC,IAAI,CAAC,IAAI,CAAC,EACjC,CAAC;YACC,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;IACD,OAAO,KAAK,CAAC;AACjB,CAAC"}
@@ -0,0 +1,46 @@
1
+ import type { Request } from 'firebase-functions/v2/https';
2
+ import { type SpamGuardConfig } from '../contracts/index.js';
3
+ export interface RateLimitOptions {
4
+ collection?: string;
5
+ windowMs?: number;
6
+ maxRequests?: number;
7
+ salt?: string;
8
+ ttlMs?: number;
9
+ }
10
+ export interface FormHandlerOptions {
11
+ region?: string;
12
+ cors?: boolean | string | RegExp | Array<string | RegExp>;
13
+ scope: string;
14
+ honeypotField?: string;
15
+ maxBodyBytes?: number;
16
+ spamGuard?: Partial<SpamGuardConfig>;
17
+ rateLimit?: RateLimitOptions;
18
+ onSubmit: (body: Record<string, unknown>, context: {
19
+ clientIpHash: string;
20
+ }) => Promise<{
21
+ status?: number;
22
+ payload?: Record<string, unknown>;
23
+ } | void>;
24
+ }
25
+ /**
26
+ * Strips CR and LF characters to prevent email header injection.
27
+ */
28
+ export declare function sanitizeHeaderValue(value: string): string;
29
+ export declare function getClientIp(req: Request): string;
30
+ export declare function hashClientIp(ip: string, salt?: string): string;
31
+ export declare function checkRateLimit(scope: string, ipHash: string, options?: RateLimitOptions): Promise<boolean>;
32
+ export type GuardResult = {
33
+ ok: true;
34
+ body: Record<string, unknown>;
35
+ clientIpHash: string;
36
+ } | {
37
+ ok: false;
38
+ status: number;
39
+ payload: Record<string, unknown>;
40
+ };
41
+ export declare function runSubmissionGuards(req: Request, options: Pick<FormHandlerOptions, 'scope' | 'honeypotField' | 'maxBodyBytes' | 'spamGuard' | 'rateLimit'>): Promise<GuardResult>;
42
+ /**
43
+ * Creates a Firebase HTTPS v2 form handler protected by honeypot, timing, and rate limiting.
44
+ */
45
+ export declare function createFormHandler(options: FormHandlerOptions): import("firebase-functions/v2/https").HttpsFunction;
46
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/forms/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EAA6B,KAAK,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExF,MAAM,WAAW,gBAAgB;IAC7B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,kBAAkB;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC;IAC1D,KAAK,EAAE,MAAM,CAAC;IACd,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,OAAO,CAAC,e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AAE,kBAAkB,uDAwB5D"}
@@ -0,0 +1,141 @@
1
+ import { createHash, createHmac } from 'crypto';
2
+ import { FieldValue, getFirestore, Timestamp } from 'firebase-admin/firestore';
3
+ import * as logger from 'firebase-functions/logger';
4
+ import { onRequest } from 'firebase-functions/v2/https';
5
+ import { DEFAULT_SPAM_GUARD_CONFIG } from '../contracts/index.js';
6
+ const DEFAULT_RATE_LIMIT = {
7
+ collection: 'rate_limits',
8
+ windowMs: 15 * 60 * 1000,
9
+ maxRequests: 5,
10
+ ttlMs: 24 * 60 * 60 * 1000,
11
+ };
12
+ /**
13
+ * Strips CR and LF characters to prevent email header injection.
14
+ */
15
+ export function sanitizeHeaderValue(value) {
16
+ return value.replace(/[\r\n]+/g, ' ').trim();
17
+ }
18
+ export function getClientIp(req) {
19
+ const forwarded = req.headers['x-forwarded-for'];
20
+ if (typeof forwarded === 'string' && forwarded.trim()) {
21
+ return forwarded.split(',')[0].trim();
22
+ }
23
+ if (Array.isArray(forwarded) && forwarded.length > 0) {
24
+ return forwarded[0].trim();
25
+ }
26
+ return req.ip || 'unknown';
27
+ }
28
+ export function hashClientIp(ip, salt) {
29
+ if (salt) {
30
+ return createHmac('sha256', salt).update(ip).digest('hex').slice(0, 24);
31
+ }
32
+ return createHash('sha256').update(ip).digest('hex').slice(0, 24);
33
+ }
34
+ export async function checkRateLimit(scope, ipHash, options = {}) {
35
+ const collection = options.collection ?? DEFAULT_RATE_LIMIT.collection;
36
+ const windowMs = options.windowMs ?? DEFAULT_RATE_LIMIT.windowMs;
37
+ const maxRequests = options.maxRequests ?? DEFAULT_RATE_LIMIT.maxRequests;
38
+ const ttlMs = options.ttlMs ?? DEFAULT_RATE_LIMIT.ttlMs;
39
+ const db = getFirestore();
40
+ const docRef = db.collection(collection).doc(`${scope}_${ipHash}`);
41
+ const now = Date.now();
42
+ const expireAt = Timestamp.fromMillis(now + ttlMs);
43
+ return db.runTransaction(async (tx) => {
44
+ const snap = await tx.get(docRef);
45
+ const data = snap.data();
46
+ if (!data ||
47
+ typeof data.windowStart !== 'number' ||
48
+ now - data.windowStart > windowMs) {
49
+ tx.set(docRef, {
50
+ count: 1,
51
+ windowStart: now,
52
+ expireAt,
53
+ updatedAt: FieldValue.serverTimestamp(),
54
+ });
55
+ return true;
56
+ }
57
+ const nextCount = (data.count ?? 0) + 1;
58
+ if (nextCount > maxRequests) {
59
+ return false;
60
+ }
61
+ tx.update(docRef, {
62
+ count: nextCount,
63
+ expireAt,
64
+ updatedAt: FieldValue.serverTimestamp(),
65
+ });
66
+ return true;
67
+ });
68
+ }
69
+ export async function runSubmissionGuards(req, options) {
70
+ if (req.method !== 'POST') {
71
+ return { ok: false, status: 405, payload: { ok: false, error: 'Method not allowed.' } };
72
+ }
73
+ const maxBodyBytes = options.maxBodyBytes ?? 16 * 1024;
74
+ const contentLength = Number(req.headers['content-length'] ?? 0);
75
+ if (Number.isFinite(contentLength) && contentLength > maxBodyBytes) {
76
+ return { ok: false, status: 413, payload: { ok: false, error: 'Payload too large.' } };
77
+ }
78
+ const body = (typeof req.body === 'object' && req.body !== null ? req.body : {});
79
+ const honeypotField = options.honeypotField ?? 'website';
80
+ const honeypotValue = body[honeypotField];
81
+ if (typeof honeypotValue === 'string' && honeypotValue.trim().length > 0) {
82
+ logger.info('Honeypot triggered', { scope: options.scope });
83
+ return { ok: false, status: 200, payload: { ok: true } };
84
+ }
85
+ const minElapsedMs = options.spamGuard?.minElapsedMs ?? DEFAULT_SPAM_GUARD_CONFIG.minElapsedMs;
86
+ if (typeof body.startedAt === 'number' && Number.isFinite(body.startedAt)) {
87
+ const elapsedMs = Date.now() - body.startedAt;
88
+ if (elapsedMs >= 0 && elapsedMs < minElapsedMs) {
89
+ logger.warn('Submission rejected due to fast submit timing', {
90
+ scope: options.scope,
91
+ elapsedMs,
92
+ });
93
+ return {
94
+ ok: false,
95
+ status: 400,
96
+ payload: {
97
+ ok: false,
98
+ error: 'Please take a moment to review your message before submitting.',
99
+ },
100
+ };
101
+ }
102
+ }
103
+ const clientIpHash = hashClientIp(getClientIp(req), options.rateLimit?.salt);
104
+ const allowed = await checkRateLimit(options.scope, clientIpHash, options.rateLimit);
105
+ if (!allowed) {
106
+ logger.warn('Rate limit exceeded', { scope: options.scope });
107
+ return {
108
+ ok: false,
109
+ status: 429,
110
+ payload: {
111
+ ok: false,
112
+ error: 'Too many submissions. Please wait a few minutes and try again.',
113
+ },
114
+ };
115
+ }
116
+ return { ok: true, body, clientIpHash };
117
+ }
118
+ /**
119
+ * Creates a Firebase HTTPS v2 form handler protected by honeypot, timing, and rate limiting.
120
+ */
121
+ export function createFormHandler(options) {
122
+ return onRequest({
123
+ region: options.region ?? 'us-west1',
124
+ cors: options.cors ?? false,
125
+ }, async (req, res) => {
126
+ const guard = await runSubmissionGuards(req, options);
127
+ if (!guard.ok) {
128
+ res.status(guard.status).json(guard.payload);
129
+ return;
130
+ }
131
+ const result = await options.onSubmit(guard.body, {
132
+ clientIpHash: guard.clientIpHash,
133
+ });
134
+ if (result) {
135
+ res.status(result.status ?? 200).json(result.payload ?? { ok: true });
136
+ return;
137
+ }
138
+ res.status(200).json({ ok: true });
139
+ });
140
+ }
141
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/forms/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC/E,OAAO,KAAK,MAAM,MAAM,2BAA2B,CAAC;AACpD,OAAO,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AAExD,OAAO,EAAE,yBAAyB,EAAwB,MAAM,uBAAuB,CAAC;AAwBxF,MAAM,kBAAkB,GAA6C;IACjE,UAAU,EAAE,aAAa;IACzB,QAAQ,EAAE,EAAE,GAAG,EAAE,GAAG,IAAI;IACxB,WAAW,EAAE,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,CACJ,CAAC;AACN,CAAC"}
@@ -0,0 +1,5 @@
1
+ export * from './contracts/index.js';
2
+ export * from './forms/index.js';
3
+ export * from './mail/index.js';
4
+ export * from './meta/index.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC;AACrC,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,iBAAiB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export * from './contracts/index.js';
2
+ export * from './forms/index.js';
3
+ export * from './mail/index.js';
4
+ export * from './meta/index.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC;AACrC,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,iBAAiB,CAAC"}
@@ -0,0 +1,27 @@
1
+ export interface MailMessage {
2
+ subject?: string;
3
+ text?: string;
4
+ html?: string;
5
+ }
6
+ export interface MailDocument {
7
+ to?: string[];
8
+ replyTo?: string;
9
+ message?: MailMessage;
10
+ delivery?: {
11
+ state?: string;
12
+ };
13
+ }
14
+ export interface QueuedMailHandlerOptions {
15
+ collection?: string;
16
+ region?: string;
17
+ smtpSecretName?: string;
18
+ mailFromParamName?: string;
19
+ defaultFrom?: string;
20
+ }
21
+ /**
22
+ * Creates a Firestore `onDocumentCreated` worker that sends queued mail via SMTP.
23
+ */
24
+ export declare function createQueuedMailHandler(options?: QueuedMailHandlerOptions): import("firebase-functions/core").CloudFunction<import("firebase-functions/v2/firestore").FirestoreEvent<import("firebase-functions/v2/firestore").QueryDocumentSnapshot | undefined, {
25
+ mailId: string;
26
+ }>>;
27
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/mail/index.ts"],"names":[],"mappings":"AAOA,MAAM,WAAW,WAAW;IACxB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,YAAY;IACzB,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,QAAQ,CAAC,EAAE;QACP,KAAK,CAAC,EAAE,MAAM,CAAC;KAClB,CAAC;CACL;AAED,MAAM,WAAW,wBAAwB;IACrC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,WAAW,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,GAAE,wBAA6B;;IA6F7E"}
@@ -0,0 +1,96 @@
1
+ import { FieldValue } from 'firebase-admin/firestore';
2
+ import * as logger from 'firebase-functions/logger';
3
+ import { defineSecret, defineString } from 'firebase-functions/params';
4
+ import { onDocumentCreated } from 'firebase-functions/v2/firestore';
5
+ import * as nodemailer from 'nodemailer';
6
+ import { sanitizeHeaderValue } from '../forms/index.js';
7
+ /**
8
+ * Creates a Firestore `onDocumentCreated` worker that sends queued mail via SMTP.
9
+ */
10
+ export function createQueuedMailHandler(options = {}) {
11
+ const collection = options.collection ?? 'mail';
12
+ const region = options.region ?? 'us-west1';
13
+ const smtpUri = defineSecret(options.smtpSecretName ?? 'SMTP_URI');
14
+ const mailFrom = defineString(options.mailFromParamName ?? 'MAIL_FROM', {
15
+ default: options.defaultFrom ?? 'No Reply <noreply@example.com>',
16
+ });
17
+ return onDocumentCreated({
18
+ document: `${collection}/{mailId}`,
19
+ region,
20
+ secrets: [smtpUri],
21
+ }, async (event) => {
22
+ const snapshot = event.data;
23
+ if (!snapshot)
24
+ return;
25
+ const data = snapshot.data();
26
+ if (data.delivery?.state === 'SUCCESS') {
27
+ return;
28
+ }
29
+ const toList = Array.isArray(data.to)
30
+ ? data.to.map((addr) => sanitizeHeaderValue(String(addr))).filter(Boolean)
31
+ : [];
32
+ const subject = data.message?.subject
33
+ ? sanitizeHeaderValue(data.message.subject)
34
+ : '';
35
+ const text = data.message?.text;
36
+ const html = data.message?.html;
37
+ if (toList.length === 0 || !subject || (!text && !html)) {
38
+ logger.warn('Skipping malformed mail document', {
39
+ mailId: event.params.mailId,
40
+ });
41
+ await snapshot.ref.update({
42
+ delivery: {
43
+ state: 'ERROR',
44
+ error: 'Missing required fields: to, message.subject, and message.text or message.html.',
45
+ endTime: FieldValue.serverTimestamp(),
46
+ },
47
+ });
48
+ return;
49
+ }
50
+ const uri = smtpUri.value().trim();
51
+ if (!uri) {
52
+ logger.error('SMTP_URI secret is empty');
53
+ return;
54
+ }
55
+ try {
56
+ if (!uri.startsWith('smtp://') && !uri.startsWith('smtps://')) {
57
+ throw new Error('SMTP_URI must start with smtps:// or smtp://');
58
+ }
59
+ const transporter = nodemailer.createTransport(uri);
60
+ const info = await transporter.sendMail({
61
+ from: mailFrom.value(),
62
+ to: toList.join(', '),
63
+ replyTo: data.replyTo ? sanitizeHeaderValue(data.replyTo) : undefined,
64
+ subject,
65
+ text,
66
+ html,
67
+ });
68
+ await snapshot.ref.update({
69
+ delivery: {
70
+ state: 'SUCCESS',
71
+ messageId: info.messageId,
72
+ endTime: FieldValue.serverTimestamp(),
73
+ },
74
+ });
75
+ logger.info('Sent queued email', {
76
+ mailId: event.params.mailId,
77
+ messageId: info.messageId,
78
+ });
79
+ }
80
+ catch (err) {
81
+ const message = err instanceof Error ? err.message : String(err);
82
+ logger.error('Failed to send queued email', {
83
+ mailId: event.params.mailId,
84
+ error: message,
85
+ });
86
+ await snapshot.ref.update({
87
+ delivery: {
88
+ state: 'ERROR',
89
+ error: message,
90
+ endTime: FieldValue.serverTimestamp(),
91
+ },
92
+ });
93
+ }
94
+ });
95
+ }
96
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/mail/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AACtD,OAAO,KAAK,MAAM,MAAM,2BAA2B,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,KAAK,UAAU,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAyBxD;;GAEG;AACH,MAAM,UAAU,uBAAuB,CAAC,UAAoC,EAAE;IAC1E,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,IAAI,MAAM,CAAC;IAChD,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,UAAU,CAAC;IAC5C,MAAM,OAAO,GAAG,YAAY,CAAC,OAAO,CAAC,cAAc,IAAI,UAAU,CAAC,CAAC;IACnE,MAAM,QAAQ,GAAG,YAAY,CAAC,OAAO,CAAC,iBAAiB,IAAI,WAAW,EAAE;QACpE,OAAO,EAAE,OAAO,CAAC,WAAW,IAAI,gCAAgC;KACnE,CAAC,CAAC;IAEH,OAAO,iBAAiB,CACpB;QACI,QAAQ,EAAE,GAAG,UAAU,WAAW;QAClC,MAAM;QACN,OAAO,EAAE,CAAC,OAAO,CAAC;KACrB,EACD,KAAK,EAAE,KAAK,EAAE,EAAE;QACZ,MAAM,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC;QAC5B,IAAI,CAAC,QAAQ;YAAE,OAAO;QAEtB,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,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AM;gBAC3B,KAAK,EAAE,OAAO;aACjB,CAAC,CAAC;YACH,MAAM,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC;gBACtB,QAAQ,EAAE;oBACN,KAAK,EAAE,OAAO;oBACd,KAAK,EAAE,OAAO;oBACd,OAAO,EAAE,UAAU,CAAC,eAAe,EAAE;iBACxC;aACJ,CAAC,CAAC;QACP,CAAC;IACL,CAAC,CACJ,CAAC;AACN,CAAC"}
@@ -0,0 +1,31 @@
1
+ export interface RouteMeta {
2
+ title: string;
3
+ description: string;
4
+ url: string;
5
+ imageUrl: string;
6
+ ogType: 'website' | 'article';
7
+ }
8
+ export interface StaticRouteMetaConfig {
9
+ title: string;
10
+ description: string;
11
+ imagePath: string;
12
+ }
13
+ export interface DynamicMetaRendererOptions {
14
+ region?: string;
15
+ defaultOrigin: string;
16
+ allowedHosts?: string[];
17
+ defaultTitle: string;
18
+ defaultDescription: string;
19
+ defaultImagePath?: string;
20
+ blogCollection?: string;
21
+ mediaCollection?: string;
22
+ staticRoutes?: Record<string, StaticRouteMetaConfig>;
23
+ cacheControl?: string;
24
+ }
25
+ export declare function escapeHtml(value: string): string;
26
+ export declare function injectMetaTags(html: string, meta: RouteMeta): string;
27
+ /**
28
+ * Creates a Firebase HTTPS v2 handler that injects OG/Twitter metadata for SPA routes.
29
+ */
30
+ export declare function createDynamicMetaRenderer(options: DynamicMetaRendererOptions): import("firebase-functions/v2/https").HttpsFunction;
31
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/meta/index.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,SAAS;IACtB,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,SAAS,GAAG,SAAS,CAAC;CACjC;AAED,MAAM,WAAW,qBAAqB;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,0BAA0B;IACvC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,aAAa,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,YAAY,EAAE,MAAM,CAAC;IACrB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,qBAAqB,CAAC,CAAC;IACrD,YAAY,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAOhD;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,GAAG,MAAM,CAgCpE;AAED;;GAEG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,0BAA0B,uDA0H5E"}
@@ -0,0 +1,143 @@
1
+ import { getFirestore } from 'firebase-admin/firestore';
2
+ import * as logger from 'firebase-functions/logger';
3
+ import { onRequest } from 'firebase-functions/v2/https';
4
+ export function escapeHtml(value) {
5
+ return value
6
+ .replace(/&/g, '&amp;')
7
+ .replace(/</g, '&lt;')
8
+ .replace(/>/g, '&gt;')
9
+ .replace(/"/g, '&quot;')
10
+ .replace(/'/g, '&#39;');
11
+ }
12
+ export function injectMetaTags(html, meta) {
13
+ const safeTitle = escapeHtml(meta.title);
14
+ const safeDesc = escapeHtml(meta.description);
15
+ const safeUrl = escapeHtml(meta.url);
16
+ const safeImg = escapeHtml(meta.imageUrl);
17
+ const tags = [
18
+ `<title>${safeTitle}</title>`,
19
+ `<meta name="description" content="${safeDesc}" />`,
20
+ `<meta property="og:type" content="${meta.ogType}" />`,
21
+ `<meta property="og:title" content="${safeTitle}" />`,
22
+ `<meta property="og:description" content="${safeDesc}" />`,
23
+ `<meta property="og:url" content="${safeUrl}" />`,
24
+ `<meta property="og:image" content="${safeImg}" />`,
25
+ `<meta name="twitter:card" content="summary" />`,
26
+ `<meta name="twitter:title" content="${safeTitle}" />`,
27
+ `<meta name="twitter:description" content="${safeDesc}" />`,
28
+ `<meta name="twitter:image" content="${safeImg}" />`,
29
+ ].join('\n ');
30
+ let updated = html
31
+ .replace(/<title>[\s\S]*?<\/title>/gi, '')
32
+ .replace(/<meta[^>]+name=["']description["'][^>]*>/gi, '')
33
+ .replace(/<meta[^>]+property=["']og:[^"']+["'][^>]*>/gi, '')
34
+ .replace(/<meta[^>]+name=["']twitter:[^"']+["'][^>]*>/gi, '');
35
+ if (updated.includes('</head>')) {
36
+ updated = updated.replace('</head>', ` ${tags}\n </head>`);
37
+ }
38
+ else {
39
+ updated = `${tags}\n${updated}`;
40
+ }
41
+ return updated;
42
+ }
43
+ /**
44
+ * Creates a Firebase HTTPS v2 handler that injects OG/Twitter metadata for SPA routes.
45
+ */
46
+ export function createDynamicMetaRenderer(options) {
47
+ const blogCollection = options.blogCollection ?? 'blog_posts';
48
+ const mediaCollection = options.mediaCollection ?? 'media_items';
49
+ const defaultImagePath = options.defaultImagePath ?? '/assets/og-default.png';
50
+ const allowedHosts = new Set(options.allowedHosts ?? [new URL(options.defaultOrigin).host]);
51
+ return onRequest({
52
+ region: options.region ?? 'us-west1',
53
+ }, async (req, res) => {
54
+ const rawHost = (req.headers['x-forwarded-host'] || req.headers.host || '')
55
+ .toString()
56
+ .split(',')[0]
57
+ .trim();
58
+ const origin = rawHost && allowedHosts.has(rawHost)
59
+ ? `https://${rawHost}`
60
+ : options.defaultOrigin;
61
+ const normalizedPath = req.path.replace(/\/+$/, '') || '/';
62
+ try {
63
+ const indexRes = await fetch(`${origin}/index.html`);
64
+ if (!indexRes.ok) {
65
+ throw new Error(`Failed to fetch index.html: ${indexRes.status}`);
66
+ }
67
+ let html = await indexRes.text();
68
+ const staticMeta = options.staticRoutes?.[normalizedPath];
69
+ if (staticMeta) {
70
+ html = injectMetaTags(html, {
71
+ title: staticMeta.title,
72
+ description: staticMeta.description,
73
+ url: `${origin}${normalizedPath}`,
74
+ imageUrl: `${origin}${staticMeta.imagePath}`,
75
+ ogType: 'website',
76
+ });
77
+ }
78
+ else if (normalizedPath === '/blog') {
79
+ html = injectMetaTags(html, {
80
+ title: options.defaultTitle,
81
+ description: options.defaultDescription,
82
+ url: `${origin}/blog`,
83
+ imageUrl: `${origin}${defaultImagePath}`,
84
+ ogType: 'website',
85
+ });
86
+ }
87
+ else if (normalizedPath.startsWith('/blog/')) {
88
+ const slug = decodeURIComponent(normalizedPath.slice('/blog/'.length)).trim();
89
+ if (slug) {
90
+ const db = getFirestore();
91
+ const snap = await db
92
+ .collection(blogCollection)
93
+ .where('slug', '==', slug)
94
+ .limit(1)
95
+ .get();
96
+ if (!snap.empty) {
97
+ const post = snap.docs[0].data();
98
+ if (post.status === 'published') {
99
+ const title = post.title || options.defaultTitle;
100
+ const description = post.description?.trim() || options.defaultDescription;
101
+ const pageUrl = `${origin}/blog/${encodeURIComponent(slug)}`;
102
+ let imageUrl = post.coverImageUrl &&
103
+ post.coverImageUrl.startsWith('http')
104
+ ? post.coverImageUrl
105
+ : '';
106
+ if (!imageUrl && post.coverImageId) {
107
+ const mediaSnap = await db
108
+ .collection(mediaCollection)
109
+ .doc(post.coverImageId)
110
+ .get();
111
+ const mediaUrl = mediaSnap.data()?.url;
112
+ if (typeof mediaUrl === 'string' &&
113
+ mediaUrl.startsWith('http')) {
114
+ imageUrl = mediaUrl;
115
+ }
116
+ }
117
+ if (!imageUrl) {
118
+ imageUrl = `${origin}${defaultImagePath}`;
119
+ }
120
+ html = injectMetaTags(html, {
121
+ title,
122
+ description,
123
+ url: pageUrl,
124
+ imageUrl,
125
+ ogType: 'article',
126
+ });
127
+ }
128
+ }
129
+ }
130
+ }
131
+ res.set('Cache-Control', options.cacheControl ?? 'public, max-age=300, s-maxage=600');
132
+ res.status(200).type('text/html').send(html);
133
+ }
134
+ catch (err) {
135
+ logger.error('Failed to render dynamic page meta', {
136
+ path: normalizedPath,
137
+ error: err instanceof Error ? err.message : String(err),
138
+ });
139
+ res.redirect(302, '/');
140
+ }
141
+ });
142
+ }
143
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/meta/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,KAAK,MAAM,MAAM,2BAA2B,CAAC;AACpD,OAAO,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AA6BxD,MAAM,UAAU,UAAU,CAAC,KAAa;IACpC,OAAO,KAAK;SACP,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC;SACtB,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC;SACvB,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AAChC,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,IAAY,EAAE,IAAe;IACxD,MAAM,SAAS,GAAG,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACzC,MAAM,QAAQ,GAAG,UAAU,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IAC9C,MAAM,OAAO,GAAG,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACrC,MAAM,OAAO,GAAG,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAE1C,MAAM,IAAI,GAAG;QACT,UAAU,SAAS,UAAU;QAC7B,qCAAqC,QAAQ,MAAM;QACnD,qCAAqC,IAAI,CAAC,MAAM,MAAM;QACtD,sCAAsC,SAAS,MAAM;QACrD,4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,CAAC;QAC3B,CAAC;IACL,CAAC,CACJ,CAAC;AACN,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,77 @@
1
1
  {
2
2
  "name": "@comify.art/thuli-link",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Reusable Firebase Cloud Functions v2, Admin SDK, form anti-spam, mail queue, and dynamic OG metadata utilities for @comify.art/thuli apps",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/comify-art/thuli-link.git"
9
+ },
10
+ "homepage": "https://github.com/comify-art/thuli-link#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/comify-art/thuli-link/issues"
13
+ },
14
+ "type": "module",
15
+ "engines": {
16
+ "node": ">=22.0.0"
17
+ },
18
+ "sideEffects": false,
19
+ "main": "./dist/index.js",
20
+ "module": "./dist/index.js",
21
+ "types": "./dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "import": "./dist/index.js"
26
+ },
27
+ "./contracts": {
28
+ "types": "./dist/contracts/index.d.ts",
29
+ "import": "./dist/contracts/index.js"
30
+ },
31
+ "./forms": {
32
+ "types": "./dist/forms/index.d.ts",
33
+ "import": "./dist/forms/index.js"
34
+ },
35
+ "./mail": {
36
+ "types": "./dist/mail/index.d.ts",
37
+ "import": "./dist/mail/index.js"
38
+ },
39
+ "./meta": {
40
+ "types": "./dist/meta/index.d.ts",
41
+ "import": "./dist/meta/index.js"
42
+ }
43
+ },
44
+ "files": [
45
+ "dist",
46
+ "rules",
47
+ "README.md",
48
+ "LICENSE"
49
+ ],
50
+ "scripts": {
51
+ "clean": "rm -rf dist",
52
+ "type-check": "tsc --noEmit",
53
+ "test": "vitest run",
54
+ "test:watch": "vitest",
55
+ "build": "npm run clean && tsc",
56
+ "package": "npm run build && npm pack --pack-destination dist"
57
+ },
58
+ "peerDependencies": {
59
+ "firebase-admin": ">=12.0.0",
60
+ "firebase-functions": ">=5.0.0",
61
+ "nodemailer": ">=6.9.0"
62
+ },
63
+ "peerDependenciesMeta": {
64
+ "nodemailer": {
65
+ "optional": true
66
+ }
67
+ },
68
+ "devDependencies": {
69
+ "@types/node": "^22.0.0",
70
+ "@types/nodemailer": "^6.4.17",
71
+ "firebase-admin": "^13.0.0",
72
+ "firebase-functions": "^6.0.0",
73
+ "nodemailer": "^6.9.16",
74
+ "typescript": "^5.7.0",
75
+ "vitest": "^3.0.0"
76
+ }
77
+ }
@@ -0,0 +1,41 @@
1
+ rules_version = '2';
2
+ service cloud.firestore {
3
+ match /databases/{database}/documents {
4
+
5
+ // Configure admin access using Firebase Auth Custom Claims,
6
+ // or replace with your project's admin check in your private app repo.
7
+ function isAdmin() {
8
+ return request.auth != null && request.auth.token.admin == true;
9
+ }
10
+
11
+ // Public read for published blog posts; admin-only write
12
+ match /blog_posts/{postId} {
13
+ allow read: if resource.data.status == 'published' || isAdmin();
14
+ allow write: if isAdmin();
15
+ }
16
+
17
+ match /blog_contents/{contentId} {
18
+ allow read: if true;
19
+ allow write: if isAdmin();
20
+ }
21
+
22
+ match /media_items/{mediaId} {
23
+ allow read: if true;
24
+ allow write: if isAdmin();
25
+ }
26
+
27
+ // Server-only outbound mail queue (written via Admin SDK in Cloud Functions)
28
+ match /mail/{mailId} {
29
+ allow read, write: if false;
30
+ }
31
+
32
+ // Server-only rate-limiting counters (written via Admin SDK in Cloud Functions)
33
+ match /rate_limits/{docId} {
34
+ allow read, write: if false;
35
+ }
36
+
37
+ match /{document=**} {
38
+ allow read, write: if false;
39
+ }
40
+ }
41
+ }