@hogsend/engine 0.35.1 → 0.36.1

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hogsend/engine",
3
- "version": "0.35.1",
3
+ "version": "0.36.1",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -42,14 +42,14 @@
42
42
  "svix": "^1.95.1",
43
43
  "winston": "^3.19.0",
44
44
  "zod": "^4.4.3",
45
- "@hogsend/core": "^0.35.1",
46
- "@hogsend/db": "^0.35.1",
47
- "@hogsend/email": "^0.35.1",
48
- "@hogsend/plugin-posthog": "^0.35.1",
49
- "@hogsend/plugin-resend": "^0.35.1"
45
+ "@hogsend/core": "^0.36.1",
46
+ "@hogsend/db": "^0.36.1",
47
+ "@hogsend/email": "^0.36.1",
48
+ "@hogsend/plugin-posthog": "^0.36.1",
49
+ "@hogsend/plugin-resend": "^0.36.1"
50
50
  },
51
51
  "optionalDependencies": {
52
- "@hogsend/plugin-postmark": "^0.35.1"
52
+ "@hogsend/plugin-postmark": "^0.36.1"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@types/node": "^22.15.3",
package/src/app.ts CHANGED
@@ -30,6 +30,11 @@ export type AppEnv = {
30
30
  user: NonNullable<AuthSession>["user"] | null;
31
31
  session: NonNullable<AuthSession>["session"] | null;
32
32
  apiKey: ApiKeyContext | undefined;
33
+ // True when the request authenticated with a PUBLISHABLE (pk_) key via
34
+ // `requirePublishableOrIngest`. Publishable-reachable handlers gate their
35
+ // identity logic on this (a pk_ key is anon-only without a verified
36
+ // userToken). Undefined/false for secret-key + session requests.
37
+ publishable?: boolean;
33
38
  };
34
39
  };
35
40
 
@@ -77,7 +82,23 @@ export function createApp(
77
82
  });
78
83
 
79
84
  app.use("*", secureHeaders());
80
- app.use("*", cors());
85
+ app.use(
86
+ "*",
87
+ cors({
88
+ // Reflect the request Origin so a browser can READ the response (needed
89
+ // for pk_ publishable-key ingest from arbitrary first-party origins).
90
+ // This is NOT the security boundary — the per-key Origin allowlist is
91
+ // enforced inside `requirePublishableOrIngest` on the actual (non-
92
+ // preflight) request. A preflight carries no Bearer, so the key class is
93
+ // unknowable here; echoing the Origin lets the browser proceed to the
94
+ // real request, which the guard then accepts or 403s. Returning "*" for an
95
+ // Origin-less request (same-origin / server SDK) preserves today's
96
+ // wildcard behavior. `credentials` stays default-off (pk_ ingest is
97
+ // header-bearer, not cookie-auth), so reflecting the Origin does not widen
98
+ // credentialed/cookie exposure.
99
+ origin: (origin) => origin ?? "*",
100
+ }),
101
+ );
81
102
  app.use("*", compress());
82
103
  app.use("*", requestId());
83
104
  app.use("*", requestLogger);
package/src/index.ts CHANGED
@@ -232,6 +232,12 @@ export {
232
232
  type BatchedBackfillResult,
233
233
  runBatchedBackfill,
234
234
  } from "./lib/backfill.js";
235
+ // --- On-site banners (thin over sendFeedItem, category `banner:<slot>`) ---
236
+ export {
237
+ type SendBannerOptions,
238
+ type SendBannerResult,
239
+ sendBanner,
240
+ } from "./lib/banner.js";
235
241
  // --- Boot output (engine-owned startup banner / structured ready log) ---
236
242
  export {
237
243
  type ApiReadyInfo,
@@ -327,6 +333,13 @@ export type {
327
333
  } from "./lib/email-service-types.js";
328
334
  // --- Enrollment guards ---
329
335
  export { checkEmailPreferences } from "./lib/enrollment-guards.js";
336
+ // --- In-app feed (sendFeedItem — sibling of sendEmail/sendConnectorAction) ---
337
+ export {
338
+ IN_APP_LIST_ID,
339
+ type SendFeedItemOptions,
340
+ type SendFeedItemResult,
341
+ sendFeedItem,
342
+ } from "./lib/feed.js";
330
343
  export { isFrequencyCapped } from "./lib/frequency-cap.js";
331
344
  export { addrSpecOf, hostOfFromAddress } from "./lib/from-address.js";
332
345
  export { hatchet } from "./lib/hatchet.js";
@@ -451,6 +464,40 @@ export {
451
464
  */
452
465
  resolveEmailSendContextByResendId,
453
466
  } from "./lib/tracking-events.js";
467
+ /**
468
+ * Publishable-key `userToken` mint/verify helpers.
469
+ *
470
+ * `generateUserToken` is the official SERVER-SIDE mint helper. It signs a
471
+ * short-lived HMAC over a `userId` with `BETTER_AUTH_SECRET`. A publishable
472
+ * (`pk_`) key is anon-only by default; to let an identified browser act on a
473
+ * concrete `userId`, the HOST BACKEND calls this AFTER its own login and hands
474
+ * the result to the browser:
475
+ *
476
+ * ```ts
477
+ * // host server route, AFTER authenticating the user — NEVER expose the secret:
478
+ * import { generateUserToken } from "@hogsend/engine";
479
+ * const userToken = generateUserToken({
480
+ * secret: process.env.BETTER_AUTH_SECRET!,
481
+ * userId: session.user.id,
482
+ * expiresInSeconds: 3600,
483
+ * });
484
+ * // return { userToken } to the browser; the SDK threads it into every
485
+ * // identity-asserting data-plane call (createHogsend({ userToken }) /
486
+ * // <HogsendProvider userToken={...}>). On expiry the SDK calls
487
+ * // config.onUserTokenExpiring() — point that at re-hitting this route.
488
+ * ```
489
+ *
490
+ * SERVER-SIDE ONLY: it uses `node:crypto` and needs `BETTER_AUTH_SECRET`. Do
491
+ * NOT mount it as a route and do NOT call it from a browser (it would leak the
492
+ * signing secret). `verifyUserToken` is the symmetric half the engine wires
493
+ * into every publishable-reachable handler.
494
+ */
495
+ export {
496
+ generateUserToken,
497
+ InvalidUserTokenError,
498
+ type UserTokenPayload,
499
+ verifyUserToken,
500
+ } from "./lib/user-token.js";
454
501
  // --- Outbound webhooks: signing core (Section 1.2) ---
455
502
  export {
456
503
  generateWebhookSecret,
@@ -518,3 +565,4 @@ export { importContactsTask } from "./workflows/import-contacts.js";
518
565
  export { sendCampaignTask } from "./workflows/send-campaign.js";
519
566
  // --- Built-in Hatchet workflow tasks ---
520
567
  export { sendEmailTask } from "./workflows/send-email.js";
568
+ export { sendFeedTask } from "./workflows/send-feed.js";
@@ -2,13 +2,18 @@ import { createHash, randomBytes } from "node:crypto";
2
2
 
3
3
  const PREFIX_LENGTH = 8;
4
4
 
5
- export function generateApiKey(): {
5
+ export function generateApiKey(opts?: { publishable?: boolean }): {
6
6
  key: string;
7
7
  prefix: string;
8
8
  hash: string;
9
9
  } {
10
10
  const raw = randomBytes(32).toString("base64url");
11
- const key = `hsk_${raw}`;
11
+ // Publishable (browser-safe) keys are minted with the `pk_` class prefix;
12
+ // secret server keys keep `hsk_`. The class lives ENTIRELY in the raw token's
13
+ // prefix — no DB column — so the request guard can branch on the bearer's
14
+ // prefix before any DB work (the CORS preflight carries no bearer, so the
15
+ // class is unknowable at the CORS layer; the guard is the boundary).
16
+ const key = `${opts?.publishable ? "pk_" : "hsk_"}${raw}`;
12
17
  const prefix = key.slice(0, PREFIX_LENGTH);
13
18
  const hash = hashApiKey(key);
14
19
  return { key, prefix, hash };
@@ -0,0 +1,71 @@
1
+ import type { FeedBlock } from "@hogsend/db";
2
+ import { type SendFeedItemResult, sendFeedItem } from "./feed.js";
3
+
4
+ /**
5
+ * The banner-category prefix. A banner is just a delivered feed item in a
6
+ * dedicated, per-slot category `banner:<slot>` (NOT the default `in_app` feed),
7
+ * so banners never pollute the notification bell and map onto the SAME
8
+ * recipient-scoped read path (`GET /v1/feed?feedId=banner:<slot>`).
9
+ */
10
+ export const BANNER_CATEGORY_PREFIX = "banner:";
11
+
12
+ /**
13
+ * Compose the feed category for a banner slot. `banner:<slot>`.
14
+ */
15
+ export function bannerCategory(slot: string): string {
16
+ return `${BANNER_CATEGORY_PREFIX}${slot}`;
17
+ }
18
+
19
+ export interface SendBannerOptions {
20
+ recipient: { userId?: string; email?: string; anonymousId?: string };
21
+ /** Banner placement slot (e.g. `"top"`, `"billing"`). Maps to category `banner:<slot>`. */
22
+ slot: string;
23
+ title?: string;
24
+ body?: string;
25
+ blocks?: FeedBlock[];
26
+ actionUrl?: string;
27
+ metadata?: Record<string, unknown>;
28
+ templateKey?: string;
29
+ journeyStateId?: string;
30
+ /** Explicit idempotency key — wins over journey auto-derivation. */
31
+ idempotencyKey?: string;
32
+ /** Disambiguates the exactly-once key across divergent branches. */
33
+ idempotencyLabel?: string;
34
+ }
35
+
36
+ export type SendBannerResult = SendFeedItemResult;
37
+
38
+ /**
39
+ * Journey-callable on-site banner send — a thin wrapper over {@link sendFeedItem}
40
+ * that pins `type: "banner"` and `category: "banner:<slot>"`. It inherits feed
41
+ * recipient resolution, `in_app` suppression, replay-safe idempotency, and the
42
+ * Redis `feed:<recipientKey>` realtime publish (so banners are realtime too).
43
+ *
44
+ * The dedicated `banner:<slot>` category keeps banners out of the default
45
+ * `in_app` notification feed. The browser reads them via
46
+ * `GET /v1/feed?feedId=banner:<slot>` (the existing route category-filters and
47
+ * recipient-scopes server-side — no new read path).
48
+ *
49
+ * Event story: dismiss/click persist via the feed `/mark` route, whose
50
+ * `inapp.*` emits are INTERNAL feed-state bookkeeping. The consumer-facing
51
+ * journey trigger is the distinct-namespace `banner.dismissed` / `banner.clicked`
52
+ * / `banner.shown` the SDK emits client-side.
53
+ */
54
+ export async function sendBanner(
55
+ opts: SendBannerOptions,
56
+ ): Promise<SendBannerResult> {
57
+ return sendFeedItem({
58
+ recipient: opts.recipient,
59
+ type: "banner",
60
+ category: bannerCategory(opts.slot),
61
+ title: opts.title,
62
+ body: opts.body,
63
+ blocks: opts.blocks,
64
+ actionUrl: opts.actionUrl,
65
+ metadata: opts.metadata,
66
+ templateKey: opts.templateKey,
67
+ journeyStateId: opts.journeyStateId,
68
+ idempotencyKey: opts.idempotencyKey,
69
+ idempotencyLabel: opts.idempotencyLabel,
70
+ });
71
+ }
@@ -13,6 +13,44 @@ import { and, eq, ilike, inArray, isNull, or, sql } from "drizzle-orm";
13
13
  const UUID_REGEX =
14
14
  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
15
15
 
16
+ /**
17
+ * Thrown by {@link resolveOrCreateContact} when a PUBLISHABLE (browser, pk_) anon
18
+ * write would attach to / merge into / mutate a contact that already carries an
19
+ * IDENTIFIED key (`external_id` or `email`), OR would drive a collide-MERGE.
20
+ *
21
+ * The `anonymousId` (PostHog `get_distinct_id()`) is browser-readable by design,
22
+ * so on the publishable path it is NOT a secret and must never be a merge driver
23
+ * or a path to a victim's identified contact. An anon-only publishable write may
24
+ * only create or update its OWN anonymous-only contact. Handlers translate this
25
+ * to a 403. The secret-key path NEVER sets `restrictToAnonymous`, so its behavior
26
+ * is unchanged.
27
+ */
28
+ export class PublishableAnonymousMergeError extends Error {
29
+ constructor(
30
+ message = "publishable anonymous write cannot attach to or merge an identified contact",
31
+ ) {
32
+ super(message);
33
+ this.name = "PublishableAnonymousMergeError";
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Thrown by {@link resolveOrCreateContact}'s engine-internal `contactId` pin when
39
+ * the pinned subject row no longer exists and no merge-alias chain leads to a live
40
+ * survivor (the subject was hard-deleted). The internal re-emit is then dropped
41
+ * (ingestEvent returns `{ stored: false }`, logs `identity.provenance.lost`) rather
42
+ * than value-resolving — a value fall-back could mint the very phantom twin the
43
+ * pin exists to prevent. Reachable ONLY for a hard-deleted/unfollowable subject.
44
+ */
45
+ export class ContactProvenanceLostError extends Error {
46
+ constructor(public readonly contactId: string) {
47
+ super(
48
+ `contact provenance lost: no live contact or survivor for ${contactId}`,
49
+ );
50
+ this.name = "ContactProvenanceLostError";
51
+ }
52
+ }
53
+
16
54
  /**
17
55
  * The transaction handle drizzle hands to a `db.transaction(cb)` callback. It
18
56
  * exposes the same `.select/.insert/.update/.execute/.query` surface as the
@@ -190,6 +228,93 @@ async function findByKey(tx: Tx, key: ResolveKey): Promise<ContactRow | null> {
190
228
  return null;
191
229
  }
192
230
 
231
+ /**
232
+ * ENGINE-INTERNAL provenance pin (see {@link resolveOrCreateContact}'s
233
+ * `contactId`). Resolve to the EXACT subject row by its unforgeable uuid PK and
234
+ * fold there — never value-probing, never minting. Serializes on the row PK via
235
+ * `FOR UPDATE`, so a concurrent collide-MERGE that soft-deletes this row as a
236
+ * loser blocks on / is observed by this pin (rather than racing the mismatched
237
+ * `external:value` vs `anonymous:value` advisory locks). If the row was merged
238
+ * away (soft-deleted), follow the server-authored merge-alias chain to the live
239
+ * SURVIVOR by row id — independent of alias kind/value, closing the post-merge
240
+ * anon-alias residual. A hard-deleted/unfollowable subject throws
241
+ * {@link ContactProvenanceLostError} (the caller drops the event, never mints).
242
+ */
243
+ async function resolveByContactId(
244
+ tx: Tx,
245
+ contactId: string,
246
+ ctx: { patch: Record<string, unknown>; hasPatch: boolean },
247
+ ): Promise<{
248
+ id: string;
249
+ resolvedKey: string;
250
+ created: boolean;
251
+ linked: boolean;
252
+ merged: boolean;
253
+ }> {
254
+ let row: ContactRow | null =
255
+ (
256
+ await tx
257
+ .select()
258
+ .from(contacts)
259
+ .where(eq(contacts.id, contactId))
260
+ .for("update")
261
+ .limit(1)
262
+ )[0] ?? null;
263
+ if (!row || row.deletedAt) {
264
+ row = await followToSurvivor(tx, contactId);
265
+ }
266
+ if (!row) throw new ContactProvenanceLostError(contactId);
267
+ const set: Record<string, unknown> = {
268
+ lastSeenAt: new Date(),
269
+ updatedAt: new Date(),
270
+ };
271
+ if (ctx.hasPatch) set.properties = mergePropertiesSql(ctx.patch);
272
+ await tx.update(contacts).set(set).where(eq(contacts.id, row.id));
273
+ return {
274
+ id: row.id,
275
+ resolvedKey: contactKey(row),
276
+ created: false,
277
+ linked: false,
278
+ merged: false,
279
+ };
280
+ }
281
+
282
+ /**
283
+ * Follow the server-authored merge-alias chain from a (soft-deleted loser)
284
+ * `contacts.id` to the live SURVIVOR row, re-locking each hop `FOR UPDATE`.
285
+ * Bounded (merge-of-a-merge) to a small cap. Keyed on `from_contact_id` — the
286
+ * unforgeable row id, never a value — so an attacker-plantable key can never
287
+ * steer it. Returns the live survivor or null (hard-deleted / chain broken).
288
+ */
289
+ async function followToSurvivor(
290
+ tx: Tx,
291
+ lostId: string,
292
+ ): Promise<ContactRow | null> {
293
+ let cursor = lostId;
294
+ for (let i = 0; i < 8; i++) {
295
+ const alias = (
296
+ await tx
297
+ .select({ contactId: contactAliases.contactId })
298
+ .from(contactAliases)
299
+ .where(eq(contactAliases.fromContactId, cursor))
300
+ .limit(1)
301
+ )[0];
302
+ if (!alias?.contactId) return null;
303
+ const survivor: ContactRow | undefined = (
304
+ await tx
305
+ .select()
306
+ .from(contacts)
307
+ .where(eq(contacts.id, alias.contactId))
308
+ .for("update")
309
+ .limit(1)
310
+ )[0];
311
+ if (!survivor) return null;
312
+ if (!survivor.deletedAt) return survivor;
313
+ cursor = alias.contactId;
314
+ }
315
+ return null;
316
+ }
317
+
193
318
  /**
194
319
  * Top-level property keys whose object value is DEEP-merged (one level) rather
195
320
  * than wholly replaced. The §2.1 shallow `||` contract clobbers a top-level key
@@ -341,6 +466,33 @@ export async function resolveOrCreateContact(opts: {
341
466
  anonymousId?: string;
342
467
  discordId?: string;
343
468
  contactProperties?: Record<string, unknown>;
469
+ /**
470
+ * PUBLISHABLE (browser, pk_) safety clamp (§Phase 1 GAP-1). When set, an
471
+ * anon-only write (no `userId`/`email`/`discordId`) may ONLY create or update
472
+ * its own anonymous-only contact: it is forbidden from filling-in-linking to,
473
+ * or merging with, any contact that already carries an `external_id`/`email`,
474
+ * and from driving a collide-MERGE — throwing {@link
475
+ * PublishableAnonymousMergeError}. The `anonymousId` is browser-readable
476
+ * (`get_distinct_id()`), so without this clamp a pk_ key could forge events as
477
+ * / poison a victim's identified contact via the anon resolution arm. The
478
+ * secret-key path NEVER sets this, so its behavior is byte-for-byte unchanged.
479
+ */
480
+ restrictToAnonymous?: boolean;
481
+ /**
482
+ * ENGINE-INTERNAL provenance — the subject contact's UNFORGEABLE row id
483
+ * (`contacts.id`, a server-minted uuid). Set ONLY by engine-internal re-emit
484
+ * sites that already resolved the subject (ingestEvent's downstream re-ingests,
485
+ * the feed mark/clear re-ingests, journey/bucket re-emits). When present (and
486
+ * uuid-shaped, and not a clamped publishable write), the resolver PINS to that
487
+ * exact row — never value-resolving, never minting — so an internal event whose
488
+ * `userId` is a contact's own canonical key (its anonymous_id/id round-tripping)
489
+ * folds back into that contact instead of minting a phantom `external_id` twin.
490
+ * NEVER settable from a request body: the public `/v1/events`/`/v1/contacts`/
491
+ * `/v1/feed` Zod schemas omit it and their handlers build the resolve call
492
+ * literally, so an attacker cannot forge provenance. Mutually exclusive with
493
+ * `restrictToAnonymous`.
494
+ */
495
+ contactId?: string;
344
496
  }): Promise<{
345
497
  id: string;
346
498
  /**
@@ -376,6 +528,17 @@ export async function resolveOrCreateContact(opts: {
376
528
  const email = opts.email ? normalizeEmail(opts.email) : undefined;
377
529
  const anonymousId = opts.anonymousId?.trim() || undefined;
378
530
  const discordId = opts.discordId?.trim() || undefined;
531
+ const contactId = opts.contactId?.trim() || undefined;
532
+ // §Phase 1 GAP-1: the publishable clamp only bites an ANON-ONLY write (the
533
+ // only shape a token-less pk_ key can produce — the gate 403s any
534
+ // email/userId without a verified userToken before we get here). An identified
535
+ // arm (token-authorized userId, or the secret path) is never clamped.
536
+ const restrictToAnonymous =
537
+ opts.restrictToAnonymous === true &&
538
+ !userId &&
539
+ !email &&
540
+ !discordId &&
541
+ !!anonymousId;
379
542
 
380
543
  const keys: ResolveKey[] = [];
381
544
  if (userId) keys.push({ kind: "external", value: userId });
@@ -394,6 +557,18 @@ export async function resolveOrCreateContact(opts: {
394
557
  const hasPatch = Object.keys(patch).length > 0;
395
558
 
396
559
  return db.transaction(async (tx) => {
560
+ // (−1) ENGINE-INTERNAL PROVENANCE PIN. A uuid-shaped `contactId` from a
561
+ // trusted internal re-emit pins resolution to that exact row (no value-key
562
+ // probe, no mint), so a contact's own canonical key round-tripping back as a
563
+ // `userId` folds into it instead of minting a phantom `external_id` twin.
564
+ // Gated on `!restrictToAnonymous` (mutually exclusive with the publishable
565
+ // clamp — a clamped pk_ write can never carry provenance) so it is never an
566
+ // attacker-reachable path. Runs BEFORE the value-key advisory locks: the pin
567
+ // serializes on the concrete row PK via `FOR UPDATE`, not on value locks.
568
+ if (contactId && UUID_REGEX.test(contactId) && !restrictToAnonymous) {
569
+ return resolveByContactId(tx, contactId, { patch, hasPatch });
570
+ }
571
+
397
572
  // (0) Advisory locks per key — serialize concurrent resolves on the same
398
573
  // identity so the INSERT race can't mint duplicates. Sorted to keep a stable
399
574
  // acquisition order across callers (deadlock-safe).
@@ -440,6 +615,14 @@ export async function resolveOrCreateContact(opts: {
440
615
  // --- CASE: fill-in-link (single existing row) ---
441
616
  const single = candidates[0];
442
617
  if (candidates.length === 1 && single) {
618
+ // §Phase 1 GAP-1: an anon-only publishable write resolved to an EXISTING
619
+ // contact that already carries an identified key (`external_id`/`email`)
620
+ // is a forge/poison attempt — the browser-readable anonymousId pointed at
621
+ // a victim. Refuse to fill-in-link / mutate it. (Resolving to its OWN
622
+ // anonymous-only contact — no external_id, no email — is allowed.)
623
+ if (restrictToAnonymous && (single.externalId || single.email)) {
624
+ throw new PublishableAnonymousMergeError();
625
+ }
443
626
  const { id, resolvedKey, mergedKeys, mergedIdentifiedKeys } =
444
627
  await fillInLink(tx, single, {
445
628
  userId,
@@ -461,6 +644,12 @@ export async function resolveOrCreateContact(opts: {
461
644
  }
462
645
 
463
646
  // --- CASE: collide-MERGE (2-3 distinct rows) ---
647
+ // §Phase 1 GAP-1: an anon-only publishable write must NEVER drive a merge —
648
+ // the browser-readable anonymousId would let an attacker fold two of a
649
+ // victim's contacts together (identity-graph corruption). Refuse.
650
+ if (restrictToAnonymous) {
651
+ throw new PublishableAnonymousMergeError();
652
+ }
464
653
  const { id, resolvedKey, mergedKeys, mergedIdentifiedKeys } =
465
654
  await mergeContacts(tx, candidates, {
466
655
  userId,