@terreno/comms 56.0.0-beta.2

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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/biome.jsonc +17 -0
  3. package/bunfig.toml +5 -0
  4. package/dist/adapters/console.d.ts +30 -0
  5. package/dist/adapters/console.js +122 -0
  6. package/dist/commsApp.d.ts +14 -0
  7. package/dist/commsApp.js +37 -0
  8. package/dist/commsService.d.ts +20 -0
  9. package/dist/commsService.js +386 -0
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.js +19 -0
  12. package/dist/modelTypes.d.ts +53 -0
  13. package/dist/modelTypes.js +2 -0
  14. package/dist/models/commsMessage.d.ts +2 -0
  15. package/dist/models/commsMessage.js +119 -0
  16. package/dist/models/pushToken.d.ts +2 -0
  17. package/dist/models/pushToken.js +56 -0
  18. package/dist/routes/commsExplorer.d.ts +7 -0
  19. package/dist/routes/commsExplorer.js +147 -0
  20. package/dist/routes/pushTokens.d.ts +7 -0
  21. package/dist/routes/pushTokens.js +292 -0
  22. package/dist/templates.d.ts +10 -0
  23. package/dist/templates.js +32 -0
  24. package/dist/types.d.ts +78 -0
  25. package/dist/types.js +2 -0
  26. package/package.json +55 -0
  27. package/src/adapters/console.test.ts +227 -0
  28. package/src/adapters/console.ts +87 -0
  29. package/src/commsApp.test.ts +448 -0
  30. package/src/commsApp.ts +48 -0
  31. package/src/commsService.test.ts +570 -0
  32. package/src/commsService.ts +293 -0
  33. package/src/index.ts +45 -0
  34. package/src/modelTypes.ts +78 -0
  35. package/src/models/commsMessage.test.ts +53 -0
  36. package/src/models/commsMessage.ts +97 -0
  37. package/src/models/pushToken.test.ts +45 -0
  38. package/src/models/pushToken.ts +69 -0
  39. package/src/routes/commsExplorer.ts +114 -0
  40. package/src/routes/pushTokens.ts +265 -0
  41. package/src/templates.test.ts +37 -0
  42. package/src/templates.ts +31 -0
  43. package/src/tests/bunSetup.ts +14 -0
  44. package/src/types.ts +93 -0
  45. package/tsconfig.json +32 -0
@@ -0,0 +1,114 @@
1
+ import {
2
+ APIError,
3
+ asyncHandler,
4
+ authenticateMiddleware,
5
+ createOpenApiBuilder,
6
+ type OpenApiMiddleware,
7
+ } from "@terreno/api";
8
+ import type express from "express";
9
+ import {DateTime} from "luxon";
10
+
11
+ import {CommsMessage} from "../models/commsMessage";
12
+
13
+ interface CommsExplorerRouteOptions {
14
+ path?: string;
15
+ openApi?: unknown;
16
+ }
17
+
18
+ export const addCommsExplorerRoute = (
19
+ app: express.Application,
20
+ options?: CommsExplorerRouteOptions
21
+ ): void => {
22
+ const routeOpenApi = options?.openApi ? {openApi: options.openApi as OpenApiMiddleware} : {};
23
+
24
+ app.get(
25
+ options?.path ?? "/comms/messages",
26
+ [
27
+ authenticateMiddleware(),
28
+ createOpenApiBuilder(routeOpenApi)
29
+ .withTags(["admin", "comms"])
30
+ .withSummary("List communication delivery attempts")
31
+ .withQueryParameter("page", {type: "number"}, {required: false})
32
+ .withQueryParameter("limit", {type: "number"}, {required: false})
33
+ .withQueryParameter("channel", {type: "string"}, {required: false})
34
+ .withQueryParameter("status", {type: "string"}, {required: false})
35
+ .withQueryParameter("userId", {type: "string"}, {required: false})
36
+ .withQueryParameter("startDate", {type: "string"}, {required: false})
37
+ .withQueryParameter("endDate", {type: "string"}, {required: false})
38
+ .withResponse(200, {
39
+ data: {items: {type: "object"}, type: "array"},
40
+ limit: {type: "number"},
41
+ more: {type: "boolean"},
42
+ page: {type: "number"},
43
+ total: {type: "number"},
44
+ })
45
+ .build(),
46
+ ],
47
+ asyncHandler(async (req: express.Request, res: express.Response) => {
48
+ const user = req.user as {admin?: boolean} | undefined;
49
+ if (!user?.admin) {
50
+ throw new APIError({status: 403, title: "Admin access required"});
51
+ }
52
+
53
+ const page = Math.max(1, Number.parseInt(req.query.page as string, 10) || 1);
54
+ const limit = Math.min(
55
+ 100,
56
+ Math.max(1, Number.parseInt(req.query.limit as string, 10) || 20)
57
+ );
58
+ const skip = (page - 1) * limit;
59
+ const match: Record<string, unknown> & {created?: {$gte?: Date; $lte?: Date}} = {
60
+ deleted: {$ne: true},
61
+ };
62
+ let startTimestamp: number | undefined;
63
+ let endTimestamp: number | undefined;
64
+
65
+ if (req.query.channel) {
66
+ match.channel = req.query.channel;
67
+ }
68
+ if (req.query.status) {
69
+ match.status = req.query.status;
70
+ }
71
+ if (req.query.userId) {
72
+ match.userId = req.query.userId;
73
+ }
74
+ if (req.query.startDate || req.query.endDate) {
75
+ match.created = {};
76
+ }
77
+ if (req.query.startDate && match.created) {
78
+ const start = DateTime.fromISO(req.query.startDate as string, {zone: "utc"});
79
+ if (!start.isValid) {
80
+ throw new APIError({status: 400, title: "Invalid startDate format"});
81
+ }
82
+ startTimestamp = start.toMillis();
83
+ match.created.$gte = start.toJSDate();
84
+ }
85
+ if (req.query.endDate && match.created) {
86
+ const end = DateTime.fromISO(req.query.endDate as string, {zone: "utc"});
87
+ if (!end.isValid) {
88
+ throw new APIError({status: 400, title: "Invalid endDate format"});
89
+ }
90
+ endTimestamp = end.toMillis();
91
+ match.created.$lte = end.toJSDate();
92
+ }
93
+ if (
94
+ startTimestamp !== undefined &&
95
+ endTimestamp !== undefined &&
96
+ startTimestamp > endTimestamp
97
+ ) {
98
+ throw new APIError({status: 400, title: "startDate must not be after endDate"});
99
+ }
100
+
101
+ const [messages, total] = await Promise.all([
102
+ CommsMessage.find(match).sort("-created").skip(skip).limit(limit),
103
+ CommsMessage.countDocuments(match),
104
+ ]);
105
+ return res.json({
106
+ data: messages,
107
+ limit,
108
+ more: skip + limit < total,
109
+ page,
110
+ total,
111
+ });
112
+ })
113
+ );
114
+ };
@@ -0,0 +1,265 @@
1
+ import {
2
+ APIError,
3
+ asyncHandler,
4
+ authenticateMiddleware,
5
+ createOpenApiBuilder,
6
+ type ModelRouterOptions,
7
+ modelRouter,
8
+ type OpenApiMiddleware,
9
+ Permissions,
10
+ } from "@terreno/api";
11
+ import type express from "express";
12
+ import {DateTime} from "luxon";
13
+ import type {Model, QueryFilter, Types} from "mongoose";
14
+ import {PushToken} from "../models/pushToken";
15
+ import type {PushTokenDocument, PushTokenPlatform} from "../modelTypes";
16
+
17
+ interface PushTokenRouteOptions {
18
+ basePath?: string;
19
+ openApi?: unknown;
20
+ }
21
+
22
+ interface PushTokenRequestBody {
23
+ deviceId?: string;
24
+ platform?: PushTokenPlatform;
25
+ token?: string;
26
+ }
27
+
28
+ const platformValues: PushTokenPlatform[] = ["android", "ios", "web"];
29
+
30
+ const openApiOptions = (openApi?: unknown): {openApi?: OpenApiMiddleware} =>
31
+ openApi ? {openApi: openApi as OpenApiMiddleware} : {};
32
+
33
+ const getAuthenticatedUser = (
34
+ req: express.Request
35
+ ): {_id: unknown; admin?: boolean; id?: string} => {
36
+ const user = req.user as {_id?: unknown; admin?: boolean; id?: string} | undefined;
37
+ if (!user?._id) {
38
+ throw new APIError({status: 401, title: "Authentication required"});
39
+ }
40
+ return user as {_id: unknown; admin?: boolean; id?: string};
41
+ };
42
+
43
+ const isDuplicateKeyError = (error: unknown): boolean =>
44
+ (error as {code?: number} | undefined)?.code === 11000;
45
+
46
+ /**
47
+ * Claims a device token for the caller in a single atomic statement.
48
+ *
49
+ * The filter only matches a token that is unclaimed, already the caller's, or released by its
50
+ * previous owner, so a concurrent request can never transfer an active token between accounts.
51
+ * A token held by another user fails the filter, and the unique index turns the resulting upsert
52
+ * insert into a duplicate-key error that surfaces as a conflict.
53
+ */
54
+ const claimPushToken = async ({
55
+ deviceId,
56
+ platform,
57
+ token,
58
+ userId,
59
+ }: {
60
+ deviceId?: string;
61
+ platform: PushTokenPlatform;
62
+ token: string;
63
+ userId: Types.ObjectId;
64
+ }): Promise<{created: boolean; document: PushTokenDocument}> => {
65
+ const now = DateTime.utc().toJSDate();
66
+ const claimableFilter: QueryFilter<PushTokenDocument> = {
67
+ $or: [{userId}, {active: false}],
68
+ token,
69
+ };
70
+ const result = await PushToken.findOneAndUpdate(
71
+ claimableFilter,
72
+ {
73
+ // createdUpdatedPlugin only hooks save(), so timestamps are maintained here.
74
+ $set: {
75
+ active: true,
76
+ deleted: false,
77
+ // Omitting deviceId preserves a previously registered identifier on refresh.
78
+ ...(deviceId === undefined ? {} : {deviceId}),
79
+ lastSeenAt: now,
80
+ platform,
81
+ updated: now,
82
+ userId,
83
+ },
84
+ $setOnInsert: {created: now},
85
+ },
86
+ {
87
+ includeResultMetadata: true,
88
+ returnDocument: "after",
89
+ runValidators: true,
90
+ upsert: true,
91
+ }
92
+ );
93
+
94
+ if (!result.value) {
95
+ throw new APIError({status: 500, title: "Push token claim returned no document"});
96
+ }
97
+ return {created: result.lastErrorObject?.updatedExisting !== true, document: result.value};
98
+ };
99
+
100
+ export const addPushTokenRoutes = (
101
+ app: express.Application,
102
+ options?: PushTokenRouteOptions
103
+ ): void => {
104
+ const basePath = options?.basePath ?? "/comms/pushTokens";
105
+ const routeOpenApi = openApiOptions(options?.openApi);
106
+
107
+ // A dedicated create endpoint is required because modelRouter create cannot provide
108
+ // the idempotent token upsert contract used by device registration.
109
+ app.post(
110
+ basePath,
111
+ [
112
+ authenticateMiddleware(),
113
+ createOpenApiBuilder(routeOpenApi)
114
+ .withTags(["comms"])
115
+ .withSummary("Register or refresh a push token")
116
+ .withRequestBody({
117
+ deviceId: {type: "string"},
118
+ platform: {
119
+ description: "Device platform: android, ios, or web",
120
+ required: true,
121
+ type: "string",
122
+ },
123
+ token: {required: true, type: "string"},
124
+ })
125
+ .withResponse(200, {data: {type: "object"}})
126
+ .withResponse(201, {data: {type: "object"}})
127
+ .build(),
128
+ ],
129
+ asyncHandler(async (req: express.Request, res: express.Response) => {
130
+ const user = getAuthenticatedUser(req);
131
+ const body = req.body as PushTokenRequestBody;
132
+ if (!body.token?.trim()) {
133
+ throw new APIError({status: 400, title: "Push token is required"});
134
+ }
135
+ if (!body.platform || !platformValues.includes(body.platform)) {
136
+ throw new APIError({status: 400, title: "Valid push platform is required"});
137
+ }
138
+
139
+ const claim = {
140
+ deviceId: body.deviceId,
141
+ platform: body.platform,
142
+ token: body.token,
143
+ userId: user._id as Types.ObjectId,
144
+ };
145
+
146
+ let result: {created: boolean; document: PushTokenDocument};
147
+ try {
148
+ result = await claimPushToken(claim);
149
+ } catch (error: unknown) {
150
+ if (!isDuplicateKeyError(error)) {
151
+ throw error;
152
+ }
153
+ // A concurrent insert won the race. Retrying resolves the caller's own duplicate
154
+ // registration and leaves a genuinely foreign token failing the filter again.
155
+ try {
156
+ result = await claimPushToken(claim);
157
+ } catch (retryError: unknown) {
158
+ if (!isDuplicateKeyError(retryError)) {
159
+ throw retryError;
160
+ }
161
+ throw new APIError({status: 409, title: "Push token is registered to another user"});
162
+ }
163
+ }
164
+
165
+ return res.status(result.created ? 201 : 200).json({data: result.document});
166
+ })
167
+ );
168
+
169
+ app.get(
170
+ basePath,
171
+ [
172
+ authenticateMiddleware(),
173
+ createOpenApiBuilder(routeOpenApi)
174
+ .withTags(["comms"])
175
+ .withSummary("List the current user's push tokens")
176
+ .withQueryParameter("page", {type: "number"}, {required: false})
177
+ .withQueryParameter("limit", {type: "number"}, {required: false})
178
+ .withQueryParameter("active", {type: "boolean"}, {required: false})
179
+ .withQueryParameter("platform", {type: "string"}, {required: false})
180
+ .withResponse(200, {
181
+ data: {items: {type: "object"}, type: "array"},
182
+ limit: {type: "number"},
183
+ more: {type: "boolean"},
184
+ page: {type: "number"},
185
+ total: {type: "number"},
186
+ })
187
+ .build(),
188
+ ],
189
+ asyncHandler(async (req: express.Request, res: express.Response) => {
190
+ const user = getAuthenticatedUser(req);
191
+ const page = Math.max(1, Number.parseInt(req.query.page as string, 10) || 1);
192
+ const limit = Math.min(
193
+ 100,
194
+ Math.max(1, Number.parseInt(req.query.limit as string, 10) || 20)
195
+ );
196
+ const skip = (page - 1) * limit;
197
+ const match: Record<string, unknown> = {userId: user._id};
198
+ if (req.query.active === "true" || req.query.active === "false") {
199
+ match.active = req.query.active === "true";
200
+ }
201
+ if (req.query.platform) {
202
+ match.platform = req.query.platform;
203
+ }
204
+ const [tokens, total] = await Promise.all([
205
+ PushToken.find(match).sort("-lastSeenAt").skip(skip).limit(limit),
206
+ PushToken.countDocuments(match),
207
+ ]);
208
+ return res.json({
209
+ data: tokens,
210
+ limit,
211
+ more: skip + limit < total,
212
+ page,
213
+ total,
214
+ });
215
+ })
216
+ );
217
+
218
+ app.delete(
219
+ `${basePath}/:id`,
220
+ [
221
+ authenticateMiddleware(),
222
+ createOpenApiBuilder(routeOpenApi)
223
+ .withTags(["comms"])
224
+ .withSummary("Deactivate a push token")
225
+ .withPathParameter("id", {type: "string"})
226
+ .withResponse(204, {})
227
+ .build(),
228
+ ],
229
+ asyncHandler(async (req: express.Request, res: express.Response) => {
230
+ const user = getAuthenticatedUser(req);
231
+ const token = await PushToken.findExactlyOne({_id: req.params.id});
232
+ const isOwner = token.userId.toString() === String(user._id);
233
+ if (!isOwner) {
234
+ throw new APIError({status: 403, title: "Push token belongs to another user"});
235
+ }
236
+
237
+ token.active = false;
238
+ await token.save();
239
+ return res.status(204).send();
240
+ })
241
+ );
242
+
243
+ const routerOptions: ModelRouterOptions<PushTokenDocument> = {
244
+ ...routeOpenApi,
245
+ // Share the "comms" tag with the custom routes so generated SDK mutations invalidate this read.
246
+ openApiOverwrite: {get: {tags: ["comms"]}},
247
+ permissions: {
248
+ create: [],
249
+ delete: [],
250
+ list: [],
251
+ read: [Permissions.IsOwner],
252
+ update: [],
253
+ },
254
+ queryFields: ["active", "platform"],
255
+ // PushToken persists userId, while OwnerQueryFilter targets a persisted ownerId field.
256
+ queryFilter: (user) => {
257
+ if (!user) {
258
+ return null;
259
+ }
260
+ return {userId: user.id};
261
+ },
262
+ sort: "-lastSeenAt",
263
+ };
264
+ app.use(basePath, modelRouter(PushToken as Model<PushTokenDocument>, routerOptions));
265
+ };
@@ -0,0 +1,37 @@
1
+ import {describe, it} from "bun:test";
2
+ import {assert} from "chai";
3
+
4
+ import {renderTemplate} from "./templates";
5
+
6
+ describe("renderTemplate", () => {
7
+ it("interpolates own data fields across subject, text, and html", (): void => {
8
+ const rendered = renderTemplate({
9
+ data: {name: "Ada"},
10
+ template: {
11
+ html: "<p>Hello {{name}}</p>",
12
+ subject: "Welcome, {{ name }}",
13
+ text: "Hello {{name}}",
14
+ },
15
+ });
16
+
17
+ assert.deepEqual(rendered, {
18
+ html: "<p>Hello Ada</p>",
19
+ subject: "Welcome, Ada",
20
+ text: "Hello Ada",
21
+ });
22
+ });
23
+
24
+ it("does not resolve inherited or missing values", (): void => {
25
+ const data = Object.create({constructor: "unsafe"}) as Record<string, unknown>;
26
+ data.name = "Ada";
27
+
28
+ const rendered = renderTemplate({
29
+ data,
30
+ template: {
31
+ subject: "{{constructor}} {{missing}} {{name}}",
32
+ },
33
+ });
34
+
35
+ assert.equal(rendered.subject, " Ada");
36
+ });
37
+ });
@@ -0,0 +1,31 @@
1
+ export interface MessageTemplate {
2
+ html?: string;
3
+ subject: string;
4
+ text?: string;
5
+ }
6
+
7
+ export interface RenderTemplateOptions {
8
+ data: Record<string, unknown>;
9
+ template: MessageTemplate;
10
+ }
11
+
12
+ const TEMPLATE_VARIABLE_PATTERN = /{{\s*([A-Za-z0-9_]+)\s*}}/g;
13
+
14
+ const interpolate = (value: string, data: Record<string, unknown>): string =>
15
+ value.replace(TEMPLATE_VARIABLE_PATTERN, (_match: string, key: string): string => {
16
+ if (Object.getOwnPropertyDescriptor(data, key) === undefined) {
17
+ return "";
18
+ }
19
+
20
+ const replacement = data[key];
21
+ if (replacement === null || replacement === undefined) {
22
+ return "";
23
+ }
24
+ return String(replacement);
25
+ });
26
+
27
+ export const renderTemplate = ({data, template}: RenderTemplateOptions): MessageTemplate => ({
28
+ ...(template.html === undefined ? {} : {html: interpolate(template.html, data)}),
29
+ subject: interpolate(template.subject, data),
30
+ ...(template.text === undefined ? {} : {text: interpolate(template.text, data)}),
31
+ });
@@ -0,0 +1,14 @@
1
+ import {beforeEach} from "bun:test";
2
+ import {registerSimpleMongoPreload} from "@terreno/test";
3
+
4
+ process.env.TERRENO_TEST_USE_MEMORY_MONGO = "true";
5
+
6
+ registerSimpleMongoPreload({
7
+ testEnv: {
8
+ tokenIssuer: "terreno-comms.test",
9
+ },
10
+ });
11
+
12
+ beforeEach((): void => {
13
+ process.env.NODE_ENV = "test";
14
+ });
package/src/types.ts ADDED
@@ -0,0 +1,93 @@
1
+ import type mongoose from "mongoose";
2
+
3
+ export interface SendResult {
4
+ accepted: boolean;
5
+ error?: string;
6
+ isPermanentFailure?: boolean;
7
+ providerMessageId?: string;
8
+ }
9
+
10
+ export interface MailMessage {
11
+ from?: string;
12
+ html?: string;
13
+ metadata?: Record<string, string>;
14
+ replyTo?: string;
15
+ subject: string;
16
+ text?: string;
17
+ to: string | string[];
18
+ }
19
+
20
+ export interface MailProvider {
21
+ readonly id: string;
22
+ sendMail(message: MailMessage): Promise<SendResult>;
23
+ }
24
+
25
+ export interface SmsMessage {
26
+ body: string;
27
+ to: string;
28
+ }
29
+
30
+ export interface SmsProvider {
31
+ readonly id: string;
32
+ sendSms(message: SmsMessage): Promise<SendResult>;
33
+ }
34
+
35
+ export interface PushMessage {
36
+ badge?: number;
37
+ body: string;
38
+ data?: Record<string, unknown>;
39
+ sound?: string | null;
40
+ title: string;
41
+ tokens: string[];
42
+ }
43
+
44
+ export interface PushProvider {
45
+ readonly id: string;
46
+ sendPush(message: PushMessage): Promise<SendResult[]>;
47
+ }
48
+
49
+ export interface StartVerificationOptions {
50
+ channel: "email" | "sms";
51
+ to: string;
52
+ }
53
+
54
+ export interface CheckVerificationOptions {
55
+ code: string;
56
+ to: string;
57
+ }
58
+
59
+ export interface VerificationResult {
60
+ error?: string;
61
+ valid: boolean;
62
+ }
63
+
64
+ export interface VerificationProvider {
65
+ readonly id: string;
66
+ checkVerification(options: CheckVerificationOptions): Promise<VerificationResult>;
67
+ startVerification(options: StartVerificationOptions): Promise<SendResult>;
68
+ }
69
+
70
+ export interface DeliveryEvent {
71
+ channel: "mail" | "push" | "sms";
72
+ providerMessageId: string;
73
+ raw?: unknown;
74
+ status: "bounced" | "delivered" | "failed" | "opened";
75
+ }
76
+
77
+ export type CommsChannel = "mail" | "push" | "sms" | "verification";
78
+ export type CommsMessageStatus = "bounced" | "delivered" | "failed" | "sent";
79
+
80
+ export interface CommsOptions {
81
+ defaultFrom?: string;
82
+ logMessages?: boolean;
83
+ mail?: MailProvider;
84
+ onDeliveryEvent?: (event: DeliveryEvent) => Promise<void>;
85
+ push?: PushProvider;
86
+ redactRecipients?: boolean;
87
+ sms?: SmsProvider;
88
+ verification?: VerificationProvider;
89
+ }
90
+
91
+ export interface SendPushToUserMessage extends Omit<PushMessage, "tokens"> {
92
+ userId: mongoose.Types.ObjectId | string;
93
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "compilerOptions": {
3
+ "allowJs": true,
4
+ "allowSyntheticDefaultImports": true,
5
+ "baseUrl": "./",
6
+ "declaration": true,
7
+ "downlevelIteration": true,
8
+ "esModuleInterop": true,
9
+ "forceConsistentCasingInFileNames": true,
10
+ "ignoreDeprecations": "6.0",
11
+ "lib": ["es2017", "dom", "es2017.object"],
12
+ "module": "commonjs",
13
+ "moduleResolution": "node",
14
+ "noEmit": false,
15
+ "noImplicitAny": false,
16
+ "noImplicitReturns": true,
17
+ "noImplicitThis": true,
18
+ "noUnusedLocals": false,
19
+ "noUnusedParameters": false,
20
+ "outDir": "./dist",
21
+ "preserveConstEnums": true,
22
+ "removeComments": false,
23
+ "rootDir": "./src",
24
+ "skipLibCheck": true,
25
+ "strict": true,
26
+ "strictFunctionTypes": true,
27
+ "strictNullChecks": true,
28
+ "target": "es5"
29
+ },
30
+ "exclude": ["node_modules", "src/**/*.test.ts", "src/tests/**"],
31
+ "include": ["src/**/*.ts", "src/*.ts"]
32
+ }