@haatlabs-core/templates 0.19.0 → 0.22.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 (44) 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 +81 -12
  6. package/starter/apps/api/src/seed-plans.int.test.ts +8 -1
  7. package/starter/apps/api/src/seed.ts +16 -3
  8. package/starter/apps/shopify-app/index.html +2 -0
  9. package/starter/apps/shopify-app/public/theme-boot.js +6 -0
  10. package/starter/apps/web/public/notifications-sw.js +47 -0
  11. package/starter/apps/worker/package.json.tmpl +2 -0
  12. package/starter/apps/worker/src/handlers/notifications.handler.ts +63 -0
  13. package/starter/apps/worker/src/runtime.ts +52 -26
  14. package/starter/dot-env.example +16 -0
  15. package/starter/packages/config/src/config.test.ts +26 -0
  16. package/starter/packages/config/src/config.ts +11 -2
  17. package/starter/packages/contracts/package.json.tmpl +3 -1
  18. package/starter/packages/contracts/src/notifications.ts +38 -0
  19. package/starter/packages/database/drizzle/0009_notifications.sql +87 -0
  20. package/starter/packages/database/drizzle/0010_platform_vendorhaat.sql +5 -0
  21. package/starter/packages/database/drizzle/meta/0009_snapshot.json +2446 -0
  22. package/starter/packages/database/drizzle/meta/0010_snapshot.json +2467 -0
  23. package/starter/packages/database/drizzle/meta/_journal.json +14 -0
  24. package/starter/packages/database/package.json.tmpl +1 -0
  25. package/starter/packages/database/src/index.ts +1 -0
  26. package/starter/packages/database/src/repositories/billing.int.test.ts +5 -4
  27. package/starter/packages/database/src/repositories/notification.repository.ts +65 -0
  28. package/starter/packages/database/src/schema/index.ts +1 -0
  29. package/starter/packages/database/src/schema/notifications.ts +37 -0
  30. package/starter/packages/database/src/schema-tables.int.test.ts +10 -0
  31. package/starter/packages/queue/src/topology.test.ts +1 -0
  32. package/starter/packages/queue/src/topology.ts +3 -0
  33. package/starter/packages/web-ui/package.json.tmpl +1 -0
  34. package/starter/packages/web-ui/src/App.test.tsx +140 -6
  35. package/starter/packages/web-ui/src/App.tsx +129 -27
  36. package/starter/packages/web-ui/src/api-client.test.ts +204 -1
  37. package/starter/packages/web-ui/src/api-client.ts +207 -1
  38. package/starter/packages/web-ui/src/components/Logo.tsx +11 -3
  39. package/starter/packages/web-ui/src/pages/HomePage.tsx +3 -3
  40. package/starter/packages/web-ui/src/pages/LoginPage.tsx +3 -1
  41. package/starter/packages/web-ui/src/pages/NotificationSettingsPage.tsx +24 -0
  42. package/starter/packages/web-ui/src/pages/NotificationsPage.tsx +19 -0
  43. package/starter/packages/web-ui/src/styles.css +73 -37
  44. package/starter/packages/web-ui/src/testing/fake-client.ts +16 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@haatlabs-core/templates",
3
- "version": "0.19.0",
3
+ "version": "0.22.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/vitest-config": "0.19.0",
40
- "@haatlabs-core/tsconfig": "0.19.0"
39
+ "@haatlabs-core/tsconfig": "0.22.0",
40
+ "@haatlabs-core/vitest-config": "0.22.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,11 +71,21 @@ 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
 
75
82
  'GET /api/v1/auth/me': { access: 'authenticated' },
76
83
  'POST /api/v1/auth/logout': { access: 'authenticated' },
84
+ // Several organizations per person: list them and move the session to another.
85
+ 'GET /api/v1/auth/organizations': { access: 'authenticated' },
86
+ 'POST /api/v1/auth/organization': { access: 'authenticated', body: ['organizationId'] },
87
+ // Spends the one-time code "Open dashboard" made; the code is the credential.
88
+ 'POST /api/v1/auth/handoff': { access: 'public', body: ['code'] },
77
89
  // The embedded app only; acts on the caller's own organization (email-sign-in.int.test.ts).
78
90
  'GET /api/v1/auth/email-sign-in': {
79
91
  access: 'authenticated',
@@ -104,6 +116,21 @@ const ROUTES: Record<
104
116
  'GET /api/v1/auth/extension-keys': { access: 'authenticated', standaloneOnly: true },
105
117
  'POST /api/v1/auth/extension-keys': { access: 'authenticated', standaloneOnly: true },
106
118
  'POST /api/v1/settings/api-keys': { access: 'authenticated', standaloneOnly: true },
119
+ // The caller's own inbox, choices and devices: every query is the caller's, so another
120
+ // organization's id finds nothing (notifications.int.test.ts). The stream never ends.
121
+ 'GET /api/v1/notifications': { access: 'authenticated' },
122
+ 'GET /api/v1/notifications/unread-count': { access: 'authenticated' },
123
+ 'POST /api/v1/notifications/read': { access: 'authenticated' },
124
+ 'POST /api/v1/notifications/read-all': { access: 'authenticated' },
125
+ 'GET /api/v1/notifications/stream': { access: 'authenticated', stream: true },
126
+ 'GET /api/v1/notifications/preferences': { access: 'authenticated' },
127
+ 'PUT /api/v1/notifications/preferences': { access: 'authenticated' },
128
+ // The organization's defaults for an audience: its owner's (audienceAdmins).
129
+ 'GET /api/v1/notifications/defaults/:audience': { access: 'authenticated' },
130
+ 'PUT /api/v1/notifications/defaults/:audience': { access: 'authenticated' },
131
+ 'GET /api/v1/notifications/push/key': { access: 'authenticated' },
132
+ 'POST /api/v1/notifications/push/subscriptions': { access: 'authenticated' },
133
+ 'DELETE /api/v1/notifications/push/subscriptions': { access: 'authenticated' },
107
134
  'POST /api/v1/billing/checkout': {
108
135
  access: 'authenticated',
109
136
  standaloneOnly: true,
@@ -142,6 +169,12 @@ const ROUTES: Record<
142
169
  'GET /api/v1/auth/shopify/install': { access: 'public' },
143
170
  'GET /api/v1/auth/shopify/callback': { access: 'public' },
144
171
  'POST /api/v1/webhooks/shopify': { access: 'public' },
172
+ // "Open dashboard": the embedded app's owner asks for a one-time link into the dashboard.
173
+ 'POST /api/v1/auth/shopify/dashboard-handoff': {
174
+ access: 'authenticated',
175
+ embeddedOnly: true,
176
+ wholeOrganization: true,
177
+ },
145
178
 
146
179
  'POST /api/v1/admin/login': { access: 'public' },
147
180
  'POST /api/v1/admin/logout': { access: 'admin' },
@@ -187,6 +220,7 @@ describe('security sweep', () => {
187
220
  email: 'sweep@example.com',
188
221
  code: '12345678',
189
222
  planCode: 'starter',
223
+ audience: 'user',
190
224
  ...victim,
191
225
  };
192
226
  let url = pattern.replace(/:([A-Za-z]+)/g, (_match, name: string) =>
@@ -212,6 +246,8 @@ describe('security sweep', () => {
212
246
  Object.entries(ROUTES)
213
247
  .filter(([, spec]) => spec.access === access)
214
248
  .map(([route]) => route);
249
+ /** A read that answers and ends: what can be asked with credentials that pass. */
250
+ const isRead = (route: string): boolean => route.startsWith('GET') && !ROUTES[route]?.stream;
215
251
  const standaloneOnly = (route: string): boolean => ROUTES[route]?.standaloneOnly === true;
216
252
  const embeddedOnly = (route: string): boolean => ROUTES[route]?.embeddedOnly === true;
217
253
  const wholeOrganization = (route: string): boolean => !!ROUTES[route]?.wholeOrganization;
@@ -386,7 +422,7 @@ describe('security sweep', () => {
386
422
 
387
423
  it("refuses the organization's own routes to the staff of a store a dashboard account connected, and only those", async () => {
388
424
  const routes = [...routesWith('authenticated'), ...routesWith('tenant')];
389
- expect(routes.filter(wholeOrganization).length).toBe(8);
425
+ expect(routes.filter(wholeOrganization).length).toBe(9);
390
426
  for (const route of routes.filter(wholeOrganization)) {
391
427
  const res = await send(route, aliceEmbedded);
392
428
  expect(res.statusCode, route).toBe(403);
@@ -401,7 +437,7 @@ describe('security sweep', () => {
401
437
  }
402
438
  // What it may read answers it as anyone of the organization's; the organization's own
403
439
  // routes answer the staff of a store installed from Shopify, and the dashboard.
404
- const reads = routes.filter((route) => route.startsWith('GET'));
440
+ const reads = routes.filter(isRead);
405
441
  for (const route of reads.filter((r) => !wholeOrganization(r))) {
406
442
  const res = await send(route, aliceEmbedded);
407
443
  expect(res.body, route).not.toMatch(WHOLE_ORGANIZATION_MESSAGE);
@@ -419,7 +455,7 @@ describe('security sweep', () => {
419
455
 
420
456
  it('refuses the embedded-only routes to a dashboard session, and asks Shopify nothing', async () => {
421
457
  const routes = Object.keys(ROUTES).filter(embeddedOnly);
422
- expect(routes.length).toBe(6);
458
+ expect(routes.length).toBe(7);
423
459
  for (const route of routes) {
424
460
  const res = await send(route, alice.headers);
425
461
  expect(res.statusCode, route).toBe(403);
@@ -429,7 +465,7 @@ describe('security sweep', () => {
429
465
  });
430
466
 
431
467
  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'))) {
468
+ for (const route of routesWith('authenticated').filter(isRead)) {
433
469
  for (const headers of [alice.headers, aliceEmbedded]) {
434
470
  const res = await send(route, headers);
435
471
  expect(res.body, route).not.toContain(SHOP);
@@ -439,9 +475,7 @@ describe('security sweep', () => {
439
475
  });
440
476
 
441
477
  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
- )) {
478
+ for (const route of [...routesWith('authenticated'), ...routesWith('tenant')].filter(isRead)) {
445
479
  const res = await send(route, bob.headers);
446
480
  expect(res.body, route).not.toContain(TOKEN_CIPHERTEXT);
447
481
  expect(res.body, route).not.toMatch(
@@ -518,18 +552,37 @@ type Access = 'public' | 'authenticated' | 'tenant' | 'admin';
518
552
  * organization; `body` and `query` say how to ask for one. A route added to the
519
553
  * application without a line here fails the first test below.
520
554
  */
521
- const ROUTES: Record<string, { access: Access; body?: string[]; query?: string[] }> = {
555
+ const ROUTES: Record<
556
+ string,
557
+ {
558
+ access: Access;
559
+ body?: string[];
560
+ query?: string[];
561
+ /** Answers with a stream that stays open: only asked where it is refused. */
562
+ stream?: true;
563
+ }
564
+ > = {
522
565
  'GET /health/live': { access: 'public' },
523
566
  'GET /health/ready': { access: 'public' },
524
567
  // Asking for a sign-in code and giving it back: open to anyone to try, limited per
525
568
  // email and per address, and worth nothing without the email's inbox.
526
569
  'POST /api/v1/auth/code': { access: 'public' },
527
570
  'POST /api/v1/auth/verify': { access: 'public' },
571
+ // Signing in with Google or GitHub: the providers offered, the redirect to one, and its
572
+ // return, authenticated by the state and the browser's cookie.
573
+ 'GET /api/v1/auth/providers': { access: 'public' },
574
+ 'GET /api/v1/auth/oauth/:provider/start': { access: 'public' },
575
+ 'GET /api/v1/auth/oauth/:provider/callback': { access: 'public' },
528
576
  // Authenticated by each gateway's signature over the raw body.
529
577
  'POST /api/v1/webhooks/:provider(stripe|razorpay)': { access: 'public' },
530
578
 
531
579
  'GET /api/v1/auth/me': { access: 'authenticated' },
532
580
  'POST /api/v1/auth/logout': { access: 'authenticated' },
581
+ // Several organizations per person: list them and move the session to another.
582
+ 'GET /api/v1/auth/organizations': { access: 'authenticated' },
583
+ 'POST /api/v1/auth/organization': { access: 'authenticated', body: ['organizationId'] },
584
+ // Spends the one-time code "Open dashboard" made; the code is the credential.
585
+ 'POST /api/v1/auth/handoff': { access: 'public', body: ['code'] },
533
586
  'GET /api/v1/plans': { access: 'authenticated' },
534
587
  'GET /api/v1/usage': { access: 'authenticated' },
535
588
  #@if standalone
@@ -540,6 +593,21 @@ const ROUTES: Record<string, { access: Access; body?: string[]; query?: string[]
540
593
  'GET /api/v1/auth/extension-keys': { access: 'authenticated' },
541
594
  'POST /api/v1/auth/extension-keys': { access: 'authenticated' },
542
595
  'POST /api/v1/settings/api-keys': { access: 'authenticated' },
596
+ // The caller's own inbox, choices and devices: every query is the caller's, so another
597
+ // organization's id finds nothing (notifications.int.test.ts). The stream never ends.
598
+ 'GET /api/v1/notifications': { access: 'authenticated' },
599
+ 'GET /api/v1/notifications/unread-count': { access: 'authenticated' },
600
+ 'POST /api/v1/notifications/read': { access: 'authenticated' },
601
+ 'POST /api/v1/notifications/read-all': { access: 'authenticated' },
602
+ 'GET /api/v1/notifications/stream': { access: 'authenticated', stream: true },
603
+ 'GET /api/v1/notifications/preferences': { access: 'authenticated' },
604
+ 'PUT /api/v1/notifications/preferences': { access: 'authenticated' },
605
+ // The organization's defaults for an audience: its owner's (audienceAdmins).
606
+ 'GET /api/v1/notifications/defaults/:audience': { access: 'authenticated' },
607
+ 'PUT /api/v1/notifications/defaults/:audience': { access: 'authenticated' },
608
+ 'GET /api/v1/notifications/push/key': { access: 'authenticated' },
609
+ 'POST /api/v1/notifications/push/subscriptions': { access: 'authenticated' },
610
+ 'DELETE /api/v1/notifications/push/subscriptions': { access: 'authenticated' },
543
611
  'POST /api/v1/billing/checkout': { access: 'authenticated' },
544
612
  'POST /api/v1/billing/cancel': { access: 'authenticated' },
545
613
 
@@ -577,6 +645,7 @@ describe('security sweep', () => {
577
645
  email: 'sweep@example.com',
578
646
  code: '12345678',
579
647
  planCode: 'starter',
648
+ audience: 'user',
580
649
  ...victim,
581
650
  };
582
651
  let url = pattern.replace(/:([A-Za-z]+)/g, (_match, name: string) =>
@@ -602,6 +671,8 @@ describe('security sweep', () => {
602
671
  Object.entries(ROUTES)
603
672
  .filter(([, spec]) => spec.access === access)
604
673
  .map(([route]) => route);
674
+ /** A read that answers and ends: what can be asked with credentials that pass. */
675
+ const isRead = (route: string): boolean => route.startsWith('GET') && !ROUTES[route]?.stream;
605
676
 
606
677
  beforeAll(async () => {
607
678
  h = await startHarness({ env: { CONNECTABLE_EXTENSION_IDS: SWEEP_EXTENSION } });
@@ -684,7 +755,7 @@ describe('security sweep', () => {
684
755
  });
685
756
 
686
757
  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'))) {
758
+ for (const route of routesWith('authenticated').filter(isRead)) {
688
759
  const res = await send(route, alice.headers);
689
760
  expect(res.body, route).not.toContain(bob.organizationId);
690
761
  expect(res.body, route).not.toContain(victim.apiKeyId);
@@ -692,9 +763,7 @@ describe('security sweep', () => {
692
763
  });
693
764
 
694
765
  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
- )) {
766
+ for (const route of [...routesWith('authenticated'), ...routesWith('tenant')].filter(isRead)) {
698
767
  const res = await send(route, bob.headers);
699
768
  expect(res.body, route).not.toMatch(
700
769
  /passwordHash|password_hash|keyHash|storageKey|accessToken/,
@@ -38,11 +38,18 @@ describe('seeding the plans file', () => {
38
38
  priceRef: 'shopify_starter_monthly',
39
39
  currency: 'USD',
40
40
  amountMinor: 1900,
41
+ interval: 'MONTH',
41
42
  planName: 'Starter',
42
43
  },
43
44
  ]);
44
45
  expect(await billing.pricesFor('pro', 'shopify')).toEqual([
45
- { priceRef: 'shopify_pro_monthly', currency: 'USD', amountMinor: 4900, planName: 'Pro' },
46
+ {
47
+ priceRef: 'shopify_pro_monthly',
48
+ currency: 'USD',
49
+ amountMinor: 4900,
50
+ interval: 'MONTH',
51
+ planName: 'Pro',
52
+ },
46
53
  ]);
47
54
  expect(await billing.pricesFor('pro', 'razorpay')).toHaveLength(1);
48
55
  expect((await billing.pricesOf('shopify')).map((price) => price.planCode).sort()).toEqual([
@@ -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();
@@ -6,6 +6,8 @@
6
6
  <meta name="shopify-api-key" content="%VITE_SHOPIFY_API_KEY%" />
7
7
  <!-- App Bridge must load from Shopify's CDN, before any other script. -->
8
8
  <script src="https://cdn.shopify.com/shopifycloud/app-bridge.js"></script>
9
+ <!-- Sets the chosen light or dark theme before the page paints (a file: the CSP forbids inline scripts). -->
10
+ <script src="/theme-boot.js"></script>
9
11
  <title>@@Name@@</title>
10
12
  <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
11
13
  </head>
@@ -0,0 +1,6 @@
1
+ (function () {
2
+ try {
3
+ var choice = window.localStorage.getItem('haatlabs:theme');
4
+ if (choice === 'light' || choice === 'dark') document.documentElement.setAttribute('data-theme', choice);
5
+ } catch {}
6
+ })();
@@ -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",