@hogsend/engine 0.44.0 → 0.45.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.44.0",
3
+ "version": "0.45.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -15,6 +15,8 @@
15
15
  "./worker": "./src/worker.ts",
16
16
  "./auth": "./src/lib/auth.ts",
17
17
  "./create-admin": "./src/lib/create-admin.ts",
18
+ "./api-key-hash": "./src/lib/api-key-hash.ts",
19
+ "./posthog-scopes": "./src/lib/posthog-scopes.ts",
18
20
  "./mcp/authoring-guide": "./src/mcp/authoring-guide.ts",
19
21
  "./package.json": "./package.json"
20
22
  },
@@ -49,17 +51,17 @@
49
51
  "svix": "^1.95.1",
50
52
  "winston": "^3.19.0",
51
53
  "zod": "^4.4.3",
52
- "@hogsend/attribution": "^0.44.0",
53
- "@hogsend/core": "^0.44.0",
54
- "@hogsend/db": "^0.44.0",
55
- "@hogsend/email": "^0.44.0",
56
- "@hogsend/plugin-posthog": "^0.44.0",
57
- "@hogsend/plugin-resend": "^0.44.0",
58
- "@hogsend/sms": "^0.44.0"
54
+ "@hogsend/attribution": "^0.45.0",
55
+ "@hogsend/core": "^0.45.0",
56
+ "@hogsend/db": "^0.45.0",
57
+ "@hogsend/email": "^0.45.0",
58
+ "@hogsend/plugin-posthog": "^0.45.0",
59
+ "@hogsend/plugin-resend": "^0.45.0",
60
+ "@hogsend/sms": "^0.45.0"
59
61
  },
60
62
  "optionalDependencies": {
61
- "@hogsend/plugin-postmark": "^0.44.0",
62
- "@hogsend/plugin-twilio": "^0.44.0"
63
+ "@hogsend/plugin-postmark": "^0.45.0",
64
+ "@hogsend/plugin-twilio": "^0.45.0"
63
65
  },
64
66
  "devDependencies": {
65
67
  "@types/node": "^22.15.3",
package/src/container.ts CHANGED
@@ -65,7 +65,10 @@ import {
65
65
  wrapLegacyAnalyticsService,
66
66
  } from "./lib/analytics-adapter.js";
67
67
  import { AnalyticsProviderRegistry } from "./lib/analytics-provider-registry.js";
68
- import { analyticsProvidersFromEnv } from "./lib/analytics-providers-from-env.js";
68
+ import {
69
+ analyticsProvidersFromEnv,
70
+ buildStoredPosthogProvider,
71
+ } from "./lib/analytics-providers-from-env.js";
69
72
  import {
70
73
  setAnalytics,
71
74
  setAnalyticsEventMirror,
@@ -111,6 +114,7 @@ import { SmsProviderRegistry } from "./lib/sms-provider-registry.js";
111
114
  import { smsProvidersFromEnv } from "./lib/sms-providers-from-env.js";
112
115
  import type { SmsService } from "./lib/sms-service-types.js";
113
116
  import { prepareTrackedHtml } from "./lib/tracking.js";
117
+ import { createUnconfiguredEmailProvider } from "./lib/unconfigured-email-provider.js";
114
118
  import { synthesizeChannelLists } from "./lists/channels.js";
115
119
  import {
116
120
  type DefinedList,
@@ -886,16 +890,30 @@ export function createHogsendClient(
886
890
  // SINGLE place Resend is constructed from env — so resolution is just a
887
891
  // registry lookup that throws if the active id resolves to nothing. NEVER
888
892
  // silently fall back for a non-resend id.
889
- const activeId =
890
- opts.email?.defaultProvider ?? env.EMAIL_PROVIDER ?? "resend";
891
- const provider = emailProviders.get(activeId);
893
+ const explicitId = opts.email?.defaultProvider ?? env.EMAIL_PROVIDER;
894
+ const activeId = explicitId ?? "resend";
895
+ let provider = emailProviders.get(activeId);
892
896
 
893
897
  if (!provider) {
894
- throw new Error(
895
- `email provider "${activeId}" is not registered (registered: ${emailProviders
896
- .getAll()
897
- .map((p) => p.meta?.id ?? "resend")
898
- .join(", ")})`,
898
+ // An EXPLICITLY requested id that resolves to nothing is a config error —
899
+ // throw (typo safety). So is an implicit default when OTHER providers are
900
+ // registered (e.g. Postmark-only without EMAIL_PROVIDER=postmark).
901
+ if (explicitId !== undefined || emailProviders.count() > 0) {
902
+ throw new Error(
903
+ `email provider "${activeId}" is not registered (registered: ${emailProviders
904
+ .getAll()
905
+ .map((p) => p.meta?.id ?? "resend")
906
+ .join(", ")})`,
907
+ );
908
+ }
909
+ // Zero providers + nothing requested = a fresh app without email creds
910
+ // yet. Boot INERT instead of crashing (mirrors the SMS channel's
911
+ // operator-opt-in stub): Studio, ingest and non-email journeys all work;
912
+ // each send fails per-call with an actionable message. The stub is NOT
913
+ // registered in the registry, so no webhook route resolves it.
914
+ provider = createUnconfiguredEmailProvider();
915
+ logger.warn(
916
+ "no email provider configured — email sends will fail until RESEND_API_KEY (or POSTMARK_SERVER_TOKEN with EMAIL_PROVIDER=postmark) is set. Everything else works without one.",
899
917
  );
900
918
  }
901
919
 
@@ -909,7 +927,7 @@ export function createHogsendClient(
909
927
  logger.warn(
910
928
  `provider ${
911
929
  provider.meta?.id ?? "resend"
912
- } reports account-level native tracking ON; disable it in the dashboard — first-party tracking is Hogsend's source of truth.`,
930
+ } can't disable its native open/click tracking per-send (account-level setting) — if it's enabled in the provider dashboard, turn it off there; first-party tracking is Hogsend's source of truth.`,
913
931
  );
914
932
  }
915
933
 
@@ -1389,7 +1407,7 @@ export function createHogsendClient(
1389
1407
  `Destination registry loaded: ${destinationRegistry.count()} destinations`,
1390
1408
  );
1391
1409
 
1392
- return {
1410
+ const client: HogsendClient = {
1393
1411
  env,
1394
1412
  logger,
1395
1413
  db,
@@ -1421,4 +1439,35 @@ export function createHogsendClient(
1421
1439
  clientJournal: opts.clientJournal ?? { entries: [] },
1422
1440
  defaults,
1423
1441
  };
1442
+
1443
+ // Boot-time reader for `hogsend connect posthog`'s persisted phc_: when no
1444
+ // provider resolved AND no POSTHOG_API_KEY is set, activate PostHog from the
1445
+ // stored derived credential (async, fire-and-forget — the container is built
1446
+ // synchronously; a failure leaves the container exactly as booted). ALL
1447
+ // activation effects live here, in one block, so "who mutates what" has a
1448
+ // single answer. Skipped under NODE_ENV=test so suites stay hermetic.
1449
+ if (!analytics && !env.POSTHOG_API_KEY && env.NODE_ENV !== "test") {
1450
+ void buildStoredPosthogProvider({ env, db, logger })
1451
+ .then((provider) => {
1452
+ if (!provider) return;
1453
+ // Someone claimed the slot while we read (consumer provider, race).
1454
+ if (client.analytics || analyticsProviders.get("posthog")) return;
1455
+ analyticsProviders.register(provider);
1456
+ client.analytics = provider;
1457
+ setAnalytics(provider);
1458
+ // Rebuild the boot closure that captured `analytics: undefined` so
1459
+ // identity merges propagate to the newly-live provider too.
1460
+ client.identity = createIdentityService({
1461
+ db,
1462
+ analytics: provider,
1463
+ logger,
1464
+ });
1465
+ logger.info(
1466
+ 'analytics provider "posthog" activated from the stored `hogsend connect posthog` credential — outbound capture is live without POSTHOG_API_KEY.',
1467
+ );
1468
+ })
1469
+ .catch(() => {});
1470
+ }
1471
+
1472
+ return client;
1424
1473
  }
@@ -2,11 +2,13 @@ import type { AnalyticsProvider } from "@hogsend/core";
2
2
  import type { Database } from "@hogsend/db";
3
3
  import {
4
4
  createPostHogProvider,
5
+ deriveIngestHost,
5
6
  type PostHogAuthTokenAccessor,
6
7
  } from "@hogsend/plugin-posthog";
7
8
  import type { env as envSchema } from "../env.js";
8
9
  import type { Logger } from "./logger.js";
9
10
  import { createTokenManager } from "./oauth-token-manager.js";
11
+ import { getDerivedCredential } from "./provider-credentials.js";
10
12
  import { getRedis } from "./redis.js";
11
13
 
12
14
  /**
@@ -28,52 +30,113 @@ export function analyticsProvidersFromEnv(
28
30
  const providers: AnalyticsProvider[] = [];
29
31
 
30
32
  if (env.POSTHOG_API_KEY) {
31
- // Token-manager-backed accessor: the manager re-checks the DB (30s
32
- // negative cache), so a credential stored at RUNTIME via
33
- // `hogsend connect posthog` comes alive without a restart.
34
- let authToken: PostHogAuthTokenAccessor | undefined;
35
- if (deps?.db) {
36
- const tokenManager = createTokenManager({
37
- db: deps.db,
38
- providerId: "posthog",
39
- logger: deps.logger,
40
- });
41
- // Load-only warm-up (no refresh, never blocks construction). The
42
- // person-reads nudge logs HERE, after the load settles — the container
43
- // can't log it truthfully at boot because capabilities resolve async
44
- // for OAuth-capable providers (a connected instance would otherwise
45
- // log "DISABLED" once on every boot).
46
- const personalKeySet = Boolean(env.POSTHOG_PERSONAL_API_KEY);
47
- void tokenManager
48
- .prime()
49
- .then(() => {
50
- if (!personalKeySet && tokenManager.credentialState() !== "present") {
51
- deps.logger?.info(
52
- 'analytics provider "posthog" has person reads DISABLED — ' +
53
- "timezone resolution falls back to contact properties. Set " +
54
- "POSTHOG_PERSONAL_API_KEY or run `hogsend connect posthog`. " +
55
- "Docs: https://hogsend.com/docs/guides/analytics-access",
56
- );
57
- }
58
- })
59
- .catch(() => {});
60
- authToken = {
61
- getToken: () => tokenManager.getAccessToken(),
62
- isAvailable: () => tokenManager.credentialState() === "present",
63
- };
64
- }
65
33
  providers.push(
66
- createPostHogProvider({
67
- apiKey: env.POSTHOG_API_KEY,
68
- host: env.POSTHOG_HOST,
69
- personalApiKey: env.POSTHOG_PERSONAL_API_KEY,
70
- projectId: env.POSTHOG_PROJECT_ID,
71
- privateHost: env.POSTHOG_PRIVATE_HOST,
72
- redis: getRedis(),
73
- authToken,
74
- }),
34
+ buildPosthogProvider(env, deps, { apiKey: env.POSTHOG_API_KEY }),
75
35
  );
76
36
  }
77
37
 
78
38
  return providers;
79
39
  }
40
+
41
+ /**
42
+ * Construct the PostHog provider with the token-manager-backed OAuth accessor.
43
+ * Shared by the env preset above (`POSTHOG_API_KEY`) and the stored-credential
44
+ * activation below (`hogsend connect posthog`'s persisted phc_). Env values
45
+ * win over `source` overrides so a hand-set var still takes precedence.
46
+ */
47
+ function buildPosthogProvider(
48
+ env: typeof envSchema,
49
+ deps: { db?: Database; logger?: Logger } | undefined,
50
+ source: {
51
+ apiKey: string;
52
+ host?: string;
53
+ projectId?: string;
54
+ privateHost?: string;
55
+ },
56
+ ): AnalyticsProvider {
57
+ // Token-manager-backed accessor: the manager re-checks the DB (30s
58
+ // negative cache), so a credential stored at RUNTIME via
59
+ // `hogsend connect posthog` comes alive without a restart.
60
+ let authToken: PostHogAuthTokenAccessor | undefined;
61
+ if (deps?.db) {
62
+ const tokenManager = createTokenManager({
63
+ db: deps.db,
64
+ providerId: "posthog",
65
+ logger: deps.logger,
66
+ });
67
+ // Load-only warm-up (no refresh, never blocks construction). The
68
+ // person-reads nudge logs HERE, after the load settles — the container
69
+ // can't log it truthfully at boot because capabilities resolve async
70
+ // for OAuth-capable providers (a connected instance would otherwise
71
+ // log "DISABLED" once on every boot).
72
+ const personalKeySet = Boolean(env.POSTHOG_PERSONAL_API_KEY);
73
+ void tokenManager
74
+ .prime()
75
+ .then(() => {
76
+ if (!personalKeySet && tokenManager.credentialState() !== "present") {
77
+ deps.logger?.info(
78
+ 'analytics provider "posthog" has person reads DISABLED — ' +
79
+ "timezone resolution falls back to contact properties. Set " +
80
+ "POSTHOG_PERSONAL_API_KEY or run `hogsend connect posthog`. " +
81
+ "Docs: https://hogsend.com/docs/guides/analytics-access",
82
+ );
83
+ }
84
+ })
85
+ .catch(() => {});
86
+ authToken = {
87
+ getToken: () => tokenManager.getAccessToken(),
88
+ isAvailable: () => tokenManager.credentialState() === "present",
89
+ };
90
+ }
91
+ return createPostHogProvider({
92
+ apiKey: source.apiKey,
93
+ host: env.POSTHOG_HOST ?? source.host,
94
+ personalApiKey: env.POSTHOG_PERSONAL_API_KEY,
95
+ projectId: env.POSTHOG_PROJECT_ID ?? source.projectId,
96
+ privateHost: env.POSTHOG_PRIVATE_HOST ?? source.privateHost,
97
+ redis: getRedis(),
98
+ authToken,
99
+ });
100
+ }
101
+
102
+ /**
103
+ * Boot-time reader for the phc_ persisted by `hogsend connect posthog`
104
+ * (provider_credentials kind="derived", `projectApiKey`): a PURE builder —
105
+ * reads the stored credential and constructs the PostHog provider from it, or
106
+ * resolves null when there is nothing stored (or it can't be decrypted, which
107
+ * must behave exactly like "unconfigured"). ALL activation side effects
108
+ * (registry, `client.analytics`, the module singleton, identity rebind) live
109
+ * at the single call site in `container.ts`. Without this reader the
110
+ * persisted key is dead weight and outbound capture silently keeps requiring
111
+ * a hand-pasted env var.
112
+ *
113
+ * The capture host resolves env-first, then the ingestion host derived from
114
+ * the stored PRIVATE host (`eu.posthog.com` → `eu.i.posthog.com`) so an
115
+ * EU-connected instance never captures to the US default.
116
+ */
117
+ export async function buildStoredPosthogProvider(opts: {
118
+ env: typeof envSchema;
119
+ db: Database;
120
+ logger: Logger;
121
+ }): Promise<AnalyticsProvider | null> {
122
+ let derived: Awaited<ReturnType<typeof getDerivedCredential>>;
123
+ try {
124
+ derived = await getDerivedCredential(opts.db, "posthog");
125
+ } catch {
126
+ return null;
127
+ }
128
+ if (!derived?.projectApiKey) return null;
129
+
130
+ return buildPosthogProvider(
131
+ opts.env,
132
+ { db: opts.db, logger: opts.logger },
133
+ {
134
+ apiKey: derived.projectApiKey,
135
+ projectId: derived.projectId,
136
+ privateHost: derived.privateHost,
137
+ host: derived.privateHost
138
+ ? deriveIngestHost(derived.privateHost)
139
+ : undefined,
140
+ },
141
+ );
142
+ }
@@ -5,12 +5,14 @@
5
5
  * so future read/write features activate without forcing a reconnect. Every
6
6
  * name is validated against PostHog's published `scopes_supported`.
7
7
  *
8
- * LOCKSTEP (3 places — no single importable source of truth, the CLI has no
9
- * engine dependency): this constant, the CLI's `POSTHOG_SCOPES`
10
- * (`packages/cli/src/lib/oauth.ts`), and the `scope` field of the hosted CIMD
11
- * document (`apps/docs/public/.well-known/hogsend-posthog-client.json`).
12
- * PostHog gates the scopes it will grant by the CIMD doc, so grep all three
13
- * and keep them identical before changing any of them.
8
+ * LOCKSTEP (3 places): this constant, the CLI's `POSTHOG_SCOPES`
9
+ * (`packages/cli/src/lib/oauth.ts` — the CLI avoids the engine ROOT import
10
+ * because the barrel does import-time env validation, but this module is
11
+ * dependency-free and exported as the `@hogsend/engine/posthog-scopes`
12
+ * subpath), and the `scope` field of the hosted CIMD document
13
+ * (`apps/docs/public/.well-known/hogsend-posthog-client.json`) — that one is
14
+ * genuinely un-importable. PostHog gates the scopes it will grant by the CIMD
15
+ * doc, so grep all three and keep them identical before changing any of them.
14
16
  */
15
17
  export const EXPECTED_POSTHOG_SCOPES: string[] = [
16
18
  "person:read",
@@ -27,3 +29,25 @@ export const EXPECTED_POSTHOG_SCOPES: string[] = [
27
29
  "event_definition:read",
28
30
  "property_definition:read",
29
31
  ];
32
+
33
+ /**
34
+ * PostHog's scope model is hierarchical — `X:write` implies `X:read` — and
35
+ * the grant NORMALIZES a request for both halves down to `X:write` alone. A
36
+ * literal set-difference against the requested list therefore reports the
37
+ * implied `:read` halves as "missing" on every fully-successful consent
38
+ * (e.g. person:read, hog_function:read, cohort:read). Treat a requested
39
+ * `X:read` as satisfied when the grant carries `X:write`.
40
+ *
41
+ * The CLI imports this via the `@hogsend/engine/posthog-scopes` subpath —
42
+ * single implementation, no mirror.
43
+ */
44
+ export function posthogScopeSatisfied(
45
+ granted: string[],
46
+ scope: string,
47
+ ): boolean {
48
+ return (
49
+ granted.includes(scope) ||
50
+ (scope.endsWith(":read") &&
51
+ granted.includes(scope.replace(/:read$/, ":write")))
52
+ );
53
+ }
@@ -0,0 +1,45 @@
1
+ import { defineEmailProvider } from "@hogsend/core";
2
+
3
+ /**
4
+ * The inert email provider a container boots with when NO provider is
5
+ * configured and none was explicitly requested (mirrors the SMS channel's
6
+ * operator-opt-in posture: unconfigured ⇒ inert stub, not a boot crash).
7
+ *
8
+ * A fresh scaffold has no RESEND_API_KEY yet — it should still boot, serve
9
+ * Studio, ingest events and run non-email journeys. Every email send fails
10
+ * per-call with this actionable message instead; the container logs one boot
11
+ * warning. Never registered in the provider registry, so no webhook route
12
+ * resolves it.
13
+ *
14
+ * DELIBERATE seam choice (vs SMS's service-level stub): the stub is the WIRE
15
+ * inside the real tracked mailer, so an unconfigured send still runs the
16
+ * pipeline (preferences → render → tracking → `email_sends` write) and fails
17
+ * at dispatch — leaving a failed-send row visible in Studio, which is exactly
18
+ * the operator-facing breadcrumb a "why didn't my email go out?" moment needs.
19
+ */
20
+ export const UNCONFIGURED_EMAIL_MESSAGE =
21
+ "no email provider configured — set RESEND_API_KEY (or POSTMARK_SERVER_TOKEN " +
22
+ "with EMAIL_PROVIDER=postmark), or pass `email: { provider }` to " +
23
+ "createHogsendClient().";
24
+
25
+ export function createUnconfiguredEmailProvider() {
26
+ return defineEmailProvider({
27
+ meta: {
28
+ id: "unconfigured",
29
+ name: "No email provider configured",
30
+ },
31
+ capabilities: {},
32
+ async send() {
33
+ throw new Error(UNCONFIGURED_EMAIL_MESSAGE);
34
+ },
35
+ async sendBatch() {
36
+ throw new Error(UNCONFIGURED_EMAIL_MESSAGE);
37
+ },
38
+ verifyWebhook() {
39
+ throw new Error(UNCONFIGURED_EMAIL_MESSAGE);
40
+ },
41
+ parseWebhook() {
42
+ throw new Error(UNCONFIGURED_EMAIL_MESSAGE);
43
+ },
44
+ });
45
+ }
@@ -3,7 +3,10 @@ import { DEFAULT_HOST, derivePrivateHost } from "@hogsend/plugin-posthog";
3
3
  import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
4
4
  import type { AppEnv } from "../../app.js";
5
5
  import { createTokenManager } from "../../lib/oauth-token-manager.js";
6
- import { EXPECTED_POSTHOG_SCOPES } from "../../lib/posthog-scopes.js";
6
+ import {
7
+ EXPECTED_POSTHOG_SCOPES,
8
+ posthogScopeSatisfied,
9
+ } from "../../lib/posthog-scopes.js";
7
10
  import {
8
11
  getDerivedCredential,
9
12
  getProviderCredential,
@@ -202,8 +205,12 @@ export const analyticsAdminRouter = new OpenAPIHono<AppEnv>()
202
205
  try {
203
206
  const oauth = await getProviderCredential(db, "posthog");
204
207
  if (oauth) {
208
+ // Hierarchical scopes: a granted `X:write` satisfies `X:read` (the
209
+ // grant normalizes both-halves requests down to write-only).
205
210
  const granted = oauth.payload.scopes;
206
- scopeGap = EXPECTED_POSTHOG_SCOPES.filter((s) => !granted.includes(s));
211
+ scopeGap = EXPECTED_POSTHOG_SCOPES.filter(
212
+ (s) => !posthogScopeSatisfied(granted, s),
213
+ );
207
214
  }
208
215
  } catch {
209
216
  scopeGap = [];
@@ -293,9 +300,11 @@ export const analyticsAdminRouter = new OpenAPIHono<AppEnv>()
293
300
  });
294
301
 
295
302
  // Opportunistically persist the phc_ (project api_token) the provisioner
296
- // read on its way through — it powers the OPTIONAL outbound capture path
297
- // and activates on the next deploy (no lazy boot-time seam). Re-read the
298
- // stored payload to merge over the just-persisted webhook secret.
303
+ // read on its way through — it powers the OPTIONAL outbound capture path.
304
+ // `activateStoredPosthogAnalytics` (container boot) reads it back, so
305
+ // capture comes alive on the next boot with NO hand-pasted
306
+ // POSTHOG_API_KEY. Re-read the stored payload to merge over the
307
+ // just-persisted webhook secret.
299
308
  if (result.projectApiKey) {
300
309
  const cur = (await getDerivedCredential(db, "posthog")) ?? {};
301
310
  await saveDerivedCredential(db, "posthog", {