@hogsend/engine 0.28.0 → 0.30.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/package.json +7 -7
- package/src/app.ts +17 -3
- package/src/cold-connect/index.ts +243 -0
- package/src/cold-connect/page.ts +164 -0
- package/src/cold-connect/throttle.ts +75 -0
- package/src/cold-connect/token.ts +130 -0
- package/src/index.ts +14 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hogsend/engine",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.30.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -40,14 +40,14 @@
|
|
|
40
40
|
"svix": "^1.95.1",
|
|
41
41
|
"winston": "^3.19.0",
|
|
42
42
|
"zod": "^4.4.3",
|
|
43
|
-
"@hogsend/core": "^0.
|
|
44
|
-
"@hogsend/db": "^0.
|
|
45
|
-
"@hogsend/email": "^0.
|
|
46
|
-
"@hogsend/plugin-posthog": "^0.
|
|
47
|
-
"@hogsend/plugin-resend": "^0.
|
|
43
|
+
"@hogsend/core": "^0.30.0",
|
|
44
|
+
"@hogsend/db": "^0.30.0",
|
|
45
|
+
"@hogsend/email": "^0.30.0",
|
|
46
|
+
"@hogsend/plugin-posthog": "^0.30.0",
|
|
47
|
+
"@hogsend/plugin-resend": "^0.30.0"
|
|
48
48
|
},
|
|
49
49
|
"optionalDependencies": {
|
|
50
|
-
"@hogsend/plugin-postmark": "^0.
|
|
50
|
+
"@hogsend/plugin-postmark": "^0.30.0"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"@types/node": "^22.15.3",
|
package/src/app.ts
CHANGED
|
@@ -33,9 +33,17 @@ export type AppEnv = {
|
|
|
33
33
|
};
|
|
34
34
|
};
|
|
35
35
|
|
|
36
|
+
/** A function that mounts custom routers onto the app after the built-in routes. */
|
|
37
|
+
export type RoutesFn = (app: OpenAPIHono<AppEnv>) => void;
|
|
38
|
+
|
|
36
39
|
export interface CreateAppOptions {
|
|
37
|
-
/**
|
|
38
|
-
|
|
40
|
+
/**
|
|
41
|
+
* Mount custom routers after the built-in routes. Accepts a single function or
|
|
42
|
+
* an array — each is applied in order, so a consumer can compose its own
|
|
43
|
+
* routes with e.g. `cc.routes` without clobbering: `routes: [existing,
|
|
44
|
+
* cc.routes]`.
|
|
45
|
+
*/
|
|
46
|
+
routes?: RoutesFn | RoutesFn[];
|
|
39
47
|
/** Extra middleware applied after the built-in stack. */
|
|
40
48
|
middleware?: MiddlewareHandler[];
|
|
41
49
|
/** Webhook sources served at `/v1/webhooks/:sourceId`. */
|
|
@@ -161,7 +169,13 @@ export function createApp(
|
|
|
161
169
|
);
|
|
162
170
|
}
|
|
163
171
|
|
|
164
|
-
opts.routes
|
|
172
|
+
for (const routeFn of Array.isArray(opts.routes)
|
|
173
|
+
? opts.routes
|
|
174
|
+
: opts.routes
|
|
175
|
+
? [opts.routes]
|
|
176
|
+
: []) {
|
|
177
|
+
routeFn(app);
|
|
178
|
+
}
|
|
165
179
|
|
|
166
180
|
if (container.env.NODE_ENV !== "production") {
|
|
167
181
|
app.doc("/openapi.json", {
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import type { OpenAPIHono } from "@hono/zod-openapi";
|
|
2
|
+
import type { AppEnv } from "../app.js";
|
|
3
|
+
import type { HogsendClient } from "../container.js";
|
|
4
|
+
import { ingestEvent } from "../lib/ingestion.js";
|
|
5
|
+
import { type ColdConnectBranding, coldConnectPageHtml } from "./page.js";
|
|
6
|
+
import {
|
|
7
|
+
type ColdConnectThrottleConfig,
|
|
8
|
+
checkColdConnectThrottle,
|
|
9
|
+
} from "./throttle.js";
|
|
10
|
+
import {
|
|
11
|
+
buildColdConnectUrl,
|
|
12
|
+
type ColdConnectBinding,
|
|
13
|
+
consumeColdConnectToken,
|
|
14
|
+
mintColdConnectToken,
|
|
15
|
+
peekColdConnectToken,
|
|
16
|
+
} from "./token.js";
|
|
17
|
+
|
|
18
|
+
export type { ColdConnectBranding } from "./page.js";
|
|
19
|
+
export type { ColdConnectThrottleConfig } from "./throttle.js";
|
|
20
|
+
export type { ColdConnectBinding } from "./token.js";
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The identity column an `identityKind` resolves a contact on. `userId` and
|
|
24
|
+
* `anonymousId` ride the `external_id`/`anonymous_id` columns under a
|
|
25
|
+
* caller-chosen `platformKey` prefix (e.g. `telegram:`) — there is NO engine-side
|
|
26
|
+
* collision guard there (unlike `discordId`'s dedicated column), so the
|
|
27
|
+
* `platformKey` prefix IS the namespace. `discordId` resolves the dedicated
|
|
28
|
+
* Discord column.
|
|
29
|
+
*/
|
|
30
|
+
export type ColdConnectIdentityKind = "userId" | "discordId" | "anonymousId";
|
|
31
|
+
|
|
32
|
+
/** Config for {@link createColdConnect}. */
|
|
33
|
+
export interface ColdConnectConfig<S = Record<string, unknown>> {
|
|
34
|
+
/** Stable connector id — seals the token, names the basePath, scopes throttle. */
|
|
35
|
+
connectorId: string;
|
|
36
|
+
/** Which `ingestEvent` identity column the platform key resolves on. */
|
|
37
|
+
identityKind: ColdConnectIdentityKind;
|
|
38
|
+
/** Map a raw platform user id to the namespaced ingest key (e.g. `telegram:<id>`). */
|
|
39
|
+
platformKey: (platformUserId: string) => string;
|
|
40
|
+
/** Event name pushed by the exchange's ingest — what the welcome journey `onEvents` on. */
|
|
41
|
+
linkedEvent: string;
|
|
42
|
+
/** The person-property key the connect page sets in `posthog.identify`. */
|
|
43
|
+
identifyPropKey: string;
|
|
44
|
+
/**
|
|
45
|
+
* Build the ingest payload from the sealed binding. CORRECTION (locked): any
|
|
46
|
+
* property the linked/welcome journey BRANCHES on (`user.properties.<id>`)
|
|
47
|
+
* MUST be a scalar `eventProperties` entry — `contactProperties` never reach
|
|
48
|
+
* the Hatchet payload.
|
|
49
|
+
*/
|
|
50
|
+
buildIngest: (binding: ColdConnectBinding<S>) => {
|
|
51
|
+
eventProperties: Record<string, unknown>;
|
|
52
|
+
contactProperties?: Record<string, unknown>;
|
|
53
|
+
};
|
|
54
|
+
/** Connect-page branding (plain-text fields; accentColor regex-validated). */
|
|
55
|
+
branding: ColdConnectBranding;
|
|
56
|
+
/** Confirm-token TTL (seconds). Default 900. */
|
|
57
|
+
ttlSeconds?: number;
|
|
58
|
+
/** Mint-throttle config (Redis-INCR, fail-closed). */
|
|
59
|
+
throttle?: ColdConnectThrottleConfig;
|
|
60
|
+
/**
|
|
61
|
+
* Optional consumer hook run AFTER the bind commits, BEFORE the token is
|
|
62
|
+
* consumed (e.g. Discord `grantVerifiedRole`). AT-LEAST-ONCE: must be
|
|
63
|
+
* idempotent. The token is consumed even if this throws — the bind already
|
|
64
|
+
* committed, so a flaky hook must not keep the token live and re-fire on every
|
|
65
|
+
* click.
|
|
66
|
+
*/
|
|
67
|
+
afterBind?: (
|
|
68
|
+
binding: ColdConnectBinding<S> & { contactKey: string },
|
|
69
|
+
deps: { container: HogsendClient },
|
|
70
|
+
) => Promise<void>;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export type MintConfirmResult =
|
|
74
|
+
| { ok: true; token: string }
|
|
75
|
+
| { ok: false; reason: string };
|
|
76
|
+
|
|
77
|
+
/** The object returned by {@link createColdConnect}. */
|
|
78
|
+
export interface ColdConnect<S = Record<string, unknown>> {
|
|
79
|
+
/**
|
|
80
|
+
* Mint a confirm token (throttled, fail-closed). Returns `{ ok:false }` when
|
|
81
|
+
* throttled or Redis is unavailable — the caller MUST NOT send a link then.
|
|
82
|
+
*/
|
|
83
|
+
mintConfirm(args: {
|
|
84
|
+
platformUserId: string;
|
|
85
|
+
email: string;
|
|
86
|
+
scalars?: S;
|
|
87
|
+
}): Promise<MintConfirmResult>;
|
|
88
|
+
/** Build the connect URL for a minted token on the given API_PUBLIC_URL. */
|
|
89
|
+
confirmUrl(args: { apiPublicUrl: string; token: string }): string;
|
|
90
|
+
/** Mount `GET /connect/<id>` + `POST /connect/<id>/exchange` on the app. */
|
|
91
|
+
routes(app: OpenAPIHono<AppEnv>): void;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Build a cold-connect flow: chat `/link <email>` → emailed one-click confirm
|
|
96
|
+
* link → click → engine-served connect page → button POST → server-sealed token
|
|
97
|
+
* → `ingestEvent` folds the two contact rows into one + returns the canonical
|
|
98
|
+
* `contactKey` → page runs CLIENT-side `posthog.identify(contactKey)`.
|
|
99
|
+
*
|
|
100
|
+
* Returns `{ mintConfirm, confirmUrl, routes }`. `routes` derives its basePath
|
|
101
|
+
* from `config.connectorId` (never a caller-chosen mount) and the exchange
|
|
102
|
+
* asserts the sealed `binding.connectorId === connectorId` (410 on mismatch),
|
|
103
|
+
* for cross-connector token isolation.
|
|
104
|
+
*/
|
|
105
|
+
export function createColdConnect<S = Record<string, unknown>>(
|
|
106
|
+
config: ColdConnectConfig<S>,
|
|
107
|
+
): ColdConnect<S> {
|
|
108
|
+
const { connectorId } = config;
|
|
109
|
+
const pagePath = `/connect/${connectorId}`;
|
|
110
|
+
const exchangePath = `/connect/${connectorId}/exchange`;
|
|
111
|
+
|
|
112
|
+
return {
|
|
113
|
+
async mintConfirm(args) {
|
|
114
|
+
const throttle = await checkColdConnectThrottle({
|
|
115
|
+
connectorId,
|
|
116
|
+
platformUserId: args.platformUserId,
|
|
117
|
+
email: args.email,
|
|
118
|
+
config: config.throttle,
|
|
119
|
+
});
|
|
120
|
+
if (!throttle.ok) {
|
|
121
|
+
return { ok: false, reason: throttle.reason };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const token = await mintColdConnectToken<S>({
|
|
125
|
+
binding: {
|
|
126
|
+
connectorId,
|
|
127
|
+
platformUserId: args.platformUserId,
|
|
128
|
+
email: args.email,
|
|
129
|
+
scalars: args.scalars,
|
|
130
|
+
},
|
|
131
|
+
ttlSeconds: config.ttlSeconds,
|
|
132
|
+
});
|
|
133
|
+
if (!token) return { ok: false, reason: "redis_unavailable" };
|
|
134
|
+
return { ok: true, token };
|
|
135
|
+
},
|
|
136
|
+
|
|
137
|
+
confirmUrl(args) {
|
|
138
|
+
return buildColdConnectUrl({
|
|
139
|
+
apiPublicUrl: args.apiPublicUrl,
|
|
140
|
+
connectorId,
|
|
141
|
+
token: args.token,
|
|
142
|
+
});
|
|
143
|
+
},
|
|
144
|
+
|
|
145
|
+
routes(app) {
|
|
146
|
+
// GET = pure page render (no writes). `?tok=` is read CLIENT-side, never
|
|
147
|
+
// reflected into the markup.
|
|
148
|
+
app.get(pagePath, (c) => {
|
|
149
|
+
const { env } = c.get("container");
|
|
150
|
+
return c.html(
|
|
151
|
+
coldConnectPageHtml(config.branding, {
|
|
152
|
+
posthogKey: env.POSTHOG_API_KEY ?? null,
|
|
153
|
+
posthogHost: env.POSTHOG_HOST ?? null,
|
|
154
|
+
exchangeUrl: exchangePath,
|
|
155
|
+
identifyPropKey: config.identifyPropKey,
|
|
156
|
+
}),
|
|
157
|
+
);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
// POST = the bind. Body is `{tok}` ONLY (identity fields are rejected —
|
|
161
|
+
// they only ever come from the sealed token).
|
|
162
|
+
app.post(exchangePath, async (c) => {
|
|
163
|
+
const container = c.get("container");
|
|
164
|
+
|
|
165
|
+
let body: unknown;
|
|
166
|
+
try {
|
|
167
|
+
body = await c.req.json();
|
|
168
|
+
} catch {
|
|
169
|
+
return c.json({ ok: false, error: "bad_json" }, 400);
|
|
170
|
+
}
|
|
171
|
+
const tok =
|
|
172
|
+
body && typeof (body as { tok?: unknown }).tok === "string"
|
|
173
|
+
? (body as { tok: string }).tok
|
|
174
|
+
: "";
|
|
175
|
+
if (!tok) {
|
|
176
|
+
return c.json({ ok: false, error: "missing_token" }, 400);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const binding = await peekColdConnectToken<S>({
|
|
180
|
+
connectorId,
|
|
181
|
+
token: tok,
|
|
182
|
+
});
|
|
183
|
+
if (!binding) {
|
|
184
|
+
return c.json({ ok: false, error: "invalid_or_used" }, 410);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Cross-connector token isolation: a token minted for another connector
|
|
188
|
+
// can never be redeemed here even if a composer miswired the mounts.
|
|
189
|
+
if (binding.connectorId !== connectorId) {
|
|
190
|
+
return c.json({ ok: false, error: "connector_mismatch" }, 410);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const platformKey = config.platformKey(binding.platformUserId);
|
|
194
|
+
const { eventProperties, contactProperties } =
|
|
195
|
+
config.buildIngest(binding);
|
|
196
|
+
|
|
197
|
+
// Authoritative bind via ingestEvent (NOT linkContact — linkContact never
|
|
198
|
+
// calls hatchet.events.push, which would kill the welcome journey that
|
|
199
|
+
// `onEvents:[linkedEvent]`). ingestEvent returns the canonical contactKey
|
|
200
|
+
// (handed to the page's posthog.identify) and fires the analytics merge.
|
|
201
|
+
// If this throws (Hatchet/DB blip → 500), the token is NOT consumed
|
|
202
|
+
// below, so the user's retry still works (peek, not consume-on-read).
|
|
203
|
+
const result = await ingestEvent({
|
|
204
|
+
db: container.db,
|
|
205
|
+
registry: container.registry,
|
|
206
|
+
hatchet: container.hatchet,
|
|
207
|
+
logger: container.logger,
|
|
208
|
+
analytics: container.analytics,
|
|
209
|
+
event: {
|
|
210
|
+
event: config.linkedEvent,
|
|
211
|
+
[config.identityKind]: platformKey,
|
|
212
|
+
userEmail: binding.email,
|
|
213
|
+
eventProperties,
|
|
214
|
+
contactProperties,
|
|
215
|
+
idempotencyKey: `cc:confirm:${connectorId}:${binding.platformUserId}:${tok}`,
|
|
216
|
+
},
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
const contactKey = result.contactKey;
|
|
220
|
+
|
|
221
|
+
// afterBind is AT-LEAST-ONCE (idempotent-required). The token is consumed
|
|
222
|
+
// even if it throws — the bind already committed, so a flaky hook must not
|
|
223
|
+
// keep the token live and re-fire on every click.
|
|
224
|
+
try {
|
|
225
|
+
await config.afterBind?.({ ...binding, contactKey }, { container });
|
|
226
|
+
} catch (err) {
|
|
227
|
+
container.logger.warn("coldConnect afterBind threw", {
|
|
228
|
+
connectorId,
|
|
229
|
+
error: err instanceof Error ? err.message : String(err),
|
|
230
|
+
});
|
|
231
|
+
} finally {
|
|
232
|
+
await consumeColdConnectToken({ connectorId, token: tok });
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return c.json({
|
|
236
|
+
ok: true,
|
|
237
|
+
key: contactKey,
|
|
238
|
+
platformUserId: binding.platformUserId,
|
|
239
|
+
});
|
|
240
|
+
});
|
|
241
|
+
},
|
|
242
|
+
};
|
|
243
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Branding for the cold-connect page. Every field is plain text (NOT HTML) — the
|
|
3
|
+
* page JSON-embeds them into a JS-string-safe config and writes them via
|
|
4
|
+
* `textContent`, so no field can inject markup. `accentColor` is regex-validated
|
|
5
|
+
* to a 6-digit hex before it ever reaches a stylesheet.
|
|
6
|
+
*/
|
|
7
|
+
export interface ColdConnectBranding {
|
|
8
|
+
/** Page `<title>` + heading before the user confirms. */
|
|
9
|
+
title: string;
|
|
10
|
+
/** Body copy under the heading. */
|
|
11
|
+
blurb: string;
|
|
12
|
+
/** Heading + body shown after a successful bind. */
|
|
13
|
+
successCopy: { heading: string; body: string };
|
|
14
|
+
/** Heading + body shown after a failed/expired bind. */
|
|
15
|
+
errorCopy: { heading: string; body: string };
|
|
16
|
+
/** A short emoji/glyph rendered in the badge. */
|
|
17
|
+
badge: string;
|
|
18
|
+
/** Accent color (`#rrggbb`); validated, falls back to a safe blue. */
|
|
19
|
+
accentColor?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const ACCENT_RE = /^#[0-9a-fA-F]{6}$/;
|
|
23
|
+
const DEFAULT_ACCENT = "#2f81f7";
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Self-contained dark connect page, generalized from the Telegram connect page.
|
|
27
|
+
*
|
|
28
|
+
* Security (from the adversarial review):
|
|
29
|
+
* - `?tok=` is read CLIENT-side and never reflected into the markup.
|
|
30
|
+
* - The bind happens on a human button CLICK (POST), NEVER on GET — an email
|
|
31
|
+
* link-preview prefetch can't complete it.
|
|
32
|
+
* - The page identifies CLIENT-side (real geo/IP) keyed to the SERVER-proven
|
|
33
|
+
* `contactKey` the exchange returns — it never sends a distinct_id the server
|
|
34
|
+
* resolves a contact on, so there is no graft/takeover vector.
|
|
35
|
+
* - posthog-js inits with `cross_subdomain_cookie: true` so it reads the
|
|
36
|
+
* visitor's existing `.hogsend.com` distinct_id and folds their prior
|
|
37
|
+
* anonymous browsing into the now-identified person.
|
|
38
|
+
*
|
|
39
|
+
* Branding is plain-text/JSON-embedded; `accentColor` is regex-validated.
|
|
40
|
+
*/
|
|
41
|
+
export function coldConnectPageHtml(
|
|
42
|
+
branding: ColdConnectBranding,
|
|
43
|
+
opts: {
|
|
44
|
+
posthogKey: string | null;
|
|
45
|
+
posthogHost: string | null;
|
|
46
|
+
exchangeUrl: string;
|
|
47
|
+
identifyPropKey: string;
|
|
48
|
+
},
|
|
49
|
+
): string {
|
|
50
|
+
const accent =
|
|
51
|
+
branding.accentColor && ACCENT_RE.test(branding.accentColor)
|
|
52
|
+
? branding.accentColor
|
|
53
|
+
: DEFAULT_ACCENT;
|
|
54
|
+
|
|
55
|
+
const config = JSON.stringify({
|
|
56
|
+
posthogKey: opts.posthogKey,
|
|
57
|
+
// posthog-js falls back to US when host is null; an EU deploy must set
|
|
58
|
+
// POSTHOG_HOST.
|
|
59
|
+
posthogHost: opts.posthogHost,
|
|
60
|
+
exchangeUrl: opts.exchangeUrl,
|
|
61
|
+
identifyPropKey: opts.identifyPropKey,
|
|
62
|
+
badge: branding.badge,
|
|
63
|
+
title: branding.title,
|
|
64
|
+
blurb: branding.blurb,
|
|
65
|
+
successCopy: branding.successCopy,
|
|
66
|
+
errorCopy: branding.errorCopy,
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
return `<!doctype html>
|
|
70
|
+
<html lang="en">
|
|
71
|
+
<head>
|
|
72
|
+
<meta charset="utf-8" />
|
|
73
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
74
|
+
<meta name="robots" content="noindex" />
|
|
75
|
+
<title>Connect</title>
|
|
76
|
+
<style>
|
|
77
|
+
:root { color-scheme: dark; }
|
|
78
|
+
* { box-sizing: border-box; }
|
|
79
|
+
body {
|
|
80
|
+
margin: 0; min-height: 100vh; display: flex; align-items: center;
|
|
81
|
+
justify-content: center; background: #09090b; color: #fafafa;
|
|
82
|
+
font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto,
|
|
83
|
+
Helvetica, Arial, sans-serif; padding: 24px;
|
|
84
|
+
}
|
|
85
|
+
.card {
|
|
86
|
+
max-width: 440px; width: 100%; text-align: center;
|
|
87
|
+
background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.1);
|
|
88
|
+
border-radius: 16px; padding: 40px 32px;
|
|
89
|
+
}
|
|
90
|
+
.badge {
|
|
91
|
+
width: 56px; height: 56px; margin: 0 auto 20px; border-radius: 9999px;
|
|
92
|
+
display: flex; align-items: center; justify-content: center;
|
|
93
|
+
background: ${accent}26; font-size: 28px;
|
|
94
|
+
}
|
|
95
|
+
h1 { font-size: 20px; margin: 0 0 8px; font-weight: 600; }
|
|
96
|
+
p { margin: 0 0 24px; color: rgba(250,250,250,0.7); line-height: 1.6; }
|
|
97
|
+
button {
|
|
98
|
+
appearance: none; border: 0; border-radius: 10px; cursor: pointer;
|
|
99
|
+
background: ${accent}; color: #fff; font-size: 15px; font-weight: 600;
|
|
100
|
+
padding: 12px 20px; width: 100%;
|
|
101
|
+
}
|
|
102
|
+
button:disabled { opacity: 0.6; cursor: default; }
|
|
103
|
+
</style>
|
|
104
|
+
</head>
|
|
105
|
+
<body>
|
|
106
|
+
<main class="card">
|
|
107
|
+
<div class="badge" id="badge" aria-hidden="true"></div>
|
|
108
|
+
<h1 id="h"></h1>
|
|
109
|
+
<p id="p"></p>
|
|
110
|
+
<button id="btn" type="button">Confirm connection</button>
|
|
111
|
+
</main>
|
|
112
|
+
<script>
|
|
113
|
+
var CFG = ${config};
|
|
114
|
+
var tok = new URLSearchParams(location.search).get("tok");
|
|
115
|
+
var btn = document.getElementById("btn");
|
|
116
|
+
var h = document.getElementById("h");
|
|
117
|
+
var p = document.getElementById("p");
|
|
118
|
+
var badge = document.getElementById("badge");
|
|
119
|
+
|
|
120
|
+
badge.textContent = CFG.badge;
|
|
121
|
+
h.textContent = CFG.title;
|
|
122
|
+
p.textContent = CFG.blurb;
|
|
123
|
+
|
|
124
|
+
function loadPosthog(host) {
|
|
125
|
+
!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagPayload isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
|
|
126
|
+
window.posthog.init(CFG.posthogKey, {
|
|
127
|
+
api_host: host,
|
|
128
|
+
person_profiles: "always",
|
|
129
|
+
cross_subdomain_cookie: true,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function done(ok, key, platformUserId) {
|
|
134
|
+
btn.style.display = "none";
|
|
135
|
+
if (ok && CFG.posthogKey) {
|
|
136
|
+
try {
|
|
137
|
+
loadPosthog(CFG.posthogHost || "https://us.i.posthog.com");
|
|
138
|
+
var props = {};
|
|
139
|
+
props[CFG.identifyPropKey] = platformUserId;
|
|
140
|
+
window.posthog.identify(key, props);
|
|
141
|
+
} catch (e) {}
|
|
142
|
+
}
|
|
143
|
+
var copy = ok ? CFG.successCopy : CFG.errorCopy;
|
|
144
|
+
h.textContent = copy.heading;
|
|
145
|
+
p.textContent = copy.body;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
btn.addEventListener("click", function () {
|
|
149
|
+
if (!tok) { done(false); return; }
|
|
150
|
+
btn.disabled = true;
|
|
151
|
+
btn.textContent = "Connecting…";
|
|
152
|
+
fetch(CFG.exchangeUrl, {
|
|
153
|
+
method: "POST",
|
|
154
|
+
headers: { "content-type": "application/json" },
|
|
155
|
+
body: JSON.stringify({ tok: tok }),
|
|
156
|
+
})
|
|
157
|
+
.then(function (r) { return r.json(); })
|
|
158
|
+
.then(function (j) { done(!!j.ok, j.key, j.platformUserId); })
|
|
159
|
+
.catch(function () { done(false); });
|
|
160
|
+
});
|
|
161
|
+
</script>
|
|
162
|
+
</body>
|
|
163
|
+
</html>`;
|
|
164
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { getRedis } from "../lib/redis.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Mint-throttle config for a cold-connect flow. Two independent budgets — one
|
|
5
|
+
* keyed on the platform user id, one on the email — each a fixed-window counter
|
|
6
|
+
* (`windowSeconds` / `max`). Both default to a conservative "a few per 15 min".
|
|
7
|
+
*/
|
|
8
|
+
export interface ColdConnectThrottleConfig {
|
|
9
|
+
/** Per-platform-user budget. */
|
|
10
|
+
perUser?: { windowSeconds?: number; max?: number };
|
|
11
|
+
/** Per-email budget. */
|
|
12
|
+
perEmail?: { windowSeconds?: number; max?: number };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const DEFAULT_WINDOW_SECONDS = 900;
|
|
16
|
+
const DEFAULT_MAX = 5;
|
|
17
|
+
|
|
18
|
+
export type ThrottleResult =
|
|
19
|
+
| { ok: true }
|
|
20
|
+
| { ok: false; reason: "rate_limited" | "redis_unavailable" };
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* A single fixed-window INCR counter. `INCR` the key; on the FIRST increment set
|
|
24
|
+
* its TTL so the window slides forward. A Redis fault throws so the caller can
|
|
25
|
+
* fail CLOSED — we never want a cache blip to silently disable the mint throttle
|
|
26
|
+
* (which gates outbound email). Returns the post-increment count.
|
|
27
|
+
*/
|
|
28
|
+
async function bump(key: string, windowSeconds: number): Promise<number> {
|
|
29
|
+
const redis = getRedis();
|
|
30
|
+
if (!redis) throw new Error("redis_unavailable");
|
|
31
|
+
const count = await redis.incr(key);
|
|
32
|
+
if (count === 1) {
|
|
33
|
+
await redis.expire(key, windowSeconds);
|
|
34
|
+
}
|
|
35
|
+
return count;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Mint-counted, Redis-INCR throttle for a cold-connect confirm mint. Bumps both
|
|
40
|
+
* the per-user and per-email windows and rejects when EITHER is over its cap.
|
|
41
|
+
*
|
|
42
|
+
* Fail-CLOSED: any Redis fault returns `{ ok:false, reason:"redis_unavailable"
|
|
43
|
+
* }` so the caller (`mintConfirm`) returns `{ ok:false }` and does NOT send a
|
|
44
|
+
* link. Cold-connect deliberately stays OFF the `connectorLinkCodes` DB table —
|
|
45
|
+
* these counters live only in Redis.
|
|
46
|
+
*/
|
|
47
|
+
export async function checkColdConnectThrottle(args: {
|
|
48
|
+
connectorId: string;
|
|
49
|
+
platformUserId: string;
|
|
50
|
+
email: string;
|
|
51
|
+
config?: ColdConnectThrottleConfig;
|
|
52
|
+
}): Promise<ThrottleResult> {
|
|
53
|
+
const { connectorId, platformUserId, email, config } = args;
|
|
54
|
+
|
|
55
|
+
const userWindow = config?.perUser?.windowSeconds ?? DEFAULT_WINDOW_SECONDS;
|
|
56
|
+
const userMax = config?.perUser?.max ?? DEFAULT_MAX;
|
|
57
|
+
const emailWindow = config?.perEmail?.windowSeconds ?? DEFAULT_WINDOW_SECONDS;
|
|
58
|
+
const emailMax = config?.perEmail?.max ?? DEFAULT_MAX;
|
|
59
|
+
|
|
60
|
+
const userKey = `hogsend:cc:throttle:${connectorId}:user:${platformUserId}`;
|
|
61
|
+
const emailKey = `hogsend:cc:throttle:${connectorId}:email:${email.toLowerCase()}`;
|
|
62
|
+
|
|
63
|
+
try {
|
|
64
|
+
const [userCount, emailCount] = await Promise.all([
|
|
65
|
+
bump(userKey, userWindow),
|
|
66
|
+
bump(emailKey, emailWindow),
|
|
67
|
+
]);
|
|
68
|
+
if (userCount > userMax || emailCount > emailMax) {
|
|
69
|
+
return { ok: false, reason: "rate_limited" };
|
|
70
|
+
}
|
|
71
|
+
return { ok: true };
|
|
72
|
+
} catch {
|
|
73
|
+
return { ok: false, reason: "redis_unavailable" };
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { getRedis } from "../lib/redis.js";
|
|
3
|
+
|
|
4
|
+
/** Default time-to-live for a cold-connect confirm token (seconds). */
|
|
5
|
+
export const COLD_CONNECT_DEFAULT_TTL_SECONDS = 900;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The sealed cold-connect binding. The `connectorId` is sealed IN the value so
|
|
9
|
+
* the exchange route can assert it matches the route it was redeemed on
|
|
10
|
+
* (cross-connector token isolation): a token minted for one connector can never
|
|
11
|
+
* be redeemed by another, even if a composer miswires the mounts.
|
|
12
|
+
*/
|
|
13
|
+
export interface ColdConnectBinding<S = Record<string, unknown>> {
|
|
14
|
+
connectorId: string;
|
|
15
|
+
platformUserId: string;
|
|
16
|
+
email: string;
|
|
17
|
+
/** Caller-supplied extra scalars carried through to the exchange. */
|
|
18
|
+
scalars?: S;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The Redis key for a cold-connect token. Namespaced per connector so two
|
|
23
|
+
* connectors' token spaces never collide and a peek/consume scoped to one
|
|
24
|
+
* connector can never touch another's.
|
|
25
|
+
*/
|
|
26
|
+
function tokenKey(connectorId: string, token: string): string {
|
|
27
|
+
return `hogsend:cc:${connectorId}:${token}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** An opaque, URL-safe token (32 hex chars). */
|
|
31
|
+
function randomToken(): string {
|
|
32
|
+
return randomBytes(16).toString("hex");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Mint a cold-connect confirm token sealing `{ connectorId, platformUserId,
|
|
37
|
+
* email, scalars }` server-side in Redis (TTL-bounded). The token rides in a
|
|
38
|
+
* link emailed to that address — clicking it proves inbox ownership. The web
|
|
39
|
+
* caller never names the platform id OR an arbitrary email; both come from the
|
|
40
|
+
* server-sealed token, not the request. Returns the token, or `null` when Redis
|
|
41
|
+
* is unavailable (fail-closed — the caller must not send a link it can't honor).
|
|
42
|
+
*/
|
|
43
|
+
export async function mintColdConnectToken<S = Record<string, unknown>>(args: {
|
|
44
|
+
binding: ColdConnectBinding<S>;
|
|
45
|
+
ttlSeconds?: number;
|
|
46
|
+
}): Promise<string | null> {
|
|
47
|
+
const redis = getRedis();
|
|
48
|
+
if (!redis) return null;
|
|
49
|
+
const token = randomToken();
|
|
50
|
+
try {
|
|
51
|
+
await redis.set(
|
|
52
|
+
tokenKey(args.binding.connectorId, token),
|
|
53
|
+
JSON.stringify(args.binding),
|
|
54
|
+
"EX",
|
|
55
|
+
args.ttlSeconds ?? COLD_CONNECT_DEFAULT_TTL_SECONDS,
|
|
56
|
+
);
|
|
57
|
+
} catch {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
return token;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* PEEK a token's sealed binding WITHOUT consuming it (Redis GET). The exchange
|
|
65
|
+
* consumes the token only AFTER the bind ingest commits, so a transient failure
|
|
66
|
+
* doesn't burn the user's single click. Returns `null` on unknown/expired/
|
|
67
|
+
* malformed token.
|
|
68
|
+
*/
|
|
69
|
+
export async function peekColdConnectToken<S = Record<string, unknown>>(args: {
|
|
70
|
+
connectorId: string;
|
|
71
|
+
token: string;
|
|
72
|
+
}): Promise<ColdConnectBinding<S> | null> {
|
|
73
|
+
const redis = getRedis();
|
|
74
|
+
if (!redis) return null;
|
|
75
|
+
let raw: string | null;
|
|
76
|
+
try {
|
|
77
|
+
raw = await redis.get(tokenKey(args.connectorId, args.token));
|
|
78
|
+
} catch {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
if (!raw) return null;
|
|
82
|
+
try {
|
|
83
|
+
const b = JSON.parse(raw) as ColdConnectBinding<S>;
|
|
84
|
+
if (
|
|
85
|
+
b &&
|
|
86
|
+
typeof b.connectorId === "string" &&
|
|
87
|
+
typeof b.platformUserId === "string" &&
|
|
88
|
+
typeof b.email === "string"
|
|
89
|
+
) {
|
|
90
|
+
return b;
|
|
91
|
+
}
|
|
92
|
+
} catch {
|
|
93
|
+
// malformed binding — treat as a miss
|
|
94
|
+
}
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Consume (single-use delete) a token AFTER its bind ingest has committed.
|
|
100
|
+
* Idempotent: a second click then sees the token gone. Best-effort — a Redis
|
|
101
|
+
* blip here leaves the token to expire on its TTL.
|
|
102
|
+
*/
|
|
103
|
+
export async function consumeColdConnectToken(args: {
|
|
104
|
+
connectorId: string;
|
|
105
|
+
token: string;
|
|
106
|
+
}): Promise<void> {
|
|
107
|
+
const redis = getRedis();
|
|
108
|
+
if (!redis) return;
|
|
109
|
+
try {
|
|
110
|
+
await redis.del(tokenKey(args.connectorId, args.token));
|
|
111
|
+
} catch {
|
|
112
|
+
// Degrade to no-op — the TTL bounds single-use anyway.
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Build the email-confirmation connect URL on the customer's own API_PUBLIC_URL.
|
|
118
|
+
* The path is derived from `connectorId` (`/connect/<connectorId>?tok=…`) — the
|
|
119
|
+
* same basePath `cc.routes` mounts, so a minted URL always resolves.
|
|
120
|
+
*/
|
|
121
|
+
export function buildColdConnectUrl(args: {
|
|
122
|
+
apiPublicUrl: string;
|
|
123
|
+
connectorId: string;
|
|
124
|
+
token: string;
|
|
125
|
+
}): string {
|
|
126
|
+
const base = args.apiPublicUrl.replace(/\/$/, "");
|
|
127
|
+
return `${base}/connect/${args.connectorId}?tok=${encodeURIComponent(
|
|
128
|
+
args.token,
|
|
129
|
+
)}`;
|
|
130
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -57,7 +57,12 @@ export {
|
|
|
57
57
|
type SchemaVersion,
|
|
58
58
|
} from "@hogsend/db";
|
|
59
59
|
// --- App / container / worker factories ---
|
|
60
|
-
export {
|
|
60
|
+
export {
|
|
61
|
+
type AppEnv,
|
|
62
|
+
type CreateAppOptions,
|
|
63
|
+
createApp,
|
|
64
|
+
type RoutesFn,
|
|
65
|
+
} from "./app.js";
|
|
61
66
|
// --- Buckets ---
|
|
62
67
|
export {
|
|
63
68
|
type BucketAccessor,
|
|
@@ -91,6 +96,14 @@ export {
|
|
|
91
96
|
resetBucketRegistry,
|
|
92
97
|
setBucketRegistry,
|
|
93
98
|
} from "./buckets/registry-singleton.js";
|
|
99
|
+
// --- Cold-connect (email-confirmed chat-platform contact linking) ---
|
|
100
|
+
export {
|
|
101
|
+
type ColdConnect,
|
|
102
|
+
type ColdConnectBinding,
|
|
103
|
+
type ColdConnectBranding,
|
|
104
|
+
type ColdConnectConfig,
|
|
105
|
+
createColdConnect,
|
|
106
|
+
} from "./cold-connect/index.js";
|
|
94
107
|
export {
|
|
95
108
|
ConnectorActionRegistry,
|
|
96
109
|
getConnectorActionRegistry,
|