@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@haatlabs-core/templates",
3
- "version": "0.18.5",
3
+ "version": "0.21.0",
4
4
  "description": "The starter files and shared project files that @haatlabs-core/cli writes.",
5
5
  "keywords": [
6
6
  "haatlabs"
@@ -36,8 +36,8 @@
36
36
  },
37
37
  "devDependencies": {
38
38
  "playwright-core": "1.63.0",
39
- "@haatlabs-core/tsconfig": "0.18.5",
40
- "@haatlabs-core/vitest-config": "0.18.5"
39
+ "@haatlabs-core/tsconfig": "0.21.0",
40
+ "@haatlabs-core/vitest-config": "0.21.0"
41
41
  },
42
42
  "scripts": {
43
43
  "build": "rm -rf dist && tsc -p tsconfig.build.json",
@@ -41,6 +41,7 @@
41
41
  "@haatlabs-core/nest-auth": "^@@platformVersion@@",
42
42
  "@haatlabs-core/nest-billing": "^@@platformVersion@@",
43
43
  "@haatlabs-core/nest-common": "^@@platformVersion@@",
44
+ "@haatlabs-core/notifications": "^@@platformVersion@@",
44
45
  "@haatlabs-core/rate-limit": "^@@platformVersion@@",
45
46
  #@if standalone
46
47
  "@haatlabs-core/services": "^@@platformVersion@@",
@@ -4,6 +4,7 @@ import { APP_FILTER } from '@nestjs/core';
4
4
  import type { GatewayName, PaymentGateway } from '@@@name@@/billing';
5
5
  import type { AppConfig } from '@@@name@@/config';
6
6
  import { ACCOUNT_FEATURES } from '@@@name@@/contracts';
7
+ import { NOTIFICATIONS_KEY_PREFIX, notificationEvents } from '@@@name@@/contracts/notifications';
7
8
  import {
8
9
  ApiKeyRepository,
9
10
  BillingRepository,
@@ -12,6 +13,7 @@ import {
12
13
  DisposableEmailRepository,
13
14
  FeatureRepository,
14
15
  IdentityRepository,
16
+ NotificationRepository,
15
17
  #@if kindShopify
16
18
  StoreRepository,
17
19
  #@end
@@ -47,6 +49,9 @@ import {
47
49
  redisCheck,
48
50
  } from '@haatlabs-core/nest-common';
49
51
  import type { HealthCheck } from '@haatlabs-core/nest-common';
52
+ import type { Recipient } from '@haatlabs-core/notifications';
53
+ import { NotificationsModule } from '@haatlabs-core/notifications/nest';
54
+ import type { Principal } from '@haatlabs-core/nest-auth';
50
55
  import type { Redis } from 'ioredis';
51
56
  import { AdminController } from './admin/admin.controller';
52
57
  #@if standalone
@@ -82,6 +87,23 @@ const healthChecks = {
82
87
  inject: [APP_DB, SYSTEM_DB, REDIS],
83
88
  };
84
89
 
90
+ /**
91
+ * Who a caller is in the inbox: the person signed in. An API key has no inbox.
92
+ #@if kindShopify
93
+ * Inside Shopify admin nobody is signed in as a person, so the store's staff share the
94
+ * store's inbox (`store` events, which the app adds as it needs them).
95
+ #@end
96
+ */
97
+ function recipientOf(principal: Principal): Recipient | null {
98
+ if (principal.userId) return { type: 'user', id: principal.userId };
99
+ #@if kindShopify
100
+ if (principal.via === 'embedded' && principal.storeId) {
101
+ return { type: 'store', id: principal.storeId };
102
+ }
103
+ #@end
104
+ return null;
105
+ }
106
+
85
107
  @Module({})
86
108
  export class AppModule {
87
109
  static forRoot(
@@ -194,6 +216,20 @@ export class AppModule {
194
216
  },
195
217
  #@end
196
218
  }),
219
+ // The inbox, preferences, push devices and the live stream, under /api/v1/notifications.
220
+ NotificationsModule.forRoot({
221
+ events: notificationEvents,
222
+ repository: {
223
+ useFactory: (a: DatabaseHandle) => new NotificationRepository(a.db),
224
+ inject: [APP_DB],
225
+ },
226
+ redis: { useFactory: (redis: Redis) => redis, inject: [REDIS] },
227
+ keyPrefix: NOTIFICATIONS_KEY_PREFIX,
228
+ webPushPublicKey: config.notifications.webPush?.publicKey ?? null,
229
+ recipientOf,
230
+ // The organization's defaults are its owner's to set (a store's staff are ADMIN).
231
+ audienceAdmins: ['OWNER'],
232
+ }),
197
233
  BillingAdminModule.forRoot({
198
234
  features: ACCOUNT_FEATURES,
199
235
  repositories: {
@@ -0,0 +1,210 @@
1
+ import { NOTIFICATIONS_KEY_PREFIX } from '@@@name@@/contracts/notifications';
2
+ import {
3
+ SystemNotificationRepository,
4
+ notifier,
5
+ outboxMessages,
6
+ withTenant,
7
+ } from '@@@name@@/database';
8
+ import { createNotificationsHandler } from '@@@name@@/worker/runtime';
9
+ import { createLogger } from '@haatlabs-core/logger';
10
+ import type { Mail } from '@haatlabs-core/mailer';
11
+ import { DELIVER_ROUTING_KEY, liveChannel } from '@haatlabs-core/notifications';
12
+ import { eq } from 'drizzle-orm';
13
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
14
+ import { registerUser, startHarness } from './testing/harness';
15
+ import type { Harness, TestUser } from './testing/harness';
16
+
17
+ interface Item {
18
+ id: string;
19
+ event: string;
20
+ title: string;
21
+ link: string | null;
22
+ readAt: string | null;
23
+ }
24
+
25
+ describe('notifications, end to end', () => {
26
+ let h: Harness;
27
+ let alice: TestUser;
28
+ let bob: TestUser;
29
+ /** What the worker emailed. */
30
+ const sent: Mail[] = [];
31
+
32
+ /** The worker's handler, as the `notifications` queue runs it. */
33
+ const workerHandler = () =>
34
+ createNotificationsHandler({
35
+ config: h.config,
36
+ repo: new SystemNotificationRepository(h.system.db),
37
+ redis: h.redis,
38
+ mailer: {
39
+ configured: true,
40
+ send: async (mail) => {
41
+ sent.push(mail);
42
+ },
43
+ },
44
+ logger: createLogger({ level: 'silent', name: 'worker' }),
45
+ });
46
+
47
+ /** Runs the worker's handler on every delivery waiting in the outbox, as the queue would. */
48
+ const deliverAll = async (): Promise<void> => {
49
+ const handler = workerHandler();
50
+ const waiting = await h.system.db
51
+ .select()
52
+ .from(outboxMessages)
53
+ .where(eq(outboxMessages.routingKey, DELIVER_ROUTING_KEY));
54
+ for (const row of waiting) {
55
+ await handler({
56
+ routingKey: row.routingKey,
57
+ payload: row.payload,
58
+ attempt: 1,
59
+ messageId: row.id,
60
+ });
61
+ }
62
+ await h.system.db
63
+ .delete(outboxMessages)
64
+ .where(eq(outboxMessages.routingKey, DELIVER_ROUTING_KEY));
65
+ };
66
+
67
+ const inboxOf = async (user: TestUser): Promise<Item[]> => {
68
+ const res = await h.request({
69
+ method: 'GET',
70
+ url: '/api/v1/notifications',
71
+ headers: user.headers,
72
+ });
73
+ expect(res.statusCode).toBe(200);
74
+ return res.json<{ items: Item[] }>().items;
75
+ };
76
+ const unreadOf = async (user: TestUser): Promise<number> => {
77
+ const res = await h.request({
78
+ method: 'GET',
79
+ url: '/api/v1/notifications/unread-count',
80
+ headers: user.headers,
81
+ });
82
+ expect(res.statusCode).toBe(200);
83
+ return res.json<{ unread: number }>().unread;
84
+ };
85
+
86
+ beforeAll(async () => {
87
+ h = await startHarness();
88
+ alice = await registerUser(h, 'alice@example.com');
89
+ bob = await registerUser(h, 'bob@example.com');
90
+ });
91
+ afterAll(async () => {
92
+ await h.stop();
93
+ });
94
+
95
+ it('notifies in a transaction, delivers through the worker, and lists it unread', async () => {
96
+ const live = h.redis.duplicate();
97
+ const heard: string[] = [];
98
+ live.on('message', (_channel: string, text: string) => heard.push(text));
99
+ await live.subscribe(
100
+ liveChannel(NOTIFICATIONS_KEY_PREFIX, alice.organizationId, {
101
+ type: 'user',
102
+ id: alice.userId,
103
+ }),
104
+ );
105
+
106
+ const { created } = await withTenant(
107
+ h.appDb.db,
108
+ { organizationId: alice.organizationId },
109
+ (tx) =>
110
+ notifier.notify(tx, {
111
+ organizationId: alice.organizationId,
112
+ event: 'account.welcome',
113
+ recipients: [{ type: 'user', id: alice.userId }],
114
+ data: { organizationName: 'Acme Outdoor' },
115
+ }),
116
+ );
117
+ expect(created).toBe(1);
118
+ await deliverAll();
119
+
120
+ const items = await inboxOf(alice);
121
+ expect(items).toHaveLength(1);
122
+ expect(items[0]).toMatchObject({
123
+ event: 'account.welcome',
124
+ title: 'Welcome to @@Name@@',
125
+ link: '/settings/notifications',
126
+ readAt: null,
127
+ });
128
+ expect(await unreadOf(alice)).toBe(1);
129
+
130
+ // Emailed to her (email is on by default), with the link to her settings.
131
+ expect(sent.map((mail) => [mail.to, mail.subject])).toEqual([
132
+ ['alice@example.com', 'Welcome to @@Name@@'],
133
+ ]);
134
+ expect(sent[0]?.html).toContain(`${h.config.api.webBaseUrl}/settings/notifications`);
135
+
136
+ // And published live, to the pages she has open.
137
+ await expect.poll(() => heard.length).toBeGreaterThanOrEqual(2);
138
+ expect(heard.map((text) => (JSON.parse(text) as { kind: string }).kind)).toEqual([
139
+ 'notification',
140
+ 'unread',
141
+ ]);
142
+ live.disconnect();
143
+ });
144
+
145
+ it('shows another organization nothing of it, and lets it mark nothing of hers read', async () => {
146
+ const [item] = await inboxOf(alice);
147
+ if (!item) throw new Error('alice has no notification');
148
+ expect(await inboxOf(bob)).toEqual([]);
149
+ const read = await h.request({
150
+ method: 'POST',
151
+ url: '/api/v1/notifications/read',
152
+ headers: bob.headers,
153
+ payload: { ids: [item.id] },
154
+ });
155
+ expect(read.statusCode).toBe(200);
156
+ expect(read.json()).toEqual({ unread: 0 });
157
+ expect(await unreadOf(alice)).toBe(1);
158
+ });
159
+
160
+ it('marks it read for her, and sends nothing twice when the delivery comes again', async () => {
161
+ const [item] = await inboxOf(alice);
162
+ if (!item) throw new Error('alice has no notification');
163
+ const read = await h.request({
164
+ method: 'POST',
165
+ url: '/api/v1/notifications/read',
166
+ headers: alice.headers,
167
+ payload: { ids: [item.id] },
168
+ });
169
+ expect(read.json()).toEqual({ unread: 0 });
170
+ expect(await unreadOf(alice)).toBe(0);
171
+
172
+ const handler = workerHandler();
173
+ await handler({
174
+ routingKey: DELIVER_ROUTING_KEY,
175
+ payload: { notificationId: item.id },
176
+ attempt: 2,
177
+ messageId: undefined,
178
+ });
179
+ expect(sent).toHaveLength(1);
180
+ });
181
+
182
+ it('gives the signed-in person their preferences, with the welcome email on', async () => {
183
+ const res = await h.request({
184
+ method: 'GET',
185
+ url: '/api/v1/notifications/preferences',
186
+ headers: alice.headers,
187
+ });
188
+ expect(res.statusCode).toBe(200);
189
+ expect(res.json()).toEqual({
190
+ events: [
191
+ {
192
+ event: 'account.welcome',
193
+ label: 'Welcome to @@Name@@',
194
+ group: 'Account',
195
+ required: false,
196
+ channels: { email: { on: true, locked: false }, push: { on: false, locked: false } },
197
+ },
198
+ ],
199
+ });
200
+ });
201
+
202
+ it('says Web Push is not set up where it has no keys', async () => {
203
+ const res = await h.request({
204
+ method: 'GET',
205
+ url: '/api/v1/notifications/push/key',
206
+ headers: alice.headers,
207
+ });
208
+ expect(res.json()).toEqual({ webPush: null });
209
+ });
210
+ });
@@ -61,6 +61,8 @@ const ROUTES: Record<
61
61
  * changing or cancelling its plan, refused in nest-billing's words.
62
62
  */
63
63
  wholeOrganization?: true | 'plan';
64
+ /** Answers with a stream that stays open: only asked where it is refused. */
65
+ stream?: true;
64
66
  }
65
67
  > = {
66
68
  'GET /health/live': { access: 'public' },
@@ -69,6 +71,11 @@ const ROUTES: Record<
69
71
  // email and per address, and worth nothing without the email's inbox.
70
72
  'POST /api/v1/auth/code': { access: 'public' },
71
73
  'POST /api/v1/auth/verify': { access: 'public' },
74
+ // Signing in with Google or GitHub: the providers offered, the redirect to one, and its
75
+ // return, authenticated by the state and the browser's cookie.
76
+ 'GET /api/v1/auth/providers': { access: 'public' },
77
+ 'GET /api/v1/auth/oauth/:provider/start': { access: 'public' },
78
+ 'GET /api/v1/auth/oauth/:provider/callback': { access: 'public' },
72
79
  // Authenticated by each gateway's signature over the raw body.
73
80
  'POST /api/v1/webhooks/:provider(stripe|razorpay)': { access: 'public' },
74
81
 
@@ -104,6 +111,21 @@ const ROUTES: Record<
104
111
  'GET /api/v1/auth/extension-keys': { access: 'authenticated', standaloneOnly: true },
105
112
  'POST /api/v1/auth/extension-keys': { access: 'authenticated', standaloneOnly: true },
106
113
  'POST /api/v1/settings/api-keys': { access: 'authenticated', standaloneOnly: true },
114
+ // The caller's own inbox, choices and devices: every query is the caller's, so another
115
+ // organization's id finds nothing (notifications.int.test.ts). The stream never ends.
116
+ 'GET /api/v1/notifications': { access: 'authenticated' },
117
+ 'GET /api/v1/notifications/unread-count': { access: 'authenticated' },
118
+ 'POST /api/v1/notifications/read': { access: 'authenticated' },
119
+ 'POST /api/v1/notifications/read-all': { access: 'authenticated' },
120
+ 'GET /api/v1/notifications/stream': { access: 'authenticated', stream: true },
121
+ 'GET /api/v1/notifications/preferences': { access: 'authenticated' },
122
+ 'PUT /api/v1/notifications/preferences': { access: 'authenticated' },
123
+ // The organization's defaults for an audience: its owner's (audienceAdmins).
124
+ 'GET /api/v1/notifications/defaults/:audience': { access: 'authenticated' },
125
+ 'PUT /api/v1/notifications/defaults/:audience': { access: 'authenticated' },
126
+ 'GET /api/v1/notifications/push/key': { access: 'authenticated' },
127
+ 'POST /api/v1/notifications/push/subscriptions': { access: 'authenticated' },
128
+ 'DELETE /api/v1/notifications/push/subscriptions': { access: 'authenticated' },
107
129
  'POST /api/v1/billing/checkout': {
108
130
  access: 'authenticated',
109
131
  standaloneOnly: true,
@@ -187,6 +209,7 @@ describe('security sweep', () => {
187
209
  email: 'sweep@example.com',
188
210
  code: '12345678',
189
211
  planCode: 'starter',
212
+ audience: 'user',
190
213
  ...victim,
191
214
  };
192
215
  let url = pattern.replace(/:([A-Za-z]+)/g, (_match, name: string) =>
@@ -212,6 +235,8 @@ describe('security sweep', () => {
212
235
  Object.entries(ROUTES)
213
236
  .filter(([, spec]) => spec.access === access)
214
237
  .map(([route]) => route);
238
+ /** A read that answers and ends: what can be asked with credentials that pass. */
239
+ const isRead = (route: string): boolean => route.startsWith('GET') && !ROUTES[route]?.stream;
215
240
  const standaloneOnly = (route: string): boolean => ROUTES[route]?.standaloneOnly === true;
216
241
  const embeddedOnly = (route: string): boolean => ROUTES[route]?.embeddedOnly === true;
217
242
  const wholeOrganization = (route: string): boolean => !!ROUTES[route]?.wholeOrganization;
@@ -401,7 +426,7 @@ describe('security sweep', () => {
401
426
  }
402
427
  // What it may read answers it as anyone of the organization's; the organization's own
403
428
  // routes answer the staff of a store installed from Shopify, and the dashboard.
404
- const reads = routes.filter((route) => route.startsWith('GET'));
429
+ const reads = routes.filter(isRead);
405
430
  for (const route of reads.filter((r) => !wholeOrganization(r))) {
406
431
  const res = await send(route, aliceEmbedded);
407
432
  expect(res.body, route).not.toMatch(WHOLE_ORGANIZATION_MESSAGE);
@@ -429,7 +454,7 @@ describe('security sweep', () => {
429
454
  });
430
455
 
431
456
  it("shows a signed-in user nothing of another organization's on any route it may call", async () => {
432
- for (const route of routesWith('authenticated').filter((r) => r.startsWith('GET'))) {
457
+ for (const route of routesWith('authenticated').filter(isRead)) {
433
458
  for (const headers of [alice.headers, aliceEmbedded]) {
434
459
  const res = await send(route, headers);
435
460
  expect(res.body, route).not.toContain(SHOP);
@@ -439,9 +464,7 @@ describe('security sweep', () => {
439
464
  });
440
465
 
441
466
  it('never returns credentials or storage internals, even to the owner', async () => {
442
- for (const route of [...routesWith('authenticated'), ...routesWith('tenant')].filter((r) =>
443
- r.startsWith('GET'),
444
- )) {
467
+ for (const route of [...routesWith('authenticated'), ...routesWith('tenant')].filter(isRead)) {
445
468
  const res = await send(route, bob.headers);
446
469
  expect(res.body, route).not.toContain(TOKEN_CIPHERTEXT);
447
470
  expect(res.body, route).not.toMatch(
@@ -518,13 +541,27 @@ type Access = 'public' | 'authenticated' | 'tenant' | 'admin';
518
541
  * organization; `body` and `query` say how to ask for one. A route added to the
519
542
  * application without a line here fails the first test below.
520
543
  */
521
- const ROUTES: Record<string, { access: Access; body?: string[]; query?: string[] }> = {
544
+ const ROUTES: Record<
545
+ string,
546
+ {
547
+ access: Access;
548
+ body?: string[];
549
+ query?: string[];
550
+ /** Answers with a stream that stays open: only asked where it is refused. */
551
+ stream?: true;
552
+ }
553
+ > = {
522
554
  'GET /health/live': { access: 'public' },
523
555
  'GET /health/ready': { access: 'public' },
524
556
  // Asking for a sign-in code and giving it back: open to anyone to try, limited per
525
557
  // email and per address, and worth nothing without the email's inbox.
526
558
  'POST /api/v1/auth/code': { access: 'public' },
527
559
  'POST /api/v1/auth/verify': { access: 'public' },
560
+ // Signing in with Google or GitHub: the providers offered, the redirect to one, and its
561
+ // return, authenticated by the state and the browser's cookie.
562
+ 'GET /api/v1/auth/providers': { access: 'public' },
563
+ 'GET /api/v1/auth/oauth/:provider/start': { access: 'public' },
564
+ 'GET /api/v1/auth/oauth/:provider/callback': { access: 'public' },
528
565
  // Authenticated by each gateway's signature over the raw body.
529
566
  'POST /api/v1/webhooks/:provider(stripe|razorpay)': { access: 'public' },
530
567
 
@@ -540,6 +577,21 @@ const ROUTES: Record<string, { access: Access; body?: string[]; query?: string[]
540
577
  'GET /api/v1/auth/extension-keys': { access: 'authenticated' },
541
578
  'POST /api/v1/auth/extension-keys': { access: 'authenticated' },
542
579
  'POST /api/v1/settings/api-keys': { access: 'authenticated' },
580
+ // The caller's own inbox, choices and devices: every query is the caller's, so another
581
+ // organization's id finds nothing (notifications.int.test.ts). The stream never ends.
582
+ 'GET /api/v1/notifications': { access: 'authenticated' },
583
+ 'GET /api/v1/notifications/unread-count': { access: 'authenticated' },
584
+ 'POST /api/v1/notifications/read': { access: 'authenticated' },
585
+ 'POST /api/v1/notifications/read-all': { access: 'authenticated' },
586
+ 'GET /api/v1/notifications/stream': { access: 'authenticated', stream: true },
587
+ 'GET /api/v1/notifications/preferences': { access: 'authenticated' },
588
+ 'PUT /api/v1/notifications/preferences': { access: 'authenticated' },
589
+ // The organization's defaults for an audience: its owner's (audienceAdmins).
590
+ 'GET /api/v1/notifications/defaults/:audience': { access: 'authenticated' },
591
+ 'PUT /api/v1/notifications/defaults/:audience': { access: 'authenticated' },
592
+ 'GET /api/v1/notifications/push/key': { access: 'authenticated' },
593
+ 'POST /api/v1/notifications/push/subscriptions': { access: 'authenticated' },
594
+ 'DELETE /api/v1/notifications/push/subscriptions': { access: 'authenticated' },
543
595
  'POST /api/v1/billing/checkout': { access: 'authenticated' },
544
596
  'POST /api/v1/billing/cancel': { access: 'authenticated' },
545
597
 
@@ -577,6 +629,7 @@ describe('security sweep', () => {
577
629
  email: 'sweep@example.com',
578
630
  code: '12345678',
579
631
  planCode: 'starter',
632
+ audience: 'user',
580
633
  ...victim,
581
634
  };
582
635
  let url = pattern.replace(/:([A-Za-z]+)/g, (_match, name: string) =>
@@ -602,6 +655,8 @@ describe('security sweep', () => {
602
655
  Object.entries(ROUTES)
603
656
  .filter(([, spec]) => spec.access === access)
604
657
  .map(([route]) => route);
658
+ /** A read that answers and ends: what can be asked with credentials that pass. */
659
+ const isRead = (route: string): boolean => route.startsWith('GET') && !ROUTES[route]?.stream;
605
660
 
606
661
  beforeAll(async () => {
607
662
  h = await startHarness({ env: { CONNECTABLE_EXTENSION_IDS: SWEEP_EXTENSION } });
@@ -684,7 +739,7 @@ describe('security sweep', () => {
684
739
  });
685
740
 
686
741
  it("shows a signed-in user nothing of another organization's on any route it may call", async () => {
687
- for (const route of routesWith('authenticated').filter((r) => r.startsWith('GET'))) {
742
+ for (const route of routesWith('authenticated').filter(isRead)) {
688
743
  const res = await send(route, alice.headers);
689
744
  expect(res.body, route).not.toContain(bob.organizationId);
690
745
  expect(res.body, route).not.toContain(victim.apiKeyId);
@@ -692,9 +747,7 @@ describe('security sweep', () => {
692
747
  });
693
748
 
694
749
  it('never returns credentials or storage internals, even to the owner', async () => {
695
- for (const route of [...routesWith('authenticated'), ...routesWith('tenant')].filter((r) =>
696
- r.startsWith('GET'),
697
- )) {
750
+ for (const route of [...routesWith('authenticated'), ...routesWith('tenant')].filter(isRead)) {
698
751
  const res = await send(route, bob.headers);
699
752
  expect(res.body, route).not.toMatch(
700
753
  /passwordHash|password_hash|keyHash|storageKey|accessToken/,
@@ -1,5 +1,5 @@
1
1
  import { loadConfig, refuseInProduction } from '@@@name@@/config';
2
- import { IdentityRepository, createDatabase } from '@@@name@@/database';
2
+ import { IdentityRepository, createDatabase, notifier, withTenant } from '@@@name@@/database';
3
3
 
4
4
  // The demo account has no password: its owner signs in with a code sent to this email.
5
5
  const email = process.env.SEED_USER_EMAIL?.trim().toLowerCase();
@@ -16,8 +16,21 @@ try {
16
16
  if (await identity.findUserByEmail(email)) {
17
17
  console.log(`Seed user ${email} already exists; nothing to do.`);
18
18
  } else {
19
- await identity.createUserWithOrganization({ email, organizationName: 'Demo Organization' });
20
- console.log(`Seeded ${email} with an organization of its own.`);
19
+ const organizationName = 'Demo Organization';
20
+ const { userId, organizationId } = await identity.createUserWithOrganization({
21
+ email,
22
+ organizationName,
23
+ });
24
+ // Something in the bell: the worker delivers it, by email too (make dev runs the worker).
25
+ await withTenant(system.db, { organizationId }, (tx) =>
26
+ notifier.notify(tx, {
27
+ organizationId,
28
+ event: 'account.welcome',
29
+ recipients: [{ type: 'user', id: userId }],
30
+ data: { organizationName },
31
+ }),
32
+ );
33
+ console.log(`Seeded ${email} with an organization of its own, and a welcome notification.`);
21
34
  }
22
35
  } finally {
23
36
  await system.close();
@@ -0,0 +1,47 @@
1
+ 'use strict';
2
+ function isPath(url) {
3
+ return url.length <= 512 && /^\/(?!\/)[^\s\\]*$/.test(url);
4
+ }
5
+ // A path, or an absolute URL on this origin (delivery sends absolute ones); anything else is '/'.
6
+ function appPath(url) {
7
+ if (typeof url !== 'string' || url.indexOf('\\') !== -1) return '/';
8
+ if (url.charAt(0) === '/') return isPath(url) ? url : '/';
9
+ try {
10
+ var parsed = new URL(url);
11
+ if (parsed.origin !== self.location.origin) return '/';
12
+ var path = parsed.pathname + parsed.search + parsed.hash;
13
+ return isPath(path) ? path : '/';
14
+ } catch {
15
+ return '/';
16
+ }
17
+ }
18
+ self.addEventListener('push', function (event) {
19
+ var data = {};
20
+ try { data = event.data ? event.data.json() : {}; } catch { data = {}; }
21
+ if (data === null || typeof data !== 'object') data = {};
22
+ event.waitUntil(self.registration.showNotification(typeof data.title === 'string' ? data.title : '', {
23
+ body: typeof data.body === 'string' ? data.body : '',
24
+ tag: typeof data.tag === 'string' ? data.tag : undefined,
25
+ // The bare path first: the absolute url may be on another of the app's hosts.
26
+ data: { url: appPath(typeof data.path === 'string' ? data.path : data.url) }
27
+ }));
28
+ });
29
+ function sameOrigin(url) {
30
+ try { return new URL(url).origin === self.location.origin; } catch { return false; }
31
+ }
32
+ self.addEventListener('notificationclick', function (event) {
33
+ event.notification.close();
34
+ var url = appPath(event.notification.data && event.notification.data.url);
35
+ event.waitUntil(self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (list) {
36
+ var client = null;
37
+ for (var i = 0; i < list.length; i += 1) {
38
+ if (sameOrigin(list[i].url) && 'focus' in list[i]) { client = list[i]; break; }
39
+ }
40
+ if (client === null) return self.clients.openWindow(url);
41
+ // navigate() rejects for a tab this worker does not control (the one that just subscribed).
42
+ return client.focus().then(function (focused) {
43
+ if (!focused || typeof focused.navigate !== 'function') return self.clients.openWindow(url);
44
+ return focused.navigate(url);
45
+ }).catch(function () { return self.clients.openWindow(url); });
46
+ }));
47
+ });
@@ -17,7 +17,9 @@
17
17
  "@@@name@@/config": "workspace:*",
18
18
  "@@@name@@/database": "workspace:*",
19
19
  "@haatlabs-core/logger": "^@@platformVersion@@",
20
+ "@haatlabs-core/mailer": "^@@platformVersion@@",
20
21
  "@haatlabs-core/nest-auth": "^@@platformVersion@@",
22
+ "@haatlabs-core/notifications": "^@@platformVersion@@",
21
23
  "@@@name@@/observability": "workspace:*",
22
24
  "@@@name@@/queue": "workspace:*",
23
25
  "drizzle-orm": "^0.45.3",
@@ -0,0 +1,63 @@
1
+ import type { AppConfig } from '@@@name@@/config';
2
+ import { NOTIFICATIONS_KEY_PREFIX, notificationEvents } from '@@@name@@/contracts/notifications';
3
+ import type { SystemNotificationRepository } from '@@@name@@/database';
4
+ import type { ConsumedMessage } from '@@@name@@/queue';
5
+ import type { Logger } from '@haatlabs-core/logger';
6
+ import type { Mailer } from '@haatlabs-core/mailer';
7
+ import {
8
+ createNotificationDeliveryHandler,
9
+ fcmTransport,
10
+ webPushTransport,
11
+ } from '@haatlabs-core/notifications';
12
+ import type { PushTransport } from '@haatlabs-core/notifications';
13
+ import type { Redis } from 'ioredis';
14
+
15
+ /** The dashboard's indigo (@haatlabs-core/ui's ACCENTS.indigo.solid), the emails' accent. */
16
+ const ACCENT = '#5850F4';
17
+
18
+ /**
19
+ * The `notifications` queue: each new notification goes live to the person's open pages, by
20
+ * push to their devices and by email, as they chose. Web Push and FCM are on where their keys
21
+ * are set (config.notifications); a device of a kind that is off is skipped.
22
+ */
23
+ export function createNotificationsHandler(deps: {
24
+ config: AppConfig;
25
+ repo: SystemNotificationRepository;
26
+ redis: Redis;
27
+ mailer: Mailer;
28
+ logger: Logger;
29
+ /** What FCM is called with; the global fetch by default. */
30
+ fetch?: typeof fetch;
31
+ }): (message: ConsumedMessage) => Promise<void> {
32
+ const { config, repo, redis } = deps;
33
+ const push: PushTransport[] = [];
34
+ if (config.notifications.webPush) push.push(webPushTransport(config.notifications.webPush));
35
+ if (config.notifications.fcm) {
36
+ push.push(
37
+ fcmTransport(config.notifications.fcm, {
38
+ redis,
39
+ keyPrefix: NOTIFICATIONS_KEY_PREFIX,
40
+ ...(deps.fetch ? { fetch: deps.fetch } : {}),
41
+ }),
42
+ );
43
+ }
44
+ return createNotificationDeliveryHandler({
45
+ repo,
46
+ events: notificationEvents,
47
+ redis,
48
+ keyPrefix: NOTIFICATIONS_KEY_PREFIX,
49
+ push,
50
+ mailer: deps.mailer,
51
+ // The same sender and host for everyone. An app that sends as its customers' own brands
52
+ // (white label) looks theirs up by organization, and one whose recipients sign in on
53
+ // different hosts (an owner's dashboard, a vendor's) picks the host by recipient.
54
+ brand: async (_organizationId, _recipient) => ({
55
+ appName: '@@Name@@',
56
+ accent: ACCENT,
57
+ baseUrl: config.api.webBaseUrl,
58
+ poweredBy: true,
59
+ }),
60
+ emailOf: (organizationId, recipient) => repo.emailOf(organizationId, recipient),
61
+ logger: deps.logger,
62
+ });
63
+ }