pipework 0.70.0 → 0.71.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/REFERENCE.md +34 -4
- package/dist/REFERENCE.md +124 -2
- package/dist/core/config/schema.js +1 -1
- package/dist/core/config/schema.js.map +1 -1
- package/dist/data/migrate/internal-definitions.d.ts.map +1 -1
- package/dist/data/migrate/internal-definitions.js +2 -1
- package/dist/data/migrate/internal-definitions.js.map +1 -1
- package/dist/infra/email/audit.d.ts +2 -2
- package/dist/infra/email/audit.d.ts.map +1 -1
- package/dist/infra/email/audit.js +3 -3
- package/dist/infra/email/audit.js.map +1 -1
- package/dist/infra/email/inbound.d.ts +199 -0
- package/dist/infra/email/inbound.d.ts.map +1 -0
- package/dist/infra/email/inbound.js +451 -0
- package/dist/infra/email/inbound.js.map +1 -0
- package/dist/infra/email/index.d.ts +1 -0
- package/dist/infra/email/index.d.ts.map +1 -1
- package/dist/infra/email/index.js +1 -0
- package/dist/infra/email/index.js.map +1 -1
- package/dist/infra/email/mail.d.ts +14 -1
- package/dist/infra/email/mail.d.ts.map +1 -1
- package/dist/infra/email/mail.js +39 -3
- package/dist/infra/email/mail.js.map +1 -1
- package/dist/infra/email/mime.d.ts +38 -0
- package/dist/infra/email/mime.d.ts.map +1 -0
- package/dist/infra/email/mime.js +474 -0
- package/dist/infra/email/mime.js.map +1 -0
- package/dist/infra/email/namespace.d.ts +8 -1
- package/dist/infra/email/namespace.d.ts.map +1 -1
- package/dist/infra/email/namespace.js +8 -1
- package/dist/infra/email/namespace.js.map +1 -1
- package/dist/infra/email/providers.d.ts +3 -1
- package/dist/infra/email/providers.d.ts.map +1 -1
- package/dist/infra/email/providers.js +8 -3
- package/dist/infra/email/providers.js.map +1 -1
- package/dist/infra/email/schema.d.ts +109 -0
- package/dist/infra/email/schema.d.ts.map +1 -1
- package/dist/infra/email/schema.js +39 -1
- package/dist/infra/email/schema.js.map +1 -1
- package/dist/infra/email/sns.d.ts +14 -0
- package/dist/infra/email/sns.d.ts.map +1 -1
- package/dist/infra/email/sns.js +37 -23
- package/dist/infra/email/sns.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import type { Queue } from '../../async/jobs/queue.js';
|
|
2
|
+
import type { Handler } from '../../request/di/types.js';
|
|
3
|
+
import type { StorageBackend } from '../storage/backend.js';
|
|
4
|
+
import type { Storage, StoredFile } from '../storage/handle.js';
|
|
5
|
+
export declare const RECEIVE_JOB = "pipework.email.receive";
|
|
6
|
+
export interface EmailAddress {
|
|
7
|
+
readonly address: string;
|
|
8
|
+
readonly name: string;
|
|
9
|
+
}
|
|
10
|
+
export interface ReceivedAttachment {
|
|
11
|
+
readonly filename: string | null;
|
|
12
|
+
readonly mediaType: string;
|
|
13
|
+
readonly size: number;
|
|
14
|
+
/** Lowercase hex SHA-256 of the decoded content. */
|
|
15
|
+
readonly sha256: string;
|
|
16
|
+
/** The `Content-ID` without angle brackets, for `cid:` references from the HTML. */
|
|
17
|
+
readonly contentId: string | null;
|
|
18
|
+
readonly inline: boolean;
|
|
19
|
+
/** The stored file, or `null` when no tenant was resolved or no `storage` was given. */
|
|
20
|
+
readonly file: StoredFile | null;
|
|
21
|
+
}
|
|
22
|
+
/** What SES concluded about a received message: each of `PASS`, `FAIL`, `GRAY` or `PROCESSING_FAILED`. */
|
|
23
|
+
export interface EmailVerdicts {
|
|
24
|
+
readonly spam: string | null;
|
|
25
|
+
readonly virus: string | null;
|
|
26
|
+
readonly spf: string | null;
|
|
27
|
+
readonly dkim: string | null;
|
|
28
|
+
readonly dmarc: string | null;
|
|
29
|
+
}
|
|
30
|
+
/** What is known about a message before it is threaded: everything but its conversation and tenant. Handed to `resolveTenant`. */
|
|
31
|
+
export type UnthreadedEmail = Omit<ReceivedEmail, 'conversationId' | 'isNewConversation' | 'tenantId'>;
|
|
32
|
+
/** A received, parsed and threaded message, as handed to `onMessage`. */
|
|
33
|
+
export interface ReceivedEmail {
|
|
34
|
+
/** The `pipework_email_inbound` row id; pass it as `inReplyTo` to `mail.send` to answer. */
|
|
35
|
+
readonly id: string;
|
|
36
|
+
readonly conversationId: string;
|
|
37
|
+
/** True when no earlier received or sent message matched this one's `In-Reply-To`/`References`. */
|
|
38
|
+
readonly isNewConversation: boolean;
|
|
39
|
+
readonly tenantId: string | null;
|
|
40
|
+
/** The `Message-ID` without angle brackets, or `null`. */
|
|
41
|
+
readonly messageId: string | null;
|
|
42
|
+
readonly inReplyTo: string | null;
|
|
43
|
+
readonly references: readonly string[];
|
|
44
|
+
/** An empty address and name when the message has no readable From. */
|
|
45
|
+
readonly from: EmailAddress;
|
|
46
|
+
readonly to: readonly EmailAddress[];
|
|
47
|
+
readonly cc: readonly EmailAddress[];
|
|
48
|
+
readonly replyTo: readonly EmailAddress[];
|
|
49
|
+
readonly subject: string;
|
|
50
|
+
readonly date: Date | null;
|
|
51
|
+
readonly text: string | null;
|
|
52
|
+
readonly html: string | null;
|
|
53
|
+
readonly attachments: readonly ReceivedAttachment[];
|
|
54
|
+
/** `null` for a message from the folder stand-in. */
|
|
55
|
+
readonly verdicts: EmailVerdicts | null;
|
|
56
|
+
/** The envelope recipients SES accepted the message for; for the stand-in, the To and Cc addresses. */
|
|
57
|
+
readonly recipients: readonly string[];
|
|
58
|
+
}
|
|
59
|
+
/** A received message's row, without bodies. */
|
|
60
|
+
export interface InboundRecord {
|
|
61
|
+
readonly id: string;
|
|
62
|
+
readonly source: 'ses' | 'folder';
|
|
63
|
+
readonly status: 'received' | 'processed' | 'failed';
|
|
64
|
+
readonly error: string | null;
|
|
65
|
+
readonly messageId: string | null;
|
|
66
|
+
readonly conversationId: string | null;
|
|
67
|
+
readonly tenantId: string | null;
|
|
68
|
+
readonly subject: string | null;
|
|
69
|
+
readonly fromAddress: string | null;
|
|
70
|
+
readonly verdicts: EmailVerdicts | null;
|
|
71
|
+
readonly receivedAt: Date;
|
|
72
|
+
readonly processedAt: Date | null;
|
|
73
|
+
readonly rawExpiresAt: Date;
|
|
74
|
+
readonly rawDeletedAt: Date | null;
|
|
75
|
+
}
|
|
76
|
+
export interface InboundSweepResult {
|
|
77
|
+
/** Raw copies deleted. */
|
|
78
|
+
readonly deleted: number;
|
|
79
|
+
/** Raw copies that could not be deleted (left for the next sweep). */
|
|
80
|
+
readonly failed: number;
|
|
81
|
+
}
|
|
82
|
+
export interface InboundScanResult {
|
|
83
|
+
/** Files taken in. */
|
|
84
|
+
readonly received: number;
|
|
85
|
+
/** Files already taken in earlier (same bytes); moved to `received/` without a new row. */
|
|
86
|
+
readonly duplicates: number;
|
|
87
|
+
}
|
|
88
|
+
type RawLocation = Record<string, unknown>;
|
|
89
|
+
/** Where received mail comes from. Made by `mail.sesReceipt` or `mail.inboundFolder`. */
|
|
90
|
+
export interface InboundSource {
|
|
91
|
+
readonly kind: 'ses' | 'folder';
|
|
92
|
+
/** Reads the raw message; throws `RawTooLargeError` past `maxBytes` and `RawNotFoundError` when it definitely does not exist. */
|
|
93
|
+
read(location: RawLocation, maxBytes: number): Promise<Buffer>;
|
|
94
|
+
remove(location: RawLocation): Promise<void>;
|
|
95
|
+
readonly ses?: SesReceiptConfig;
|
|
96
|
+
readonly folder?: {
|
|
97
|
+
readonly dir: string;
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
export declare class RawNotFoundError extends Error {
|
|
101
|
+
constructor(detail: string);
|
|
102
|
+
}
|
|
103
|
+
export declare class RawTooLargeError extends Error {
|
|
104
|
+
readonly maxBytes: number;
|
|
105
|
+
constructor(maxBytes: number);
|
|
106
|
+
}
|
|
107
|
+
export interface SesReceiptConfig {
|
|
108
|
+
/** A storage backend over the SES receipt bucket with no prefix (`storage.s3({ bucket, region, credentials })`); keys are the S3 action's object keys. */
|
|
109
|
+
readonly bucket: StorageBackend;
|
|
110
|
+
/** The SNS topics SES publishes receipt notifications to. */
|
|
111
|
+
readonly topicArns: readonly string[];
|
|
112
|
+
readonly region?: string;
|
|
113
|
+
readonly fetchCert?: (url: string) => Promise<string>;
|
|
114
|
+
readonly confirm?: (url: string) => Promise<void>;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* The SES receipt source. SES stores each raw message in S3 (receipt rule action "S3" with an SNS topic)
|
|
118
|
+
* and notifies the topic; `inbound.webhook` verifies the notification and records it, and the receive job
|
|
119
|
+
* reads the object from `bucket`. A notification whose action is not S3 (for example the SNS action,
|
|
120
|
+
* which carries the message inline), or whose type is not `Received`, is answered 200 and ignored.
|
|
121
|
+
*/
|
|
122
|
+
export declare function sesReceipt(config: SesReceiptConfig): InboundSource;
|
|
123
|
+
/**
|
|
124
|
+
* The development source: `.eml` files dropped in `dir` are received by `inbound.scan()`, which copies each
|
|
125
|
+
* to `<dir>/received/` (where the raw copy stays until `sweep`) and removes the original. Refused when the
|
|
126
|
+
* environment is `production`.
|
|
127
|
+
*/
|
|
128
|
+
export declare function inboundFolder(config: {
|
|
129
|
+
readonly dir: string;
|
|
130
|
+
}): InboundSource;
|
|
131
|
+
export interface InboundConfig {
|
|
132
|
+
readonly source: InboundSource;
|
|
133
|
+
/** The app's job queue; its worker surface must run `inbound.jobs`. */
|
|
134
|
+
readonly queue: Queue;
|
|
135
|
+
/**
|
|
136
|
+
* Called in the receive job with each parsed, threaded message. A throw makes the queue retry the job.
|
|
137
|
+
* It is called at least once per message: a retry after a handler error, or a job re-run after a crash,
|
|
138
|
+
* calls it again with the same `id`. Make it idempotent on `id`.
|
|
139
|
+
*/
|
|
140
|
+
readonly onMessage: (email: ReceivedEmail) => Promise<void> | void;
|
|
141
|
+
/** Stores attachments (as the resolved tenant's files). Without it, or without a tenant, attachments have `file: null`. */
|
|
142
|
+
readonly storage?: Storage;
|
|
143
|
+
/**
|
|
144
|
+
* Names the tenant a message belongs to (`null` for none), e.g. by its recipient address. It runs before
|
|
145
|
+
* threading, so it gets the message without a conversation: a message is only joined to a conversation of
|
|
146
|
+
* the same tenant (or of a message with no tenant).
|
|
147
|
+
*/
|
|
148
|
+
readonly resolveTenant?: (email: UnthreadedEmail) => Promise<string | null>;
|
|
149
|
+
/** Days the raw copy is kept before `sweep` deletes it. Default 30. */
|
|
150
|
+
readonly rawRetentionDays?: number;
|
|
151
|
+
/** Raw messages larger than this are marked `failed` and not handled. Default 40 MiB. */
|
|
152
|
+
readonly maxRawBytes?: number;
|
|
153
|
+
/** The app's environment; `inboundFolder` is refused when this is `production`. */
|
|
154
|
+
readonly environment?: string;
|
|
155
|
+
}
|
|
156
|
+
export interface Inbound {
|
|
157
|
+
/** The public POST endpoint SNS delivers SES receipt notifications to (SES source only). */
|
|
158
|
+
webhook(config: {
|
|
159
|
+
readonly path: string;
|
|
160
|
+
}): Handler<Record<string, unknown>, unknown>;
|
|
161
|
+
/** Job handlers for the receive job; spread into the worker surface's `jobs`. */
|
|
162
|
+
readonly jobs: readonly Handler<Record<string, unknown>, unknown>[];
|
|
163
|
+
/** Folder source only: receives every `.eml` file in the folder. Needs a Flow (a job or schedule run). */
|
|
164
|
+
scan(): Promise<InboundScanResult>;
|
|
165
|
+
/** Deletes raw copies past their retention. Needs a Flow (a job or schedule run). */
|
|
166
|
+
sweep(options?: {
|
|
167
|
+
readonly limit?: number;
|
|
168
|
+
}): Promise<InboundSweepResult>;
|
|
169
|
+
/** The row of a received message, or `null`. Needs a Flow (a job, request or test context). */
|
|
170
|
+
get(id: string): Promise<InboundRecord | null>;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Receiving email. `inbound.webhook` (SES) or `inbound.scan` (folder) records each message in
|
|
174
|
+
* `pipework_email_inbound` and enqueues the `pipework.email.receive` job, once per message. The job
|
|
175
|
+
* reads the raw message, parses it, assigns a conversation, resolves the tenant, stores the attachments
|
|
176
|
+
* as that tenant's files and calls `onMessage` with a `ReceivedEmail`.
|
|
177
|
+
*
|
|
178
|
+
* Needs blueprint `email: {}` (table `pipework_email_inbound`; `pipework_email_messages` gains `conversation_id`).
|
|
179
|
+
* The row is not tenant-scoped (it exists before a tenant is known) and holds no bodies: the raw message
|
|
180
|
+
* is the copy and `sweep` deletes it after `rawRetentionDays`.
|
|
181
|
+
*
|
|
182
|
+
* Threading: the ids in In-Reply-To then References are matched to an earlier received message's
|
|
183
|
+
* Message-ID, or, for an id `<X@region.amazonses.com>`, to a sent message whose `provider_message_id` is `X`
|
|
184
|
+
* (set the sent message's conversation with `mail.send({ conversationId })` or `inReplyTo`). The first match
|
|
185
|
+
* decides the conversation; with none the message starts one (`isNewConversation: true`). Ids are matched exactly.
|
|
186
|
+
* A received message is matched only when its tenant equals the tenant `resolveTenant` named for this message or
|
|
187
|
+
* either is null; a sent message's conversation is refused when it holds a received message of another tenant.
|
|
188
|
+
*
|
|
189
|
+
* Threading is not authentication: Message-IDs are not secret and From is forgeable. Before attaching a message to
|
|
190
|
+
* a conversation's participants, the app checks `from` against them and the DKIM and DMARC verdicts.
|
|
191
|
+
*
|
|
192
|
+
* The receive job is a trace step `pipework/email:receive` with an `EmailInbound:received` audit record on success.
|
|
193
|
+
* A handler error (or a failure reading the raw message) rethrows so the queue retries; attachments stored by
|
|
194
|
+
* an earlier attempt are reused. Set `maxAttempts` on the queue. A raw message over `maxRawBytes` is marked
|
|
195
|
+
* `failed` and not retried. Message bodies are never logged.
|
|
196
|
+
*/
|
|
197
|
+
export declare function createInbound(config: InboundConfig): Inbound;
|
|
198
|
+
export {};
|
|
199
|
+
//# sourceMappingURL=inbound.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inbound.d.ts","sourceRoot":"","sources":["../../../src/infra/email/inbound.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,2BAA2B,CAAA;AACtD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,2BAA2B,CAAA;AAExD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAA;AAC3D,OAAO,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB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,CAAC,CAAA;IAC3E,uEAAuE;IACvE,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAA;IAClC,yFAAyF;IACzF,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAA;IAC7B,mFAAmF;IACnF,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAC9B;AAED,MAAM,WAAW,OAAO;IACtB,4FAA4F;IAC5F,OAAO,CAAC,MAAM,EAAE;QAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAA;IACrF,iFAAiF;IACjF,QAAQ,CAAC,IAAI,EAAE,SAAS,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,EAAE,CAAA;IACnE,0GAA0G;IAC1G,IAAI,IAAI,OAAO,CAAC,iBAAiB,CAAC,CAAA;IAClC,qFAAqF;IACrF,KAAK,CAAC,OAAO,CAAC,EAAE;QAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAA;IACzE,+FAA+F;IAC/F,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CAAA;CAC/C;AA4BD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAiS5D"}
|
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { copyFile, mkdir, readdir, readFile, stat, unlink } from 'node:fs/promises';
|
|
3
|
+
import { basename, join } from 'node:path';
|
|
4
|
+
import { Readable } from 'node:stream';
|
|
5
|
+
import { sql } from '../../data/db/sql.js';
|
|
6
|
+
import { pipeSystem } from '../../data/db/db.js';
|
|
7
|
+
import { schema } from '../../data/schema/namespace.js';
|
|
8
|
+
import { fitting } from '../../request/di/index.js';
|
|
9
|
+
import { getContext } from '../../request/context/store.js';
|
|
10
|
+
import { getBaseLogger } from '../../core/logging/index.js';
|
|
11
|
+
import { __flowStep } from '../../trace/runtime/flow-step.js';
|
|
12
|
+
import { auditEmail } from './audit.js';
|
|
13
|
+
import { parseMime } from './mime.js';
|
|
14
|
+
import { snsHandler } from './sns.js';
|
|
15
|
+
export const RECEIVE_JOB = 'pipework.email.receive';
|
|
16
|
+
const DEFAULT_RETENTION_DAYS = 30;
|
|
17
|
+
const DEFAULT_MAX_RAW_BYTES = 41_943_040;
|
|
18
|
+
const DEFAULT_SWEEP_LIMIT = 500;
|
|
19
|
+
export class RawNotFoundError extends Error {
|
|
20
|
+
constructor(detail) {
|
|
21
|
+
super(`raw message not found: ${detail}`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export class RawTooLargeError extends Error {
|
|
25
|
+
maxBytes;
|
|
26
|
+
constructor(maxBytes) {
|
|
27
|
+
super(`raw message is larger than ${maxBytes} bytes`);
|
|
28
|
+
this.maxBytes = maxBytes;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
async function collect(stream, maxBytes) {
|
|
32
|
+
const parts = [];
|
|
33
|
+
let size = 0;
|
|
34
|
+
for await (const chunk of stream) {
|
|
35
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
36
|
+
size += buf.length;
|
|
37
|
+
if (size > maxBytes) {
|
|
38
|
+
if (stream instanceof Readable)
|
|
39
|
+
stream.destroy();
|
|
40
|
+
throw new RawTooLargeError(maxBytes);
|
|
41
|
+
}
|
|
42
|
+
parts.push(buf);
|
|
43
|
+
}
|
|
44
|
+
return Buffer.concat(parts);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The SES receipt source. SES stores each raw message in S3 (receipt rule action "S3" with an SNS topic)
|
|
48
|
+
* and notifies the topic; `inbound.webhook` verifies the notification and records it, and the receive job
|
|
49
|
+
* reads the object from `bucket`. A notification whose action is not S3 (for example the SNS action,
|
|
50
|
+
* which carries the message inline), or whose type is not `Received`, is answered 200 and ignored.
|
|
51
|
+
*/
|
|
52
|
+
export function sesReceipt(config) {
|
|
53
|
+
if (config.topicArns.length === 0)
|
|
54
|
+
throw new Error('[pipework] mail.sesReceipt needs at least one topic ARN in topicArns.');
|
|
55
|
+
return {
|
|
56
|
+
kind: 'ses',
|
|
57
|
+
ses: config,
|
|
58
|
+
async read(location, maxBytes) {
|
|
59
|
+
let stream;
|
|
60
|
+
try {
|
|
61
|
+
stream = await config.bucket.read(String(location['key']));
|
|
62
|
+
}
|
|
63
|
+
catch (err) {
|
|
64
|
+
if (/\bNoSuchKey\b/.test(err instanceof Error ? err.message : String(err)))
|
|
65
|
+
throw new RawNotFoundError(String(location['key']));
|
|
66
|
+
throw err;
|
|
67
|
+
}
|
|
68
|
+
return collect(stream, maxBytes);
|
|
69
|
+
},
|
|
70
|
+
async remove(location) {
|
|
71
|
+
await config.bucket.remove(String(location['key']));
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The development source: `.eml` files dropped in `dir` are received by `inbound.scan()`, which copies each
|
|
77
|
+
* to `<dir>/received/` (where the raw copy stays until `sweep`) and removes the original. Refused when the
|
|
78
|
+
* environment is `production`.
|
|
79
|
+
*/
|
|
80
|
+
export function inboundFolder(config) {
|
|
81
|
+
return {
|
|
82
|
+
kind: 'folder',
|
|
83
|
+
folder: config,
|
|
84
|
+
async read(location, maxBytes) {
|
|
85
|
+
const path = String(location['path']);
|
|
86
|
+
try {
|
|
87
|
+
if ((await stat(path)).size > maxBytes)
|
|
88
|
+
throw new RawTooLargeError(maxBytes);
|
|
89
|
+
return await readFile(path);
|
|
90
|
+
}
|
|
91
|
+
catch (err) {
|
|
92
|
+
if (err.code === 'ENOENT')
|
|
93
|
+
throw new RawNotFoundError(path);
|
|
94
|
+
throw err;
|
|
95
|
+
}
|
|
96
|
+
},
|
|
97
|
+
async remove(location) {
|
|
98
|
+
try {
|
|
99
|
+
await unlink(String(location['path']));
|
|
100
|
+
}
|
|
101
|
+
catch (err) {
|
|
102
|
+
if (err.code !== 'ENOENT')
|
|
103
|
+
throw err;
|
|
104
|
+
}
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
function toDate(value) {
|
|
109
|
+
if (value instanceof Date)
|
|
110
|
+
return value;
|
|
111
|
+
const text = String(value);
|
|
112
|
+
return new Date(/(Z|[+-]\d\d(:?\d\d)?)$/.test(text) ? text : `${text.replace(' ', 'T')}Z`);
|
|
113
|
+
}
|
|
114
|
+
/** A Postgres text-array literal, sent as one parameter and cast with `::text[]`. */
|
|
115
|
+
function textArray(values) {
|
|
116
|
+
return `{${values.map(v => `"${v.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`).join(',')}}`;
|
|
117
|
+
}
|
|
118
|
+
function verdictsOf(receipt) {
|
|
119
|
+
const status = (key) => {
|
|
120
|
+
const v = receipt[key];
|
|
121
|
+
return typeof v?.status === 'string' ? v.status : null;
|
|
122
|
+
};
|
|
123
|
+
return {
|
|
124
|
+
spam: status('spamVerdict'), virus: status('virusVerdict'), spf: status('spfVerdict'),
|
|
125
|
+
dkim: status('dkimVerdict'), dmarc: status('dmarcVerdict'),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
function addressOf(a) {
|
|
129
|
+
return a === null ? { address: '', name: '' } : { address: a.address, name: a.name };
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Receiving email. `inbound.webhook` (SES) or `inbound.scan` (folder) records each message in
|
|
133
|
+
* `pipework_email_inbound` and enqueues the `pipework.email.receive` job, once per message. The job
|
|
134
|
+
* reads the raw message, parses it, assigns a conversation, resolves the tenant, stores the attachments
|
|
135
|
+
* as that tenant's files and calls `onMessage` with a `ReceivedEmail`.
|
|
136
|
+
*
|
|
137
|
+
* Needs blueprint `email: {}` (table `pipework_email_inbound`; `pipework_email_messages` gains `conversation_id`).
|
|
138
|
+
* The row is not tenant-scoped (it exists before a tenant is known) and holds no bodies: the raw message
|
|
139
|
+
* is the copy and `sweep` deletes it after `rawRetentionDays`.
|
|
140
|
+
*
|
|
141
|
+
* Threading: the ids in In-Reply-To then References are matched to an earlier received message's
|
|
142
|
+
* Message-ID, or, for an id `<X@region.amazonses.com>`, to a sent message whose `provider_message_id` is `X`
|
|
143
|
+
* (set the sent message's conversation with `mail.send({ conversationId })` or `inReplyTo`). The first match
|
|
144
|
+
* decides the conversation; with none the message starts one (`isNewConversation: true`). Ids are matched exactly.
|
|
145
|
+
* A received message is matched only when its tenant equals the tenant `resolveTenant` named for this message or
|
|
146
|
+
* either is null; a sent message's conversation is refused when it holds a received message of another tenant.
|
|
147
|
+
*
|
|
148
|
+
* Threading is not authentication: Message-IDs are not secret and From is forgeable. Before attaching a message to
|
|
149
|
+
* a conversation's participants, the app checks `from` against them and the DKIM and DMARC verdicts.
|
|
150
|
+
*
|
|
151
|
+
* The receive job is a trace step `pipework/email:receive` with an `EmailInbound:received` audit record on success.
|
|
152
|
+
* A handler error (or a failure reading the raw message) rethrows so the queue retries; attachments stored by
|
|
153
|
+
* an earlier attempt are reused. Set `maxAttempts` on the queue. A raw message over `maxRawBytes` is marked
|
|
154
|
+
* `failed` and not retried. Message bodies are never logged.
|
|
155
|
+
*/
|
|
156
|
+
export function createInbound(config) {
|
|
157
|
+
if (config.source.kind === 'folder' && config.environment === 'production') {
|
|
158
|
+
throw new Error('[pipework] mail.inboundFolder is refused in production.\n\n' +
|
|
159
|
+
' The stand-in reads .eml files from a folder.\n' +
|
|
160
|
+
' Configure a real source, e.g. mail.sesReceipt({ bucket, topicArns }).\n');
|
|
161
|
+
}
|
|
162
|
+
const retentionDays = Math.floor(config.rawRetentionDays ?? DEFAULT_RETENTION_DAYS);
|
|
163
|
+
const maxRawBytes = config.maxRawBytes ?? DEFAULT_MAX_RAW_BYTES;
|
|
164
|
+
if (!(retentionDays >= 0))
|
|
165
|
+
throw new Error('[pipework] inbound rawRetentionDays must be zero or more.');
|
|
166
|
+
if (!(maxRawBytes > 0))
|
|
167
|
+
throw new Error('[pipework] inbound maxRawBytes must be positive.');
|
|
168
|
+
async function record(source, sourceId, location, extra) {
|
|
169
|
+
const traceId = getContext()?.trace?.id ?? null;
|
|
170
|
+
return pipeSystem().transaction(async (tx) => {
|
|
171
|
+
const inserted = await tx.execute(sql `
|
|
172
|
+
INSERT INTO pipework_email_inbound
|
|
173
|
+
(source_id, source, raw_location, raw_expires_at, verdicts, recipients, from_address, trace_id)
|
|
174
|
+
VALUES (${sourceId}, ${source}, ${JSON.stringify(location)}::jsonb, now() + make_interval(days => ${retentionDays}::int),
|
|
175
|
+
${extra.verdicts === null ? null : JSON.stringify(extra.verdicts)}::jsonb,
|
|
176
|
+
${extra.recipients === null ? null : JSON.stringify(extra.recipients)}::jsonb, ${extra.from}, ${traceId}::uuid)
|
|
177
|
+
ON CONFLICT (source_id) DO NOTHING
|
|
178
|
+
RETURNING id`);
|
|
179
|
+
if (inserted.length === 0)
|
|
180
|
+
return null;
|
|
181
|
+
const inboundId = inserted[0]['id'];
|
|
182
|
+
await config.queue.enqueue(tx, { type: RECEIVE_JOB, payload: { inboundId }, continueFlow: true });
|
|
183
|
+
return inboundId;
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
async function ingestNotification(message) {
|
|
187
|
+
let parsed;
|
|
188
|
+
try {
|
|
189
|
+
parsed = JSON.parse(message);
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
return { ignored: true };
|
|
193
|
+
}
|
|
194
|
+
if (typeof parsed !== 'object' || parsed === null)
|
|
195
|
+
return { ignored: true };
|
|
196
|
+
const event = parsed;
|
|
197
|
+
if (event['notificationType'] !== 'Received')
|
|
198
|
+
return { ignored: true };
|
|
199
|
+
const mailPart = event['mail'];
|
|
200
|
+
const receipt = event['receipt'];
|
|
201
|
+
const action = receipt?.['action'];
|
|
202
|
+
if (typeof mailPart?.messageId !== 'string' || receipt === undefined)
|
|
203
|
+
return { ignored: true };
|
|
204
|
+
if (action?.type !== 'S3' || typeof action.bucketName !== 'string' || typeof action.objectKey !== 'string') {
|
|
205
|
+
getBaseLogger().info({ event: 'email receipt ignored', actionType: action?.type ?? null }, 'SES receipt ignored: its action is not S3');
|
|
206
|
+
return { ignored: true };
|
|
207
|
+
}
|
|
208
|
+
const recipientList = Array.isArray(receipt['recipients']) ? receipt['recipients'] : mailPart.destination;
|
|
209
|
+
const recipients = Array.isArray(recipientList) ? recipientList.filter((r) => typeof r === 'string') : [];
|
|
210
|
+
const id = await record('ses', mailPart.messageId, { bucket: action.bucketName, key: action.objectKey }, {
|
|
211
|
+
verdicts: verdictsOf(receipt), recipients, from: typeof mailPart.source === 'string' ? mailPart.source : null,
|
|
212
|
+
});
|
|
213
|
+
if (id === null)
|
|
214
|
+
getBaseLogger().info({ event: 'email receipt duplicate', sourceId: mailPart.messageId }, 'SES receipt already recorded');
|
|
215
|
+
return {};
|
|
216
|
+
}
|
|
217
|
+
async function thread(ids, recorded, tenantId) {
|
|
218
|
+
const db = pipeSystem();
|
|
219
|
+
if (ids.length > 0) {
|
|
220
|
+
const sesLocals = ids.flatMap(id => {
|
|
221
|
+
const m = /^(.+)@[^@]*amazonses\.com$/i.exec(id);
|
|
222
|
+
return m === null ? [] : [m[1]];
|
|
223
|
+
});
|
|
224
|
+
const received = await db.execute(sql `
|
|
225
|
+
SELECT message_id_header AS id, conversation_id FROM pipework_email_inbound
|
|
226
|
+
WHERE message_id_header = ANY(${textArray(ids)}::text[]) AND conversation_id IS NOT NULL
|
|
227
|
+
AND (${tenantId}::uuid IS NULL OR tenant_id IS NULL OR tenant_id = ${tenantId}::uuid)`);
|
|
228
|
+
const sent = sesLocals.length === 0 ? [] : await db.execute(sql `
|
|
229
|
+
SELECT provider_message_id AS id, conversation_id FROM pipework_email_messages
|
|
230
|
+
WHERE provider_message_id = ANY(${textArray(sesLocals)}::text[]) AND conversation_id IS NOT NULL`);
|
|
231
|
+
const byId = new Map();
|
|
232
|
+
for (const r of received)
|
|
233
|
+
byId.set(r['id'], r['conversation_id']);
|
|
234
|
+
const bySes = new Map();
|
|
235
|
+
for (const r of sent) {
|
|
236
|
+
const conversation = r['conversation_id'];
|
|
237
|
+
const foreign = tenantId === null ? [] : await db.execute(sql `
|
|
238
|
+
SELECT 1 FROM pipework_email_inbound
|
|
239
|
+
WHERE conversation_id = ${conversation}::uuid AND tenant_id IS NOT NULL AND tenant_id <> ${tenantId}::uuid LIMIT 1`);
|
|
240
|
+
if (foreign.length === 0)
|
|
241
|
+
bySes.set(r['id'], conversation);
|
|
242
|
+
}
|
|
243
|
+
for (const id of ids) {
|
|
244
|
+
const hit = byId.get(id) ?? bySes.get(/^(.+)@[^@]*amazonses\.com$/i.exec(id)?.[1] ?? '\u0000');
|
|
245
|
+
if (hit !== undefined)
|
|
246
|
+
return { conversationId: hit, isNew: false };
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
// No match: this message's own conversation, kept from an earlier attempt of the job.
|
|
250
|
+
if (recorded !== null)
|
|
251
|
+
return { conversationId: recorded, isNew: true };
|
|
252
|
+
return { conversationId: randomUUID(), isNew: true };
|
|
253
|
+
}
|
|
254
|
+
async function fail(id, error) {
|
|
255
|
+
await pipeSystem().execute(sql `UPDATE pipework_email_inbound SET status = 'failed', error = ${error} WHERE id = ${id}::uuid`);
|
|
256
|
+
await auditEmail('failed', id, { error }, 'EmailInbound');
|
|
257
|
+
getBaseLogger().error({ event: 'email receive failed', inboundId: id }, `received email not handled: ${error}`);
|
|
258
|
+
return { status: 'failed' };
|
|
259
|
+
}
|
|
260
|
+
const receive = __flowStep({ ref: 'pipework/email:receive' }, async (inboundId) => {
|
|
261
|
+
const db = pipeSystem();
|
|
262
|
+
const row = (await db.execute(sql `SELECT * FROM pipework_email_inbound WHERE id = ${inboundId}::uuid`))[0];
|
|
263
|
+
if (row === undefined)
|
|
264
|
+
throw new Error(`[pipework] Received email ${inboundId} does not exist.`);
|
|
265
|
+
const status = row['status'];
|
|
266
|
+
if (status === 'processed' || status === 'failed')
|
|
267
|
+
return { status };
|
|
268
|
+
if (config.source.kind === 'folder' && getContext()?.instance.config.environment === 'production') {
|
|
269
|
+
throw new Error('[pipework] mail.inboundFolder is refused in production.');
|
|
270
|
+
}
|
|
271
|
+
if (row['raw_deleted_at'] !== null)
|
|
272
|
+
return fail(inboundId, 'the raw message was deleted before it was handled');
|
|
273
|
+
let raw;
|
|
274
|
+
try {
|
|
275
|
+
raw = await config.source.read(row['raw_location'], maxRawBytes);
|
|
276
|
+
}
|
|
277
|
+
catch (err) {
|
|
278
|
+
if (err instanceof RawTooLargeError || err instanceof RawNotFoundError)
|
|
279
|
+
return fail(inboundId, err.message);
|
|
280
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
281
|
+
await db.execute(sql `UPDATE pipework_email_inbound SET error = ${message} WHERE id = ${inboundId}::uuid`);
|
|
282
|
+
throw err;
|
|
283
|
+
}
|
|
284
|
+
const parsed = parseMime(raw);
|
|
285
|
+
const recipients = row['recipients'] ?? [...parsed.to, ...parsed.cc].map(a => a.address);
|
|
286
|
+
const verdicts = row['verdicts'] ?? null;
|
|
287
|
+
const unthreaded = {
|
|
288
|
+
id: inboundId,
|
|
289
|
+
messageId: parsed.messageId, inReplyTo: parsed.inReplyTo, references: parsed.references,
|
|
290
|
+
from: addressOf(parsed.from),
|
|
291
|
+
to: parsed.to.map(addressOf), cc: parsed.cc.map(addressOf), replyTo: parsed.replyTo.map(addressOf),
|
|
292
|
+
subject: parsed.subject, date: parsed.date, text: parsed.text, html: parsed.html,
|
|
293
|
+
attachments: parsed.attachments.map(a => ({
|
|
294
|
+
filename: a.filename, mediaType: a.mediaType, size: a.size, sha256: createHash('sha256').update(a.content).digest('hex'),
|
|
295
|
+
contentId: a.contentId, inline: a.inline, file: null,
|
|
296
|
+
})),
|
|
297
|
+
verdicts, recipients,
|
|
298
|
+
};
|
|
299
|
+
let tenantId = row['tenant_id'] ?? null;
|
|
300
|
+
if (tenantId === null && config.resolveTenant !== undefined)
|
|
301
|
+
tenantId = await config.resolveTenant(unthreaded);
|
|
302
|
+
const { conversationId, isNew } = await thread(parsed.threadIds, row['conversation_id'] ?? null, tenantId);
|
|
303
|
+
const base = { ...unthreaded, conversationId, isNewConversation: isNew, tenantId };
|
|
304
|
+
await db.execute(sql `
|
|
305
|
+
UPDATE pipework_email_inbound SET
|
|
306
|
+
message_id_header = ${parsed.messageId}, in_reply_to = ${parsed.inReplyTo}, "references" = ${JSON.stringify(parsed.references)}::jsonb,
|
|
307
|
+
from_address = ${base.from.address}, subject = ${parsed.subject}, conversation_id = ${conversationId}::uuid,
|
|
308
|
+
tenant_id = ${tenantId}::uuid, recipients = ${JSON.stringify(recipients)}::jsonb, error = NULL
|
|
309
|
+
WHERE id = ${inboundId}::uuid`);
|
|
310
|
+
let attachments = base.attachments;
|
|
311
|
+
if (config.storage !== undefined && tenantId !== null && parsed.attachments.length > 0) {
|
|
312
|
+
const storage = config.storage;
|
|
313
|
+
const stored = Array.isArray(row['attachment_files']) ? [...row['attachment_files']] : [];
|
|
314
|
+
const files = [];
|
|
315
|
+
for (let i = 0; i < parsed.attachments.length; i++) {
|
|
316
|
+
const part = parsed.attachments[i];
|
|
317
|
+
let file = null;
|
|
318
|
+
const earlier = stored[i];
|
|
319
|
+
if (typeof earlier === 'string')
|
|
320
|
+
file = await storage.getFor(tenantId, earlier);
|
|
321
|
+
if (file === null) {
|
|
322
|
+
file = await storage.putFor(tenantId, {
|
|
323
|
+
body: Readable.from([part.content]), mediaType: part.mediaType,
|
|
324
|
+
...(part.filename !== null ? { filename: part.filename } : {}),
|
|
325
|
+
expectedSha256: attachments[i].sha256,
|
|
326
|
+
});
|
|
327
|
+
stored[i] = file.id;
|
|
328
|
+
await db.execute(sql `UPDATE pipework_email_inbound SET attachment_files = ${JSON.stringify(stored)}::jsonb WHERE id = ${inboundId}::uuid`);
|
|
329
|
+
}
|
|
330
|
+
files.push(file);
|
|
331
|
+
}
|
|
332
|
+
attachments = attachments.map((a, i) => ({ ...a, file: files[i] ?? null }));
|
|
333
|
+
}
|
|
334
|
+
try {
|
|
335
|
+
await config.onMessage({ ...base, tenantId, attachments });
|
|
336
|
+
}
|
|
337
|
+
catch (err) {
|
|
338
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
339
|
+
await db.execute(sql `UPDATE pipework_email_inbound SET error = ${message} WHERE id = ${inboundId}::uuid`);
|
|
340
|
+
throw err;
|
|
341
|
+
}
|
|
342
|
+
const traceId = getContext()?.trace?.id ?? null;
|
|
343
|
+
await db.execute(sql `
|
|
344
|
+
UPDATE pipework_email_inbound SET status = 'processed', processed_at = now(), error = NULL, trace_id = COALESCE(${traceId}::uuid, trace_id)
|
|
345
|
+
WHERE id = ${inboundId}::uuid`);
|
|
346
|
+
await auditEmail('received', inboundId, {
|
|
347
|
+
conversationId, isNewConversation: isNew, tenantId, attachments: attachments.length,
|
|
348
|
+
}, 'EmailInbound');
|
|
349
|
+
return { status: 'processed' };
|
|
350
|
+
});
|
|
351
|
+
const receiveJob = fitting.use().job(RECEIVE_JOB)
|
|
352
|
+
.input(schema.check.object({ inboundId: schema.check.string() }))
|
|
353
|
+
.fit(async ({ input }) => receive(input.inboundId));
|
|
354
|
+
return {
|
|
355
|
+
webhook(webhook) {
|
|
356
|
+
const ses = config.source.ses;
|
|
357
|
+
if (config.source.kind !== 'ses' || ses === undefined) {
|
|
358
|
+
throw new Error('[pipework] inbound.webhook needs a mail.sesReceipt source; this inbound reads a folder.');
|
|
359
|
+
}
|
|
360
|
+
return snsHandler({
|
|
361
|
+
path: webhook.path, topicArns: ses.topicArns,
|
|
362
|
+
...(ses.region !== undefined ? { region: ses.region } : {}),
|
|
363
|
+
...(ses.fetchCert !== undefined ? { fetchCert: ses.fetchCert } : {}),
|
|
364
|
+
...(ses.confirm !== undefined ? { confirm: ses.confirm } : {}),
|
|
365
|
+
}, ingestNotification);
|
|
366
|
+
},
|
|
367
|
+
jobs: [receiveJob],
|
|
368
|
+
async scan() {
|
|
369
|
+
const folder = config.source.folder;
|
|
370
|
+
if (config.source.kind !== 'folder' || folder === undefined) {
|
|
371
|
+
throw new Error('[pipework] inbound.scan needs a mail.inboundFolder source; this inbound receives through SES.');
|
|
372
|
+
}
|
|
373
|
+
let names;
|
|
374
|
+
try {
|
|
375
|
+
names = (await readdir(folder.dir)).filter(n => n.toLowerCase().endsWith('.eml')).sort();
|
|
376
|
+
}
|
|
377
|
+
catch (err) {
|
|
378
|
+
if (err.code === 'ENOENT')
|
|
379
|
+
return { received: 0, duplicates: 0 };
|
|
380
|
+
throw err;
|
|
381
|
+
}
|
|
382
|
+
const done = join(folder.dir, 'received');
|
|
383
|
+
let received = 0;
|
|
384
|
+
let duplicates = 0;
|
|
385
|
+
for (const name of names) {
|
|
386
|
+
const from = join(folder.dir, name);
|
|
387
|
+
if (!(await stat(from)).isFile())
|
|
388
|
+
continue;
|
|
389
|
+
const bytes = await readFile(from);
|
|
390
|
+
const sha = createHash('sha256').update(bytes).digest('hex');
|
|
391
|
+
await mkdir(done, { recursive: true });
|
|
392
|
+
const to = join(done, `${sha.slice(0, 12)}-${basename(name)}`);
|
|
393
|
+
await copyFile(from, to);
|
|
394
|
+
const id = await record('folder', `folder:${sha}`, { path: to }, { verdicts: null, recipients: null, from: null });
|
|
395
|
+
await unlink(from);
|
|
396
|
+
if (id === null)
|
|
397
|
+
duplicates++;
|
|
398
|
+
else
|
|
399
|
+
received++;
|
|
400
|
+
}
|
|
401
|
+
return { received, duplicates };
|
|
402
|
+
},
|
|
403
|
+
async sweep(options) {
|
|
404
|
+
const limit = options?.limit ?? DEFAULT_SWEEP_LIMIT;
|
|
405
|
+
const db = pipeSystem();
|
|
406
|
+
const due = await db.execute(sql `
|
|
407
|
+
SELECT id, raw_location FROM pipework_email_inbound
|
|
408
|
+
WHERE raw_expires_at <= now() AND raw_deleted_at IS NULL
|
|
409
|
+
ORDER BY raw_expires_at LIMIT ${limit}`);
|
|
410
|
+
let deleted = 0;
|
|
411
|
+
let failed = 0;
|
|
412
|
+
for (const row of due) {
|
|
413
|
+
try {
|
|
414
|
+
await config.source.remove(row['raw_location']);
|
|
415
|
+
await db.execute(sql `UPDATE pipework_email_inbound SET raw_deleted_at = now() WHERE id = ${row['id']}::uuid`);
|
|
416
|
+
deleted++;
|
|
417
|
+
}
|
|
418
|
+
catch (err) {
|
|
419
|
+
failed++;
|
|
420
|
+
getBaseLogger().error({ err, inboundId: row['id'] }, 'inbound sweep could not delete a raw message');
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
return { deleted, failed };
|
|
424
|
+
},
|
|
425
|
+
async get(id) {
|
|
426
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id))
|
|
427
|
+
return null;
|
|
428
|
+
const row = (await pipeSystem().execute(sql `SELECT * FROM pipework_email_inbound WHERE id = ${id}::uuid`))[0];
|
|
429
|
+
if (row === undefined)
|
|
430
|
+
return null;
|
|
431
|
+
const date = (v) => (v === null || v === undefined ? null : toDate(v));
|
|
432
|
+
return {
|
|
433
|
+
id: row['id'],
|
|
434
|
+
source: row['source'],
|
|
435
|
+
status: row['status'],
|
|
436
|
+
error: row['error'] ?? null,
|
|
437
|
+
messageId: row['message_id_header'] ?? null,
|
|
438
|
+
conversationId: row['conversation_id'] ?? null,
|
|
439
|
+
tenantId: row['tenant_id'] ?? null,
|
|
440
|
+
subject: row['subject'] ?? null,
|
|
441
|
+
fromAddress: row['from_address'] ?? null,
|
|
442
|
+
verdicts: row['verdicts'] ?? null,
|
|
443
|
+
receivedAt: toDate(row['received_at']),
|
|
444
|
+
processedAt: date(row['processed_at']),
|
|
445
|
+
rawExpiresAt: toDate(row['raw_expires_at']),
|
|
446
|
+
rawDeletedAt: date(row['raw_deleted_at']),
|
|
447
|
+
};
|
|
448
|
+
},
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
//# sourceMappingURL=inbound.js.map
|