@haatlabs-core/templates 0.18.5 → 0.21.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.
Files changed (38) hide show
  1. package/package.json +3 -3
  2. package/starter/apps/api/package.json.tmpl +1 -0
  3. package/starter/apps/api/src/app.module.ts +36 -0
  4. package/starter/apps/api/src/notifications.int.test.ts +210 -0
  5. package/starter/apps/api/src/security-sweep.int.test.ts +63 -10
  6. package/starter/apps/api/src/seed.ts +16 -3
  7. package/starter/apps/web/public/notifications-sw.js +47 -0
  8. package/starter/apps/worker/package.json.tmpl +2 -0
  9. package/starter/apps/worker/src/handlers/notifications.handler.ts +63 -0
  10. package/starter/apps/worker/src/runtime.ts +52 -26
  11. package/starter/dot-env.example +16 -0
  12. package/starter/packages/config/src/config.test.ts +26 -0
  13. package/starter/packages/config/src/config.ts +11 -2
  14. package/starter/packages/contracts/package.json.tmpl +3 -1
  15. package/starter/packages/contracts/src/notifications.ts +38 -0
  16. package/starter/packages/database/drizzle/0009_notifications.sql +87 -0
  17. package/starter/packages/database/drizzle/meta/0009_snapshot.json +2446 -0
  18. package/starter/packages/database/drizzle/meta/_journal.json +7 -0
  19. package/starter/packages/database/package.json.tmpl +1 -0
  20. package/starter/packages/database/src/index.ts +1 -0
  21. package/starter/packages/database/src/repositories/notification.repository.ts +65 -0
  22. package/starter/packages/database/src/schema/index.ts +1 -0
  23. package/starter/packages/database/src/schema/notifications.ts +37 -0
  24. package/starter/packages/database/src/schema-tables.int.test.ts +10 -0
  25. package/starter/packages/queue/src/topology.test.ts +1 -0
  26. package/starter/packages/queue/src/topology.ts +3 -0
  27. package/starter/packages/web-ui/package.json.tmpl +1 -0
  28. package/starter/packages/web-ui/src/App.test.tsx +51 -2
  29. package/starter/packages/web-ui/src/App.tsx +84 -8
  30. package/starter/packages/web-ui/src/api-client.test.ts +204 -1
  31. package/starter/packages/web-ui/src/api-client.ts +207 -1
  32. package/starter/packages/web-ui/src/components/Logo.tsx +5 -0
  33. package/starter/packages/web-ui/src/pages/ConnectExtensionPage.test.tsx +57 -0
  34. package/starter/packages/web-ui/src/pages/ConnectExtensionPage.tsx +33 -1
  35. package/starter/packages/web-ui/src/pages/NotificationSettingsPage.tsx +24 -0
  36. package/starter/packages/web-ui/src/pages/NotificationsPage.tsx +19 -0
  37. package/starter/packages/web-ui/src/styles.css +21 -0
  38. package/starter/packages/web-ui/src/testing/fake-client.ts +15 -0
@@ -1,4 +1,5 @@
1
1
  import type { AppConfig } from '@@@name@@/config';
2
+ import { NOTIFICATIONS_KEY_PREFIX } from '@@@name@@/contracts/notifications';
2
3
  import {
3
4
  DisposableEmailRepository,
4
5
  OutboxRepository,
@@ -6,6 +7,7 @@ import {
6
7
  SystemBillingRepository,
7
8
  #@end
8
9
  SystemMetricsRepository,
10
+ SystemNotificationRepository,
9
11
  #@if kindShopify
10
12
  SystemStoreRepository,
11
13
  #@end
@@ -15,31 +17,31 @@ import {
15
17
  import { ShopifyAdminClient, StoreAccessTokens, TokenCipher } from '@@@name@@/shopify';
16
18
  #@end
17
19
  import { createLogger, watchRedis } from '@haatlabs-core/logger';
20
+ import { mailerFromConfig } from '@haatlabs-core/mailer';
21
+ import type { Mailer } from '@haatlabs-core/mailer';
18
22
  import { startDisposableDomainRefresh } from '@haatlabs-core/nest-auth/disposable';
23
+ import { startNotificationPrune } from '@haatlabs-core/notifications';
19
24
  import { createMetrics } from '@@@name@@/observability';
20
25
  import type { Metrics } from '@@@name@@/observability';
21
26
  import {
22
27
  OutboxRelay,
23
- #@if kindShopify
24
28
  QueueName,
25
- #@end
26
29
  QueuePublisher,
27
30
  connectQueue,
28
- #@if kindShopify
29
31
  startConsumers,
30
- #@end
31
32
  } from '@@@name@@/queue';
32
- #@if kindShopify
33
33
  import type { Consumer } from '@@@name@@/queue';
34
- #@end
35
34
  import { sql } from 'drizzle-orm';
36
35
  import { Redis } from 'ioredis';
37
36
  #@if kindShopify
38
37
  import { StoreBillingSync } from './billing/store-billing-sync';
39
38
  import { createShopifySyncHandler } from './handlers/shopify-sync.handler';
40
39
  #@end
40
+ import { createNotificationsHandler } from './handlers/notifications.handler';
41
41
  import { startHealthServer } from './health';
42
42
 
43
+ export { createNotificationsHandler } from './handlers/notifications.handler';
44
+
43
45
  export interface WorkerOverrides {
44
46
  outboxIdleDelayMs?: number;
45
47
  /** Pass null to run without the probe server (tests). */
@@ -48,16 +50,20 @@ export interface WorkerOverrides {
48
50
  metrics?: Metrics;
49
51
  /** What the worker calls out with (tests stand in for it); the global fetch by default. */
50
52
  fetch?: typeof fetch;
53
+ /** What sends notification emails (tests keep them); the configured SMTP server by default. */
54
+ mailer?: Mailer;
51
55
  }
52
56
 
53
57
  /**
54
58
  * The background process. It moves what the API wrote to the outbox onto the queues,
55
59
  #@if kindShopify
56
- * answers its health probes, and keeps each organization's plan what Shopify is charging
57
- * its store for (the `shopify-sync` queue). The app's own jobs are consumed here too.
60
+ * answers its health probes, delivers notifications (the `notifications` queue) and keeps
61
+ * each organization's plan what Shopify is charging its store for (the `shopify-sync`
62
+ * queue). The app's own jobs are consumed here too.
58
63
  #@end
59
64
  #@if !kindShopify
60
- * and answers its health probes. The app's own jobs are consumed here too.
65
+ * answers its health probes and delivers notifications (the `notifications` queue). The
66
+ * app's own jobs are consumed here too.
61
67
  #@end
62
68
  */
63
69
  export async function startWorker(
@@ -82,6 +88,31 @@ export async function startWorker(
82
88
  },
83
89
  );
84
90
  relay.start();
91
+
92
+ // Notifications: delivered as they are written, and pruned once a day by one worker.
93
+ const notificationsRepo = new SystemNotificationRepository(system.db);
94
+ const consumers: Consumer[] = [
95
+ await startConsumers(queue, {
96
+ queue: QueueName.Notifications,
97
+ concurrency: config.worker.concurrency,
98
+ maxAttempts: config.worker.maxAttempts,
99
+ logger,
100
+ handler: createNotificationsHandler({
101
+ config,
102
+ repo: notificationsRepo,
103
+ redis,
104
+ mailer: overrides.mailer ?? mailerFromConfig(config.mail),
105
+ logger,
106
+ fetch: overrides.fetch,
107
+ }),
108
+ }),
109
+ ];
110
+ const stopPrune = startNotificationPrune({
111
+ repo: notificationsRepo,
112
+ redis,
113
+ keyPrefix: NOTIFICATIONS_KEY_PREFIX,
114
+ logger,
115
+ });
85
116
  #@if kindShopify
86
117
  const stores = new SystemStoreRepository(system.db);
87
118
  const fetchImpl = overrides.fetch ?? fetch;
@@ -109,7 +140,6 @@ export async function startWorker(
109
140
  })
110
141
  : null;
111
142
  // Without the Shopify app there is no store to read a plan for: its work stays queued.
112
- let consumer: Consumer | null = null;
113
143
  if (shopifyApp && storeTokens) {
114
144
  const billingSync = new StoreBillingSync({
115
145
  stores,
@@ -125,13 +155,15 @@ export async function startWorker(
125
155
  }),
126
156
  logger,
127
157
  });
128
- consumer = await startConsumers(queue, {
129
- queue: QueueName.ShopifySync,
130
- concurrency: config.worker.concurrency,
131
- maxAttempts: config.worker.maxAttempts,
132
- logger,
133
- handler: createShopifySyncHandler(billingSync, logger),
134
- });
158
+ consumers.push(
159
+ await startConsumers(queue, {
160
+ queue: QueueName.ShopifySync,
161
+ concurrency: config.worker.concurrency,
162
+ maxAttempts: config.worker.maxAttempts,
163
+ logger,
164
+ handler: createShopifySyncHandler(billingSync, logger),
165
+ }),
166
+ );
135
167
  } else {
136
168
  logger.warn({}, 'Shopify is not set up here: the shopify-sync queue is not consumed');
137
169
  }
@@ -149,13 +181,8 @@ export async function startWorker(
149
181
  redis: () => redis.ping(),
150
182
  queue: () => queue.redis.ping(),
151
183
  },
152
- #@if kindShopify
153
184
  // Live while it takes work: a consumer that has stopped is restarted with the process.
154
- () => consumer?.running() ?? true,
155
- #@end
156
- #@if !kindShopify
157
- () => true,
158
- #@end
185
+ () => consumers.every((consumer) => consumer.running()),
159
186
  { metrics },
160
187
  );
161
188
 
@@ -174,10 +201,9 @@ export async function startWorker(
174
201
  logger.info('Worker started');
175
202
 
176
203
  const stop = async (): Promise<void> => {
177
- #@if kindShopify
178
204
  // Takes no more work and finishes what it has in hand.
179
- await consumer?.stop();
180
- #@end
205
+ await Promise.all(consumers.map((consumer) => consumer.stop()));
206
+ stopPrune();
181
207
  disposable?.stop();
182
208
  await relay.stop();
183
209
  if (health) {
@@ -132,6 +132,22 @@ GITHUB_OAUTH_CLIENT_SECRET=
132
132
  # /connect/extension: the app's own extension (`haatlabs create --kind extension`). Empty: none.
133
133
  CONNECTABLE_EXTENSION_IDS=
134
134
 
135
+ # Push notifications (@haatlabs-core/notifications). Each group is all set or all empty: a group
136
+ # with only some of its keys stops the api and the worker from starting. Empty: no push of
137
+ # that kind; the inbox and notification emails work without either.
138
+ # Web Push, for the dashboard in a browser or installed as an app: generate the pair with
139
+ # `npx web-push generate-vapid-keys`. The private key is a secret. The subject is how a push
140
+ # service reaches you: mailto:<an address> or https://<your site>.
141
+ # VAPID_PUBLIC_KEY=
142
+ # VAPID_PRIVATE_KEY=
143
+ # VAPID_SUBJECT=mailto:you@example.com
144
+ # Firebase Cloud Messaging, for a mobile app: a service account of the Firebase project with
145
+ # the role "Firebase Cloud Messaging API Admin". The private key is a secret: paste it on one
146
+ # line with its line breaks written as \n.
147
+ # FCM_PROJECT_ID=
148
+ # FCM_CLIENT_EMAIL=
149
+ # FCM_PRIVATE_KEY=
150
+
135
151
  # Payment gateways for plans bought from the standalone dashboard. Each is switched on by
136
152
  # setting all of its keys; leave them empty and it does not exist. Use test-mode keys
137
153
  # anywhere but production. Webhooks: <API_BASE_URL>/api/v1/webhooks/stripe and
@@ -225,4 +225,30 @@ describe('loadConfig', () => {
225
225
  }
226
226
  });
227
227
  });
228
+
229
+ describe('push', () => {
230
+ const vapid = {
231
+ VAPID_PUBLIC_KEY: 'BPublicKey',
232
+ VAPID_PRIVATE_KEY: 'private-key',
233
+ VAPID_SUBJECT: 'mailto:ops@example.com',
234
+ };
235
+
236
+ it('is off until its keys are set', () => {
237
+ expect(loadConfig(buildTestEnv()).notifications).toEqual({ webPush: null, fcm: null });
238
+ });
239
+
240
+ it('turns Web Push on with all three VAPID keys', () => {
241
+ expect(loadConfig(buildTestEnv(vapid)).notifications.webPush).toEqual({
242
+ publicKey: 'BPublicKey',
243
+ privateKey: 'private-key',
244
+ subject: 'mailto:ops@example.com',
245
+ });
246
+ });
247
+
248
+ it('refuses a half-set group, naming what is missing', () => {
249
+ expect(() => loadConfig(buildTestEnv({ VAPID_PUBLIC_KEY: 'BPublicKey' }))).toThrow(
250
+ /VAPID_PRIVATE_KEY, VAPID_SUBJECT/,
251
+ );
252
+ });
253
+ });
228
254
  });
@@ -11,6 +11,7 @@ import {
11
11
  #@if kindShopify
12
12
  mapTokenEncryption,
13
13
  #@end
14
+ notificationsConfig,
14
15
  paymentsEnvChecks,
15
16
  paymentsEnvShape,
16
17
  #@if kindShopify
@@ -20,6 +21,7 @@ import {
20
21
  } from '@haatlabs-core/config-core';
21
22
  import type {
22
23
  CoreConfig,
24
+ NotificationsConfig,
23
25
  PaymentsConfig,
24
26
  #@if kindShopify
25
27
  ShopifyConfig,
@@ -74,6 +76,8 @@ export interface AppConfig extends CoreConfig {
74
76
  payments: PaymentsConfig;
75
77
  /** The browser extensions a person may connect (their ids). */
76
78
  extension: { ids: string[] };
79
+ /** Web Push (VAPID) and FCM: each null unless all of its keys are set. */
80
+ notifications: NotificationsConfig;
77
81
  #@if standalone
78
82
  /** The Haatlabs API's RapidAPI key; null when HAATLABS_API_KEY is not set. */
79
83
  haatlabsApiKey: string | null;
@@ -85,10 +89,14 @@ export { ConfigError } from '@haatlabs-core/config-core';
85
89
  export function loadConfig(
86
90
  env: NodeJS.ProcessEnv | Record<string, string | undefined> = process.env,
87
91
  ): AppConfig {
88
- return loadConfigWith(EnvSchema, (e) => mapAppConfig(e), env);
92
+ // The push keys are read from the environment as given: a half-set group is refused.
93
+ return loadConfigWith(EnvSchema, (e) => mapAppConfig(e, env), env);
89
94
  }
90
95
 
91
- function mapAppConfig(e: z.output<typeof EnvSchema>): AppConfig {
96
+ function mapAppConfig(
97
+ e: z.output<typeof EnvSchema>,
98
+ env: NodeJS.ProcessEnv | Record<string, string | undefined>,
99
+ ): AppConfig {
92
100
  return {
93
101
  ...mapCoreConfig(e),
94
102
  #@if kindShopify
@@ -99,6 +107,7 @@ function mapAppConfig(e: z.output<typeof EnvSchema>): AppConfig {
99
107
  #@end
100
108
  payments: mapPayments(e),
101
109
  extension: { ids: csv(e.CONNECTABLE_EXTENSION_IDS) },
110
+ notifications: notificationsConfig(env),
102
111
  #@if standalone
103
112
  haatlabsApiKey: e.HAATLABS_API_KEY || null,
104
113
  #@end
@@ -4,7 +4,8 @@
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "exports": {
7
- ".": "./src/index.ts"
7
+ ".": "./src/index.ts",
8
+ "./notifications": "./src/notifications.ts"
8
9
  },
9
10
  "scripts": {
10
11
  "typecheck": "tsc --noEmit",
@@ -13,6 +14,7 @@
13
14
  "dependencies": {
14
15
  "@haatlabs-core/billing": "^@@platformVersion@@",
15
16
  "@haatlabs-core/errors": "^@@platformVersion@@",
17
+ "@haatlabs-core/notifications": "^@@platformVersion@@",
16
18
  "@haatlabs-core/shopify": "^@@platformVersion@@",
17
19
  "zod": "^4.6.5",
18
20
  "@haatlabs-core/auth-contracts": "^@@platformVersion@@"
@@ -0,0 +1,38 @@
1
+ import { defineNotificationEvents } from '@haatlabs-core/notifications';
2
+
3
+ // What @@Name@@ notifies people of: each event's name in the settings, its group there, who it
4
+ // is for, which channels are on until someone chooses, and what it says in the inbox, in a
5
+ // push and in an email. The API and the worker load this, never a page: it is not in this
6
+ // package's index, which the pages load (@haatlabs-core/notifications is a server package).
7
+ //
8
+ // Add the app's own events here, then call `notifier.notify(tx, …)` (@@@name@@/database) in
9
+ // the transaction of the change they tell of.
10
+
11
+ /**
12
+ * What every notifications key of this app in Redis starts with (the live stream's channels,
13
+ * the daily prune): the API and the worker must agree on it.
14
+ */
15
+ export const NOTIFICATIONS_KEY_PREFIX = '@@name@@';
16
+
17
+ export const notificationEvents = defineNotificationEvents({
18
+ 'account.welcome': {
19
+ label: 'Welcome to @@Name@@',
20
+ group: 'Account',
21
+ audiences: ['user'],
22
+ defaults: { email: true, push: false },
23
+ render: (data: { organizationName: string }) => ({
24
+ title: 'Welcome to @@Name@@',
25
+ body: `${data.organizationName} is set up. Choose which notifications you get in Settings.`,
26
+ link: '/settings/notifications',
27
+ }),
28
+ email: (data: { organizationName: string }) => ({
29
+ subject: 'Welcome to @@Name@@',
30
+ heading: 'Welcome to @@Name@@',
31
+ paragraphs: [
32
+ `${data.organizationName} is set up and ready.`,
33
+ 'You can choose which notifications reach you by email and push.',
34
+ ],
35
+ button: { label: 'Choose notifications' },
36
+ }),
37
+ },
38
+ });
@@ -0,0 +1,87 @@
1
+ CREATE TABLE "notification_defaults" (
2
+ "organization_id" uuid NOT NULL,
3
+ "audience" text NOT NULL,
4
+ "event" text NOT NULL,
5
+ "channel" text NOT NULL,
6
+ "enabled" boolean NOT NULL,
7
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
8
+ CONSTRAINT "notification_defaults_pkey" PRIMARY KEY("organization_id","audience","event","channel")
9
+ );
10
+ --> statement-breakpoint
11
+ CREATE TABLE "notification_preferences" (
12
+ "organization_id" uuid NOT NULL,
13
+ "recipient_type" text NOT NULL,
14
+ "recipient_id" text NOT NULL,
15
+ "event" text NOT NULL,
16
+ "channel" text NOT NULL,
17
+ "enabled" boolean NOT NULL,
18
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
19
+ CONSTRAINT "notification_preferences_pkey" PRIMARY KEY("organization_id","recipient_type","recipient_id","event","channel")
20
+ );
21
+ --> statement-breakpoint
22
+ CREATE TABLE "notifications" (
23
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
24
+ "organization_id" uuid NOT NULL,
25
+ "recipient_type" text NOT NULL,
26
+ "recipient_id" text NOT NULL,
27
+ "event" text NOT NULL,
28
+ "title" text NOT NULL,
29
+ "body" text DEFAULT '' NOT NULL,
30
+ "link" text,
31
+ "data" jsonb DEFAULT '{}'::jsonb NOT NULL,
32
+ "dedupe_key" text,
33
+ "read_at" timestamp with time zone,
34
+ "live_sent_at" timestamp with time zone,
35
+ "push_sent_at" timestamp with time zone,
36
+ "email_sent_at" timestamp with time zone,
37
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL
38
+ );
39
+ --> statement-breakpoint
40
+ CREATE TABLE "push_subscriptions" (
41
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
42
+ "organization_id" uuid NOT NULL,
43
+ "recipient_type" text NOT NULL,
44
+ "recipient_id" text NOT NULL,
45
+ "kind" text NOT NULL,
46
+ "endpoint" text NOT NULL,
47
+ "p256dh" text,
48
+ "auth" text,
49
+ "user_agent" text,
50
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
51
+ "last_used_at" timestamp with time zone,
52
+ CONSTRAINT "push_subscriptions_org_endpoint_unique" UNIQUE("organization_id","endpoint")
53
+ );
54
+ --> statement-breakpoint
55
+ ALTER TABLE "notification_defaults" ADD CONSTRAINT "notification_defaults_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
56
+ ALTER TABLE "notification_preferences" ADD CONSTRAINT "notification_preferences_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
57
+ ALTER TABLE "notifications" ADD CONSTRAINT "notifications_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
58
+ ALTER TABLE "push_subscriptions" ADD CONSTRAINT "push_subscriptions_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
59
+ CREATE INDEX "notifications_recipient_created_idx" ON "notifications" USING btree ("organization_id","recipient_type","recipient_id","created_at");--> statement-breakpoint
60
+ CREATE INDEX "notifications_unread_idx" ON "notifications" USING btree ("organization_id","recipient_type","recipient_id") WHERE "notifications"."read_at" is null;--> statement-breakpoint
61
+ CREATE UNIQUE INDEX "notifications_dedupe_uq" ON "notifications" USING btree ("organization_id","recipient_type","recipient_id","event","dedupe_key") WHERE "notifications"."dedupe_key" is not null;--> statement-breakpoint
62
+ CREATE INDEX "push_subscriptions_recipient_idx" ON "push_subscriptions" USING btree ("organization_id","recipient_type","recipient_id");
63
+ --> statement-breakpoint
64
+ -- The runtime role reads and changes its own tenant's inbox, choices and devices; the worker
65
+ -- delivers and prunes on the system connection.
66
+ GRANT SELECT, INSERT, UPDATE, DELETE
67
+ ON notifications, notification_preferences, notification_defaults, push_subscriptions
68
+ TO app_user;
69
+ --> statement-breakpoint
70
+ DO $$
71
+ DECLARE
72
+ t text;
73
+ BEGIN
74
+ FOREACH t IN ARRAY ARRAY[
75
+ 'notifications', 'notification_preferences', 'notification_defaults', 'push_subscriptions'
76
+ ]
77
+ LOOP
78
+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', t);
79
+ EXECUTE format(
80
+ 'CREATE POLICY tenant_isolation ON %I
81
+ USING (organization_id = NULLIF(current_setting(''app.organization_id'', true), '''')::uuid)
82
+ WITH CHECK (organization_id = NULLIF(current_setting(''app.organization_id'', true), '''')::uuid)',
83
+ t
84
+ );
85
+ END LOOP;
86
+ END
87
+ $$;