@hogsend/engine 0.66.0 → 0.67.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hogsend/engine",
3
- "version": "0.66.0",
3
+ "version": "0.67.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -53,19 +53,19 @@
53
53
  "svix": "^1.95.1",
54
54
  "winston": "^3.19.0",
55
55
  "zod": "^4.4.3",
56
- "@hogsend/attribution": "^0.66.0",
57
- "@hogsend/core": "^0.66.0",
58
- "@hogsend/db": "^0.66.0",
59
- "@hogsend/email": "^0.66.0",
60
- "@hogsend/plugin-posthog": "^0.66.0",
61
- "@hogsend/plugin-resend": "^0.66.0",
62
- "@hogsend/sms": "^0.66.0"
56
+ "@hogsend/attribution": "^0.67.0",
57
+ "@hogsend/core": "^0.67.0",
58
+ "@hogsend/db": "^0.67.0",
59
+ "@hogsend/email": "^0.67.0",
60
+ "@hogsend/plugin-posthog": "^0.67.0",
61
+ "@hogsend/plugin-resend": "^0.67.0",
62
+ "@hogsend/sms": "^0.67.0"
63
63
  },
64
64
  "optionalDependencies": {
65
- "@hogsend/plugin-apollo": "^0.66.0",
66
- "@hogsend/plugin-hogsend": "^0.66.0",
67
- "@hogsend/plugin-postmark": "^0.66.0",
68
- "@hogsend/plugin-twilio": "^0.66.0"
65
+ "@hogsend/plugin-apollo": "^0.67.0",
66
+ "@hogsend/plugin-hogsend": "^0.67.0",
67
+ "@hogsend/plugin-postmark": "^0.67.0",
68
+ "@hogsend/plugin-twilio": "^0.67.0"
69
69
  },
70
70
  "devDependencies": {
71
71
  "@types/node": "^22.15.3",
package/src/container.ts CHANGED
@@ -10,6 +10,7 @@ import type {
10
10
  DefinedConversion,
11
11
  DefinedFlag,
12
12
  DefinedFunnel,
13
+ DefinedReferral,
13
14
  EmailProvider,
14
15
  EnrichmentProvider,
15
16
  FunnelStageEntry,
@@ -125,6 +126,8 @@ import {
125
126
  getOperatorSetting,
126
127
  } from "./lib/operator-settings.js";
127
128
  import { createRedisSecondaryStorage, getRedis } from "./lib/redis.js";
129
+ import { ReferralRegistry } from "./lib/referral-registry.js";
130
+ import { setReferralRuntime } from "./lib/referral-runtime.js";
128
131
  import { sendResetPasswordEmail } from "./lib/reset-email.js";
129
132
  import { seedPostHogDestination } from "./lib/seed-posthog-destination.js";
130
133
  import { setSmsService } from "./lib/sms.js";
@@ -236,6 +239,16 @@ export interface HogsendClient {
236
239
  accountLinkHooks: AccountLinkHooks;
237
240
  /** Parsed + validated ACCOUNT_LINK_ALLOWED_ORIGINS. Empty array = none permitted. */
238
241
  accountLinkAllowedOrigins: string[];
242
+ /**
243
+ * The container-held registry of referral definitions (`defineReferral`),
244
+ * keyed by id. There is NO env preset and NO single active referral: a
245
+ * referral exists because it was authored in code, and a product may run
246
+ * several at once. EMPTY is the normal state of a deploy that never asked
247
+ * for referrals, and every wired site (the arrive touch, the bind at
248
+ * identity adoption, the qualify evaluation in `ingestEvent`, the conversion
249
+ * tree walk) is INERT while it stays empty.
250
+ */
251
+ referrals: ReferralRegistry;
239
252
  /**
240
253
  * The container-held registry of enrichment providers, keyed by `meta.id` —
241
254
  * the enrichment sibling of {@link smsProviders}. Empty when no enrichment
@@ -380,6 +393,13 @@ export interface HogsendClient {
380
393
  * (frequency cap).
381
394
  */
382
395
  defaults: HogsendDefaults;
396
+ /**
397
+ * Resolved browser-readable contact projection (`GET /v1/contacts/me`).
398
+ * `publicProperties` is an operator ALLOWLIST of exact `contacts.properties`
399
+ * keys; `exposeEmail` opts the address in. Both default to closed
400
+ * (`[]` / `false`), so a deploy that configures nothing exposes nothing.
401
+ */
402
+ contactsConfig: { publicProperties: string[]; exposeEmail: boolean };
383
403
  }
384
404
 
385
405
  export interface HogsendClientOptions {
@@ -486,6 +506,20 @@ export interface HogsendClientOptions {
486
506
  linkTracking?: boolean;
487
507
  linkHost?: string;
488
508
  };
509
+ /**
510
+ * What `GET /v1/contacts/me` may hand back to a browser.
511
+ *
512
+ * - `publicProperties` — EXACT `contacts.properties` keys the browser may
513
+ * read. No wildcard, no prefix match. Anything not listed is omitted.
514
+ * - `exposeEmail` — include the contact's email address in the response.
515
+ *
516
+ * Defaults are closed (`[]` / `false`): with no `contacts` option the route
517
+ * answers `{ identified: false, traits: {} }` for everyone.
518
+ */
519
+ contacts?: {
520
+ publicProperties?: string[];
521
+ exposeEmail?: boolean;
522
+ };
489
523
  /**
490
524
  * Account linking (Steam, Twitch, or your own `defineAccountLink` provider).
491
525
  * The engine owns the stateful flow (state tokens, the link store,
@@ -506,6 +540,14 @@ export interface HogsendClientOptions {
506
540
  */
507
541
  allowedOrigins?: string[];
508
542
  };
543
+ /**
544
+ * Referral programs, authored with `defineReferral` (PRD 05). Pass the SAME
545
+ * array in BOTH `index.ts` and `worker.ts`: the HTTP side runs the touch and
546
+ * the bind, the worker side runs `getReferralLink` inside journeys.
547
+ * Duplicate ids inside one array warn and last-writer-wins, like every other
548
+ * registry merge. Omitted ⇒ referrals are entirely inert.
549
+ */
550
+ referrals?: DefinedReferral[];
509
551
  /**
510
552
  * Enrichment (Refinement) is a first-class provider kind mirroring
511
553
  * {@link email}/{@link sms}. The engine owns the cohesive refinement
@@ -992,6 +1034,21 @@ export function createHogsendClient(
992
1034
  ...(opts.accountLinks?.allowedOrigins ?? []),
993
1035
  ]);
994
1036
  const accountLinkHooks: AccountLinkHooks = opts.accountLinks?.hooks ?? {};
1037
+ // Referrals: code-only, no env preset. Duplicate ids in one array are almost
1038
+ // certainly an authoring mistake, so warn (last-writer-wins, mirroring the
1039
+ // account-link providers merge just above).
1040
+ {
1041
+ const seenReferralIds = new Set<string>();
1042
+ for (const referral of opts.referrals ?? []) {
1043
+ if (seenReferralIds.has(referral.id)) {
1044
+ logger.warn(
1045
+ `referrals contains "${referral.id}" more than once — the last one wins (last-writer-wins on id)`,
1046
+ );
1047
+ }
1048
+ seenReferralIds.add(referral.id);
1049
+ }
1050
+ }
1051
+ const referrals = new ReferralRegistry(opts.referrals ?? []);
995
1052
  if (
996
1053
  accountLinkProviders.count() > 0 &&
997
1054
  accountLinkAllowedOrigins.length === 0
@@ -1753,6 +1810,21 @@ export function createHogsendClient(
1753
1810
  `Destination registry loaded: ${destinationRegistry.count()} destinations`,
1754
1811
  );
1755
1812
 
1813
+ // The referral runtime, for the sites that hold no container: the bind in
1814
+ // `lib/contacts.ts` (post-commit, library code), the qualify + conversion
1815
+ // walk in `lib/ingestion.ts`, and `getReferralLink` inside a durable journey
1816
+ // task. OPTIONAL by design — a deploy with no referrals installs an empty
1817
+ // registry and every one of those sites stays inert.
1818
+ setReferralRuntime({
1819
+ referrals,
1820
+ db,
1821
+ baseUrl: env.API_PUBLIC_URL,
1822
+ hatchet,
1823
+ registry,
1824
+ logger,
1825
+ ...(analytics ? { analytics } : {}),
1826
+ });
1827
+
1756
1828
  const client: HogsendClient = {
1757
1829
  env,
1758
1830
  logger,
@@ -1770,6 +1842,7 @@ export function createHogsendClient(
1770
1842
  accountLinkProviders,
1771
1843
  accountLinkHooks,
1772
1844
  accountLinkAllowedOrigins,
1845
+ referrals,
1773
1846
  enrichmentProviders,
1774
1847
  enrichmentProvider,
1775
1848
  crmProviders,
@@ -1795,6 +1868,10 @@ export function createHogsendClient(
1795
1868
  hatchet: opts.overrides?.hatchet ?? hatchet,
1796
1869
  clientJournal: opts.clientJournal ?? { entries: [] },
1797
1870
  defaults,
1871
+ contactsConfig: {
1872
+ publicProperties: opts.contacts?.publicProperties ?? [],
1873
+ exposeEmail: opts.contacts?.exposeEmail ?? false,
1874
+ },
1798
1875
  };
1799
1876
 
1800
1877
  // Boot-time reader for `hogsend connect posthog`'s persisted phc_: when no
package/src/index.ts CHANGED
@@ -495,6 +495,7 @@ export {
495
495
  type IdentityKind,
496
496
  identifiedContactFilter,
497
497
  type MergedLinkUnlink,
498
+ projectPublicContact,
498
499
  type ResolvePolicy,
499
500
  resolveContactNoCreate,
500
501
  resolveOrCreateContact,
@@ -700,6 +701,7 @@ export {
700
701
  // internal mechanics behind the /qr endpoint, not semver surface.
701
702
  export {
702
703
  IdempotencyConflictError,
704
+ LinkOwnershipError,
703
705
  type LinkType,
704
706
  type MintedLink,
705
707
  type MintLinkOptions,
@@ -765,6 +767,82 @@ export {
765
767
  getRedis,
766
768
  getRedisIfConnected,
767
769
  } from "./lib/redis.js";
770
+ // --- Referral intent layer (the ONE place the store is called AND emits) ---
771
+ export {
772
+ type BindReferralInput,
773
+ bindReferral,
774
+ type ConvertReferralInput,
775
+ convertReferral,
776
+ type QualifyReferralInput,
777
+ qualifyReferral,
778
+ qualifyReferralsForEvent,
779
+ REFERRAL_TREE_MAX_DEPTH,
780
+ type ReferralIntentHandles,
781
+ type TouchReferralInput,
782
+ type TouchReferralResult,
783
+ touchReferral,
784
+ } from "./lib/referral-intent.js";
785
+ // --- Referrals: definition wiring + the journey-safe link mint ---
786
+ // `defineReferral` itself lives in `@hogsend/core` (re-exported from the core
787
+ // barrel). Pass definitions to `createHogsendClient({ referrals: [...] })` in
788
+ // BOTH index.ts and worker.ts; `client.referrals` is the resolved registry.
789
+ export {
790
+ type GetReferralLinkOptions,
791
+ getReferralLink,
792
+ type ReferralLink,
793
+ type ReferralLinkContainer,
794
+ } from "./lib/referral-link.js";
795
+ export { ReferralRegistry } from "./lib/referral-registry.js";
796
+ // --- Referral REPORT (report-time model/window/depth/weights, PRD 05 §5.3) ---
797
+ export {
798
+ type CurrencyValue,
799
+ getReferralReport,
800
+ getReferralTree,
801
+ InvalidWindowError,
802
+ NO_CURRENCY,
803
+ parseWindowMs,
804
+ REFERRAL_MODELS,
805
+ REFERRAL_REPORT_MAX_DEPTH,
806
+ type ReferralBeneficiary,
807
+ type ReferralModel,
808
+ type ReferralReport,
809
+ type ReferralTreeLevel,
810
+ type ReferralTreeNode,
811
+ resolveLevelWeights,
812
+ } from "./lib/referral-report.js";
813
+ export {
814
+ getReferralRuntime,
815
+ type ReferralRuntime,
816
+ resetReferralRuntime,
817
+ setReferralRuntime,
818
+ } from "./lib/referral-runtime.js";
819
+ // --- Referral store (the ONE writer of referral_touches; NEVER emits) ---
820
+ // The store returns mutation FACTS; the intent layer emits `referral.*`
821
+ // outbound and re-ingests for journeys, side by side (PRD 05 §6). Pinned by
822
+ // `lib/referrals-no-emit.test.ts`.
823
+ export {
824
+ type BindTouchesInput,
825
+ type BindTouchesResult,
826
+ bindTouches,
827
+ type ListTouchesInput,
828
+ listTouchesForReferee,
829
+ listTouchesForReferrer,
830
+ type QualifyTouchInput,
831
+ type QualifyTouchResult,
832
+ qualifyTouch,
833
+ REFERRAL_IDEMPOTENCY_PROPERTY,
834
+ REFERRAL_VETO_REASON_PROPERTY,
835
+ type RecordTouchInput,
836
+ type RecordTouchResult,
837
+ type ReferralRejectReason,
838
+ type ReferralTouchRecord,
839
+ type ReferralTouchSource,
840
+ type ReferralTouchStatus,
841
+ type RejectTouchInput,
842
+ type RejectTouchResult,
843
+ recordTouch,
844
+ rejectTouch,
845
+ } from "./lib/referrals.js";
768
846
  // --- Refinement (`refineContact` — a STANDALONE import, never on `ctx`) ---
769
847
  export {
770
848
  REFINE_EVENT,
@@ -434,6 +434,38 @@ export function serializeContact(
434
434
  };
435
435
  }
436
436
 
437
+ /**
438
+ * The BROWSER-safe projection of a contact (`GET /v1/contacts/me`). Applies the
439
+ * operator allowlist: only EXACT `publicProperties` keys survive, and `email`
440
+ * is present only when `exposeEmail` is on. A missing row projects to
441
+ * `{ identified: false, traits: {} }` — the route never 404s, so the absence of
442
+ * a contact is indistinguishable from an empty allowlist.
443
+ *
444
+ * `identified` means the row carries a real identity (`externalId` or `email`);
445
+ * an anonymous-only row reads its own traits but is NOT identified.
446
+ */
447
+ export function projectPublicContact(
448
+ row: ContactRow | null | undefined,
449
+ config: { publicProperties: string[]; exposeEmail: boolean },
450
+ ): {
451
+ identified: boolean;
452
+ traits: Record<string, unknown>;
453
+ email?: string | null;
454
+ } {
455
+ const props = (row?.properties ?? {}) as Record<string, unknown>;
456
+ const traits: Record<string, unknown> = {};
457
+ if (row) {
458
+ for (const key of config.publicProperties) {
459
+ if (Object.hasOwn(props, key)) traits[key] = props[key];
460
+ }
461
+ }
462
+ return {
463
+ identified: Boolean(row && (row.externalId || row.email)),
464
+ traits,
465
+ ...(config.exposeEmail ? { email: row?.email ?? null } : {}),
466
+ };
467
+ }
468
+
437
469
  export function serializePrefs(row: typeof emailPreferences.$inferSelect) {
438
470
  return {
439
471
  id: row.id,
@@ -1500,6 +1532,44 @@ async function resolveContactShared(
1500
1532
  // Only the singleton-COLLISION soft-unlinks are here. The repoint that moves
1501
1533
  // the loser's surviving links to the survivor is deliberately silent — see
1502
1534
  // the note on step 4 of `foldLinkedAccounts`.
1535
+ // REFERRAL BIND (PRD 05 stage 3), post-commit for the same reason the
1536
+ // account-link emit above is: `bindReferral` announces `referral.bound` on
1537
+ // both planes, and a resolve that rolled back must never have announced a
1538
+ // bind that never happened. This is the ONE bind site precisely because
1539
+ // `resolveContactShared` is the ONE owner of every `resolveOrCreateContact`
1540
+ // / `resolveContactNoCreate` call.
1541
+ //
1542
+ // The keys scanned are every key this resolve just made this contact's:
1543
+ // the resolved canonical key (which the create arm's `adoptOrphanHistory`
1544
+ // just stamped history under), the anon key supplied by the identify call,
1545
+ // and any key a merge absorbed. `bindTouches` is a no-op for a key with no
1546
+ // unbound touch, so the extra scans cost one indexed lookup on a partial
1547
+ // index built for exactly this query.
1548
+ if (resolved.id !== null) {
1549
+ const boundContactId = resolved.id;
1550
+ const keys = new Set<string>([resolved.resolvedKey]);
1551
+ if (opts.anonymousId) keys.add(opts.anonymousId);
1552
+ for (const key of resolved.mergedKeys ?? []) keys.add(key);
1553
+ // AWAITED, not fire-and-forget: the same ingest that identifies the
1554
+ // referee may ALSO be the qualify event (a `signup` carrying the email),
1555
+ // and `ingestEvent`'s qualify hook runs after this resolve and reads
1556
+ // `status = 'bound'`. A detached bind would lose that race and the touch
1557
+ // would sit at `touched` until the next qualifying event. Errors are still
1558
+ // swallowed with an attributed log: an identify must never fail because a
1559
+ // referral edge could not be stamped.
1560
+ try {
1561
+ const { bindReferral } = await import("./referral-intent.js");
1562
+ for (const refereeKey of keys) {
1563
+ await bindReferral({ db, refereeKey, contactId: boundContactId });
1564
+ }
1565
+ } catch (error: unknown) {
1566
+ logger.warn("referral bind failed", {
1567
+ contactId: boundContactId,
1568
+ error: error instanceof Error ? error.message : String(error),
1569
+ });
1570
+ }
1571
+ }
1572
+
1503
1573
  if (resolved.linkUnlinks && resolved.linkUnlinks.length > 0) {
1504
1574
  emitAccountUnlinked(db, resolved.linkUnlinks);
1505
1575
  // THE JOURNEY PLANE, beside the outbound one (PRD 08 T5). TWO DIFFERENT
@@ -802,6 +802,38 @@ export async function ingestEvent(opts: {
802
802
  }
803
803
  : null;
804
804
 
805
+ // (5b-referral) REFERRAL QUALIFY (PRD 05 §6 qualify). Does THIS event
806
+ // promote one of this contact's BOUND touches? Cheap on a miss (one map
807
+ // lookup keyed by `qualify.event`), so it runs on every ingested event, and
808
+ // entirely inert with no referrals registered.
809
+ //
810
+ // Gated on `contactId !== null` for the same reason site 5 is: a touch can
811
+ // only qualify once it is BOUND, and a bound touch by definition has a
812
+ // referee CONTACT — a refused resolve has no contact to look one up for.
813
+ // Best-effort: the event is already durable.
814
+ if (insertedRow && contactId !== null) {
815
+ try {
816
+ const { qualifyReferralsForEvent } = await import("./referral-intent.js");
817
+ await qualifyReferralsForEvent({
818
+ handles: {
819
+ db,
820
+ hatchet,
821
+ registry,
822
+ logger,
823
+ ...(opts.analytics ? { analytics: opts.analytics } : {}),
824
+ },
825
+ event: event.event,
826
+ eventProperties: event.eventProperties,
827
+ contactId,
828
+ });
829
+ } catch (err) {
830
+ logger.warn("referral qualify evaluation failed", {
831
+ event: event.event,
832
+ error: err instanceof Error ? err.message : String(err),
833
+ });
834
+ }
835
+ }
836
+
805
837
  // (5c) Conversion-point evaluation (plan §5.1) — the unique
806
838
  // (definition, event) index makes any replay a no-op.
807
839
  //
@@ -869,6 +901,35 @@ export async function ingestEvent(opts: {
869
901
  error: err instanceof Error ? err.message : String(err),
870
902
  });
871
903
  }
904
+
905
+ // THE REFERRAL TREE (PRD 05 §6 convert). Beside the attribution
906
+ // ledger, never inside it: the ledger answers "which touchpoints get
907
+ // credit", the tree answers "which PEOPLE get told". Announces
908
+ // `referral.converted` to the direct referrer and
909
+ // `referral.tree_converted` to each ancestor to depth 5, with `level`
910
+ // as a FACT on the event so a reward journey filters on it. Inert
911
+ // with no referrals registered; isolated so a tree failure can never
912
+ // cost a conversion.
913
+ try {
914
+ const { convertReferral } = await import("./referral-intent.js");
915
+ await convertReferral({
916
+ db,
917
+ hatchet,
918
+ registry,
919
+ logger,
920
+ ...(opts.analytics ? { analytics: opts.analytics } : {}),
921
+ contactId,
922
+ conversionId: firedConversion.conversionId,
923
+ value: firedConversion.value ?? null,
924
+ currency: firedConversion.currency ?? null,
925
+ occurredAt: insertedRow.occurredAt,
926
+ });
927
+ } catch (err) {
928
+ logger.warn("referral conversion walk failed", {
929
+ conversionId: firedConversion.conversionId,
930
+ error: err instanceof Error ? err.message : String(err),
931
+ });
932
+ }
872
933
  }
873
934
  } catch (err) {
874
935
  logger.warn("Conversion evaluation failed", {
package/src/lib/links.ts CHANGED
@@ -16,9 +16,26 @@ import { and, eq, isNull, ne, or, sql } from "drizzle-orm";
16
16
  * SHARE-SAFE INVARIANT: a link is identity-bearing (carries a `distinctId` the
17
17
  * click can stitch + may mint a single-use `hs_t`) ONLY when `type: "personal"`
18
18
  * AND an explicit `distinctId` is passed. A `"public"` link NEVER carries a
19
- * person token — a shared/reshared public link attributes by campaign only.
19
+ * person token - a shared/reshared public link attributes by campaign only.
20
+ * `"shared"` (a referral link) is owned by a person and clicked by SOMEONE
21
+ * ELSE, so it sits on the PUBLIC side of that invariant: it attributes to
22
+ * `ownerContactId` and stitches nobody.
20
23
  */
21
- export type LinkType = "personal" | "public";
24
+ export type LinkType = "personal" | "public" | "shared";
25
+
26
+ /**
27
+ * Thrown when the `shared` link ownership invariant is broken (PRD 05 5.2):
28
+ * a `shared` link with no `ownerContactId` credits nobody, and an
29
+ * `ownerContactId` on a `personal`/`public` link is a silent no-op that reads
30
+ * as if attribution were configured. Both are authoring errors, so they throw
31
+ * at mint time rather than minting a link that quietly does nothing.
32
+ */
33
+ export class LinkOwnershipError extends Error {
34
+ constructor(message: string) {
35
+ super(message);
36
+ this.name = "LinkOwnershipError";
37
+ }
38
+ }
22
39
 
23
40
  export interface MintLinkOptions {
24
41
  db: Database;
@@ -28,8 +45,22 @@ export interface MintLinkOptions {
28
45
  baseUrl: string;
29
46
  /** Originating channel: "studio" | "discord" | "sms" | "referral" | … (open). */
30
47
  source: string;
31
- /** "personal" (1:1, identity-bearing) | "public" (shareable). Default "public". */
48
+ /**
49
+ * "personal" (1:1, identity-bearing) | "public" (shareable) | "shared"
50
+ * (owned by a person, clicked by others - a referral link). Default
51
+ * "public".
52
+ */
32
53
  type?: LinkType;
54
+ /**
55
+ * The contact this link earns credit FOR. REQUIRED for `type: "shared"`,
56
+ * forbidden on `personal`/`public` (see {@link LinkOwnershipError}).
57
+ *
58
+ * This is an ATTRIBUTION field, never an identity one: it is deliberately
59
+ * not `distinctId`, because a referral link's clicker must never be stitched
60
+ * to its owner. Reusing `personal` for this would identify every referee AS
61
+ * the referrer, which is precisely the share-safe invariant's failure mode.
62
+ */
63
+ ownerContactId?: string;
33
64
  /** Operator-facing name (Studio list). */
34
65
  label?: string;
35
66
  /**
@@ -40,8 +71,16 @@ export interface MintLinkOptions {
40
71
  /** UTM-style campaign grouping (public links). */
41
72
  campaign?: string;
42
73
  /**
43
- * The canonical contact key a click should stitch — honoured ONLY for
44
- * `type: "personal"`; dropped for public links (the share-safe invariant).
74
+ * The `defineReferral` id this link belongs to (`getReferralLink` sets it).
75
+ * Stored on the row so a CLICK can find the DEFINITION that owns it - the
76
+ * hooks, the bind window and the qualify rule - without inferring it from
77
+ * `campaign`, which is operator-facing grouping and may be absent or shared.
78
+ */
79
+ referralId?: string;
80
+ /**
81
+ * The canonical contact key a click should stitch - honoured ONLY for
82
+ * `type: "personal"`; dropped for public AND shared links (the share-safe
83
+ * invariant).
45
84
  */
46
85
  distinctId?: string;
47
86
  /** The admin actor who minted it (Studio). */
@@ -81,6 +120,10 @@ export interface MintedLink {
81
120
  slug: string | null;
82
121
  /** The vanity short URL (`${baseUrl}/l/:slug`), if a slug was minted. */
83
122
  vanityUrl: string | null;
123
+ /** The link's type, as stored. */
124
+ type: LinkType;
125
+ /** The credited owner for a `shared` link; null for personal/public. */
126
+ ownerContactId: string | null;
84
127
  /**
85
128
  * True when the mint RECOVERED an existing live link (same slug or
86
129
  * idempotencyKey + same destination) instead of inserting a new one.
@@ -290,7 +333,12 @@ export function assertHttpUrl(url: string): void {
290
333
  async function recoverExistingLink(
291
334
  db: Database,
292
335
  baseUrl: string,
293
- row: { id: string; slug: string | null },
336
+ row: {
337
+ id: string;
338
+ slug: string | null;
339
+ type: string;
340
+ ownerContactId: string | null;
341
+ },
294
342
  ): Promise<MintedLink | null> {
295
343
  const [tracked] = await db
296
344
  .select({ id: sql<string | null>`min(${trackedLinks.id}::text)` })
@@ -304,6 +352,8 @@ async function recoverExistingLink(
304
352
  url: `${baseUrl}/v1/t/c/${trackedLinkId}`,
305
353
  slug: row.slug,
306
354
  vanityUrl: row.slug ? vanityUrlFor(baseUrl, row.slug) : null,
355
+ type: row.type as LinkType,
356
+ ownerContactId: row.ownerContactId,
307
357
  existing: true,
308
358
  };
309
359
  }
@@ -314,7 +364,25 @@ export async function mintLink(opts: MintLinkOptions): Promise<MintedLink> {
314
364
  throw new Error("mintLink: slug and idempotencyKey are mutually exclusive");
315
365
  }
316
366
  const type: LinkType = opts.type ?? "public";
317
- // A public link must NEVER carry a person token — drop any distinctId.
367
+ // THE OWNERSHIP INVARIANT (PRD 05 5.2). Loud at mint time, because both
368
+ // halves fail SILENTLY otherwise: an unowned shared link records touches
369
+ // that credit nobody, and an owner set on a public link looks like
370
+ // attribution is wired when nothing reads it.
371
+ const ownerContactId = opts.ownerContactId ?? null;
372
+ if (type === "shared" && !ownerContactId) {
373
+ throw new LinkOwnershipError(
374
+ 'mintLink: type "shared" requires ownerContactId - a shared link is ' +
375
+ "owned by the person it credits",
376
+ );
377
+ }
378
+ if (type !== "shared" && ownerContactId) {
379
+ throw new LinkOwnershipError(
380
+ `mintLink: ownerContactId is only valid for type "shared", got "${type}"`,
381
+ );
382
+ }
383
+ // Only a PERSONAL link carries a person token. A public link must never
384
+ // carry one, and neither must a shared link: it is clicked by someone other
385
+ // than its owner, so stitching would identify every referee as the referrer.
318
386
  const distinctId = type === "personal" ? (opts.distinctId ?? null) : null;
319
387
  const slug = opts.slug !== undefined ? normalizeSlug(opts.slug) : null;
320
388
 
@@ -335,8 +403,10 @@ export async function mintLink(opts: MintLinkOptions): Promise<MintedLink> {
335
403
  description: opts.description ?? null,
336
404
  appendRef: opts.appendRef ?? false,
337
405
  campaign: opts.campaign ?? null,
406
+ referralId: opts.referralId ?? null,
338
407
  source: opts.source,
339
408
  distinctId,
409
+ ownerContactId,
340
410
  createdBy: opts.createdBy ?? null,
341
411
  idempotencyKey: opts.idempotencyKey ?? null,
342
412
  });
@@ -360,13 +430,19 @@ export async function mintLink(opts: MintLinkOptions): Promise<MintedLink> {
360
430
  .from(links)
361
431
  .where(and(eq(links.slug, slug), isNull(links.archivedAt)))
362
432
  .limit(1);
363
- if (row && row.originalUrl === opts.url && row.type === type) {
433
+ if (
434
+ row &&
435
+ row.originalUrl === opts.url &&
436
+ row.type === type &&
437
+ row.ownerContactId === ownerContactId
438
+ ) {
364
439
  const recovered = await recoverExistingLink(opts.db, opts.baseUrl, row);
365
440
  if (recovered) return recovered;
366
441
  }
367
442
  // Slug held by an ARCHIVED link (the live lookup misses — archived
368
- // links keep their slug reserved), a different destination, or a
369
- // different type → conflict.
443
+ // links keep their slug reserved), a different destination, a
444
+ // different type, or a different owner (two referrers whose slugFrom
445
+ // collide must NOT share one link) → conflict.
370
446
  throw new SlugTakenError(slug);
371
447
  }
372
448
  if (opts.idempotencyKey && isIdempotencyKeyViolation(err)) {
@@ -380,7 +456,12 @@ export async function mintLink(opts: MintLinkOptions): Promise<MintedLink> {
380
456
  ),
381
457
  )
382
458
  .limit(1);
383
- if (row && row.originalUrl === opts.url) {
459
+ if (
460
+ row &&
461
+ row.originalUrl === opts.url &&
462
+ row.type === type &&
463
+ row.ownerContactId === ownerContactId
464
+ ) {
384
465
  const recovered = await recoverExistingLink(opts.db, opts.baseUrl, row);
385
466
  if (recovered) return recovered;
386
467
  }
@@ -398,6 +479,8 @@ export async function mintLink(opts: MintLinkOptions): Promise<MintedLink> {
398
479
  url: `${opts.baseUrl}/v1/t/c/${trackedLinkId}`,
399
480
  slug,
400
481
  vanityUrl: slug ? vanityUrlFor(opts.baseUrl, slug) : null,
482
+ type,
483
+ ownerContactId,
401
484
  existing: false,
402
485
  };
403
486
  }