@pithy-sh/support 0.1.1 → 0.1.3
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/dist/ai/classify.d.ts +90 -0
- package/dist/ai/classify.d.ts.map +1 -0
- package/dist/ai/classify.js +151 -0
- package/dist/attachment/store.d.ts +53 -0
- package/dist/attachment/store.d.ts.map +1 -0
- package/dist/attachment/store.js +67 -0
- package/dist/audit/actions.d.ts +68 -0
- package/dist/audit/actions.d.ts.map +1 -0
- package/dist/audit/actions.js +68 -0
- package/dist/capability.d.ts +93 -0
- package/dist/capability.d.ts.map +1 -0
- package/dist/capability.js +187 -0
- package/dist/client/projection.d.ts +56 -0
- package/dist/client/projection.d.ts.map +1 -0
- package/dist/client/projection.js +0 -0
- package/dist/config/config.d.ts +215 -0
- package/dist/config/config.d.ts.map +1 -0
- package/dist/config/config.js +169 -0
- package/dist/data/attachment.d.ts +30 -0
- package/dist/data/attachment.d.ts.map +1 -0
- package/dist/data/attachment.js +32 -0
- package/dist/data/billingScope.d.ts +30 -0
- package/dist/data/billingScope.d.ts.map +1 -0
- package/dist/data/billingScope.js +32 -0
- package/dist/data/categories.d.ts +54 -0
- package/dist/data/categories.d.ts.map +1 -0
- package/dist/data/categories.js +97 -0
- package/dist/data/classification.d.ts +34 -0
- package/dist/data/classification.d.ts.map +1 -0
- package/dist/data/classification.js +28 -0
- package/dist/data/enums.d.ts +82 -0
- package/dist/data/enums.d.ts.map +1 -0
- package/dist/data/enums.js +70 -0
- package/dist/data/flag.d.ts +25 -0
- package/dist/data/flag.d.ts.map +1 -0
- package/dist/data/flag.js +27 -0
- package/dist/data/message.d.ts +81 -0
- package/dist/data/message.d.ts.map +1 -0
- package/dist/data/message.js +84 -0
- package/dist/data/tables.d.ts +160 -0
- package/dist/data/tables.d.ts.map +1 -0
- package/dist/data/tables.js +44 -0
- package/dist/data/thread.d.ts +77 -0
- package/dist/data/thread.d.ts.map +1 -0
- package/dist/data/thread.js +65 -0
- package/dist/error/errors.d.ts +64 -0
- package/dist/error/errors.d.ts.map +1 -0
- package/dist/error/errors.js +82 -0
- package/dist/http/guards.d.ts +44 -0
- package/dist/http/guards.d.ts.map +1 -0
- package/dist/http/guards.js +53 -0
- package/dist/http/handlers.d.ts +89 -0
- package/dist/http/handlers.d.ts.map +1 -0
- package/dist/http/handlers.js +248 -0
- package/dist/http/resolve.d.ts +44 -0
- package/dist/http/resolve.d.ts.map +1 -0
- package/dist/http/resolve.js +72 -0
- package/dist/http/responses.d.ts +829 -0
- package/dist/http/responses.d.ts.map +1 -0
- package/dist/http/responses.js +303 -0
- package/dist/http/routes.d.ts +109 -0
- package/dist/http/routes.d.ts.map +1 -0
- package/dist/http/routes.js +62 -0
- package/dist/http/schemas.d.ts +121 -0
- package/dist/http/schemas.d.ts.map +1 -0
- package/dist/http/schemas.js +89 -0
- package/dist/http/scopes.d.ts +56 -0
- package/dist/http/scopes.d.ts.map +1 -0
- package/dist/http/scopes.js +107 -0
- package/dist/http/views.d.ts +36 -0
- package/dist/http/views.d.ts.map +1 -0
- package/dist/http/views.js +144 -0
- package/dist/inbound/authenticity.d.ts +81 -0
- package/dist/inbound/authenticity.d.ts.map +1 -0
- package/dist/inbound/authenticity.js +61 -0
- package/dist/inbound/guard.d.ts +74 -0
- package/dist/inbound/guard.d.ts.map +1 -0
- package/dist/inbound/guard.js +78 -0
- package/dist/inbound/handler.d.ts +28 -0
- package/dist/inbound/handler.d.ts.map +1 -0
- package/dist/inbound/handler.js +82 -0
- package/dist/inbound/ingest.d.ts +104 -0
- package/dist/inbound/ingest.d.ts.map +1 -0
- package/dist/inbound/ingest.js +326 -0
- package/dist/inbound/recipient.d.ts +16 -0
- package/dist/inbound/recipient.d.ts.map +1 -0
- package/dist/inbound/recipient.js +46 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +14 -0
- package/dist/link/sender.d.ts +160 -0
- package/dist/link/sender.d.ts.map +1 -0
- package/dist/link/sender.js +200 -0
- package/dist/migrations/0001_threads.d.ts +26 -0
- package/dist/migrations/0001_threads.d.ts.map +1 -0
- package/dist/migrations/0001_threads.js +103 -0
- package/dist/mime/address.d.ts +22 -0
- package/dist/mime/address.d.ts.map +1 -0
- package/dist/mime/address.js +28 -0
- package/dist/mime/parse.d.ts +96 -0
- package/dist/mime/parse.d.ts.map +1 -0
- package/dist/mime/parse.js +146 -0
- package/dist/mime/sanitize.d.ts +25 -0
- package/dist/mime/sanitize.d.ts.map +1 -0
- package/dist/mime/sanitize.js +212 -0
- package/dist/mime/threading.d.ts +79 -0
- package/dist/mime/threading.d.ts.map +1 -0
- package/dist/mime/threading.js +111 -0
- package/dist/mime/truncate.d.ts +17 -0
- package/dist/mime/truncate.d.ts.map +1 -0
- package/dist/mime/truncate.js +47 -0
- package/dist/provision/provisionSupport.d.ts +158 -0
- package/dist/provision/provisionSupport.d.ts.map +1 -0
- package/dist/provision/provisionSupport.js +110 -0
- package/dist/provision/resolveSupportConfig.d.ts +45 -0
- package/dist/provision/resolveSupportConfig.d.ts.map +1 -0
- package/dist/provision/resolveSupportConfig.js +22 -0
- package/dist/reply/send.d.ts +123 -0
- package/dist/reply/send.d.ts.map +1 -0
- package/dist/reply/send.js +153 -0
- package/dist/reply/snippets.d.ts +79 -0
- package/dist/reply/snippets.d.ts.map +1 -0
- package/dist/reply/snippets.js +135 -0
- package/dist/secret/registry.d.ts +18 -0
- package/dist/secret/registry.d.ts.map +1 -0
- package/dist/secret/registry.js +21 -0
- package/dist/seeds/example.d.ts +3 -0
- package/dist/seeds/example.d.ts.map +1 -0
- package/dist/seeds/example.js +350 -0
- package/dist/store/paging.d.ts +18 -0
- package/dist/store/paging.d.ts.map +1 -0
- package/dist/store/paging.js +20 -0
- package/dist/store/search.d.ts +67 -0
- package/dist/store/search.d.ts.map +1 -0
- package/dist/store/search.js +160 -0
- package/dist/store/searchIndex.d.ts +53 -0
- package/dist/store/searchIndex.d.ts.map +1 -0
- package/dist/store/searchIndex.js +66 -0
- package/dist/store/threads.d.ts +147 -0
- package/dist/store/threads.d.ts.map +1 -0
- package/dist/store/threads.js +197 -0
- package/dist/submission/encoding.d.ts +21 -0
- package/dist/submission/encoding.d.ts.map +1 -0
- package/dist/submission/encoding.js +55 -0
- package/dist/submission/guard.d.ts +71 -0
- package/dist/submission/guard.d.ts.map +1 -0
- package/dist/submission/guard.js +46 -0
- package/dist/submission/submit.d.ts +152 -0
- package/dist/submission/submit.d.ts.map +1 -0
- package/dist/submission/submit.js +319 -0
- package/dist/version.generated.d.ts +5 -0
- package/dist/version.generated.d.ts.map +1 -0
- package/dist/version.generated.js +7 -0
- package/dist/workflows/classify.d.ts +63 -0
- package/dist/workflows/classify.d.ts.map +1 -0
- package/dist/workflows/classify.js +68 -0
- package/dist/workflows/retryPolicy.d.ts +39 -0
- package/dist/workflows/retryPolicy.d.ts.map +1 -0
- package/dist/workflows/retryPolicy.js +43 -0
- package/dist/workflows/specs.d.ts +43 -0
- package/dist/workflows/specs.d.ts.map +1 -0
- package/dist/workflows/specs.js +46 -0
- package/dist/workflows/worker.d.ts +48 -0
- package/dist/workflows/worker.d.ts.map +1 -0
- package/dist/workflows/worker.js +37 -0
- package/package.json +24 -15
- package/src/version.generated.ts +1 -1
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
2
|
+
//#region src/submission/encoding.ts
|
|
3
|
+
/**
|
|
4
|
+
* Turning a base64 attachment back into bytes.
|
|
5
|
+
*
|
|
6
|
+
* Base64 rather than `multipart/form-data` for the submission route, and the reason is the contract
|
|
7
|
+
* rather than the encoding: every other route in this capability declares what it accepts as a Zod
|
|
8
|
+
* object over JSON, validated on the route line, and a multipart body is the one shape that cannot be.
|
|
9
|
+
* The cost is a third more bytes on the wire, which is why `attachments.maxBytes` is documented as a
|
|
10
|
+
* bound on the **decoded** size — the number that reaches R2 and the adopter's bill.
|
|
11
|
+
*/
|
|
12
|
+
/** How much larger a base64 string is than the bytes it encodes: four characters per three bytes. */
|
|
13
|
+
const BASE64_EXPANSION = 4 / 3;
|
|
14
|
+
/**
|
|
15
|
+
* The largest base64 string worth decoding, derived from a decoded-byte bound.
|
|
16
|
+
*
|
|
17
|
+
* Checked **before** decoding, not after. `atob` materialises the whole result, so a client that sends
|
|
18
|
+
* fifty megabytes of base64 has already been allocated fifty megabytes of Worker memory by the time a
|
|
19
|
+
* post-hoc size check could refuse it — and the request that does that is the one an attacker sends.
|
|
20
|
+
* A little slack for padding and any whitespace a client's encoder inserted.
|
|
21
|
+
*/
|
|
22
|
+
function maxEncodedLength(maxBytes) {
|
|
23
|
+
return Math.ceil(maxBytes * BASE64_EXPANSION) + 4;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Decode one base64 attachment payload.
|
|
27
|
+
*
|
|
28
|
+
* Accepts the URL-safe alphabet too: a client that reached for `base64url` because its platform's
|
|
29
|
+
* default encoder produces it has not made a mistake worth a 400, and the two differ by two
|
|
30
|
+
* characters. Anything that is not base64 at all is a `validation/invalid_input`, which is what the
|
|
31
|
+
* route's own validator would have raised had the string been checkable there.
|
|
32
|
+
*/
|
|
33
|
+
function decodeBase64(value, options) {
|
|
34
|
+
if (value.length > maxEncodedLength(options.maxBytes)) throw new ValidationError({
|
|
35
|
+
message: "That attachment is too large.",
|
|
36
|
+
action: `Attach a file under ${options.maxBytes} bytes.`,
|
|
37
|
+
detail: `encoded attachment is ${value.length} characters, over the ${maxEncodedLength(options.maxBytes)} the ${options.maxBytes} byte bound allows`
|
|
38
|
+
});
|
|
39
|
+
const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
|
|
40
|
+
let binary;
|
|
41
|
+
try {
|
|
42
|
+
binary = atob(normalized);
|
|
43
|
+
} catch (cause) {
|
|
44
|
+
throw new ValidationError({
|
|
45
|
+
message: "That attachment could not be read.",
|
|
46
|
+
action: "Send the file's bytes as a base64 string.",
|
|
47
|
+
detail: "attachment payload is not valid base64"
|
|
48
|
+
}, { cause });
|
|
49
|
+
}
|
|
50
|
+
const bytes = new Uint8Array(binary.length);
|
|
51
|
+
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
|
|
52
|
+
return bytes;
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
export { decodeBase64, maxEncodedLength };
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { SupportSubmissionConfig } from "../config/config";
|
|
2
|
+
import { type SupportDatabase } from "../data/tables";
|
|
3
|
+
/**
|
|
4
|
+
* The in-app submission guard — the bound between "a signed-in user may write in" and "one account is
|
|
5
|
+
* the whole inbox".
|
|
6
|
+
*
|
|
7
|
+
* ## Why this is not the mail guard with a different column
|
|
8
|
+
*
|
|
9
|
+
* `inbound/guard.ts` exists because a public address is a public write endpoint reachable by anybody
|
|
10
|
+
* with an SMTP client, and its bounds are the shape of that problem: a size cap before parsing, a
|
|
11
|
+
* per-address rate for the broken auto-responder, a global rate for the distributed flood where no
|
|
12
|
+
* single address stands out.
|
|
13
|
+
*
|
|
14
|
+
* None of that describes this surface. **A submission is attributable and revocable**: it carries an
|
|
15
|
+
* account the adopter issued, so the flood the mail guard's global bound exists for cannot happen
|
|
16
|
+
* anonymously here — an attacker needs an account per bucket of ten, and every one of them is a row an
|
|
17
|
+
* adopter can disable. What remains is one real failure, and it is the one this file bounds: a single
|
|
18
|
+
* account, hostile or looping, filling the inbox.
|
|
19
|
+
*
|
|
20
|
+
* So there is one check rather than three, and it counts on the **account** rather than the address.
|
|
21
|
+
* Not the same thing: an address is a claim in a header and an account is an identity a session
|
|
22
|
+
* proved, which is the whole distinction this channel exists to exploit.
|
|
23
|
+
*
|
|
24
|
+
* ## Counted from the messages table, and only against its own channel
|
|
25
|
+
*
|
|
26
|
+
* The same reasoning `inbound/guard.ts` states — the rows already exist, a counter row would be a
|
|
27
|
+
* second write that overcounts a failed store and undercounts a flood — over the same sliding hour,
|
|
28
|
+
* and over an index (`submitted_by_user_id`, `received_at`) that the migration creates for this.
|
|
29
|
+
*
|
|
30
|
+
* **`channel = "app"` is on the count deliberately.** Neither surface may starve the other: a customer
|
|
31
|
+
* who emailed twenty times about a billing dispute must still be able to file a bug from inside the
|
|
32
|
+
* app, and somebody filing bug reports must never consume the mail inbox's capacity. Sharing one
|
|
33
|
+
* counter would couple two threat models that have nothing in common.
|
|
34
|
+
*/
|
|
35
|
+
/** Why a submission was refused. The value lands in the audit event's `metadata.reason`. */
|
|
36
|
+
export type SupportSubmissionRejectionReason = "account_rate" | "attachment_too_large" | "attachment_type";
|
|
37
|
+
/** The guard's answer: accept, or refuse with a reason. */
|
|
38
|
+
export type SubmissionVerdict = {
|
|
39
|
+
accepted: true;
|
|
40
|
+
} | {
|
|
41
|
+
accepted: false;
|
|
42
|
+
reason: SupportSubmissionRejectionReason;
|
|
43
|
+
detail: string;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Check how much this account has already filed inside the window.
|
|
47
|
+
*
|
|
48
|
+
* `>=` rather than `>`, matching the mail guard: the bound is how many an account *may land*, so the
|
|
49
|
+
* request that would be the eleventh is refused when ten are already stored.
|
|
50
|
+
*/
|
|
51
|
+
export declare function checkAccountRate(db: SupportDatabase, config: SupportSubmissionConfig, input: {
|
|
52
|
+
userId: string;
|
|
53
|
+
now: Date;
|
|
54
|
+
}): Promise<SubmissionVerdict>;
|
|
55
|
+
/**
|
|
56
|
+
* Check one attachment against the declared bounds.
|
|
57
|
+
*
|
|
58
|
+
* Size is measured on the **decoded** bytes, which is the number that matters and not the one the
|
|
59
|
+
* request carried: a base64 payload is a third larger than what lands in R2, and bounding the encoded
|
|
60
|
+
* form would silently make the effective limit whatever `maxBytes * 0.75` happens to be.
|
|
61
|
+
*
|
|
62
|
+
* The type check is an **allowlist**, so a type nobody thought about is refused rather than accepted —
|
|
63
|
+
* the opposite default from the mail path, where refusing an unexpected type would lose a customer's
|
|
64
|
+
* bug report. It bounds what lands in the adopter's bucket; it is not what stops a stored-XSS, which
|
|
65
|
+
* is `putAttachment` writing every object as `application/octet-stream` whatever was declared.
|
|
66
|
+
*/
|
|
67
|
+
export declare function checkAttachment(config: SupportSubmissionConfig, input: {
|
|
68
|
+
contentType: string;
|
|
69
|
+
bytes: number;
|
|
70
|
+
}): SubmissionVerdict;
|
|
71
|
+
//# sourceMappingURL=guard.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guard.d.ts","sourceRoot":"","sources":["../../src/submission/guard.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EAA0B,KAAK,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAG9E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,4FAA4F;AAC5F,MAAM,MAAM,gCAAgC,GAAG,cAAc,GAAG,sBAAsB,GAAG,iBAAiB,CAAC;AAE3G,2DAA2D;AAC3D,MAAM,MAAM,iBAAiB,GACzB;IAAE,QAAQ,EAAE,IAAI,CAAA;CAAE,GAClB;IAAE,QAAQ,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,gCAAgC,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAElF;;;;;GAKG;AACH,wBAAsB,gBAAgB,CACpC,EAAE,EAAE,eAAe,EACnB,MAAM,EAAE,uBAAuB,EAC/B,KAAK,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,IAAI,CAAA;CAAE,GACnC,OAAO,CAAC,iBAAiB,CAAC,CAyB5B;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,uBAAuB,EAC/B,KAAK,EAAE;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC5C,iBAAiB,CAmBnB"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { SUPPORT_MESSAGES_TABLE } from "../data/tables.js";
|
|
2
|
+
import { GUARD_WINDOW_MS } from "../inbound/guard.js";
|
|
3
|
+
//#region src/submission/guard.ts
|
|
4
|
+
/**
|
|
5
|
+
* Check how much this account has already filed inside the window.
|
|
6
|
+
*
|
|
7
|
+
* `>=` rather than `>`, matching the mail guard: the bound is how many an account *may land*, so the
|
|
8
|
+
* request that would be the eleventh is refused when ten are already stored.
|
|
9
|
+
*/
|
|
10
|
+
async function checkAccountRate(db, config, input) {
|
|
11
|
+
const since = new Date(input.now.getTime() - GUARD_WINDOW_MS);
|
|
12
|
+
const filed = await db.selectFrom(SUPPORT_MESSAGES_TABLE).select((eb) => eb.fn.countAll().as("count")).where("channel", "=", "app").where("direction", "=", "inbound").where("submittedByUserId", "=", input.userId).where("receivedAt", ">=", since.getTime()).executeTakeFirst();
|
|
13
|
+
if ((filed?.count ?? 0) >= config.maxPerAccountPerHour) return {
|
|
14
|
+
accepted: false,
|
|
15
|
+
reason: "account_rate",
|
|
16
|
+
detail: `account ${input.userId} has filed ${filed?.count} submissions in the last hour, at or over the ${config.maxPerAccountPerHour} bound`
|
|
17
|
+
};
|
|
18
|
+
return { accepted: true };
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Check one attachment against the declared bounds.
|
|
22
|
+
*
|
|
23
|
+
* Size is measured on the **decoded** bytes, which is the number that matters and not the one the
|
|
24
|
+
* request carried: a base64 payload is a third larger than what lands in R2, and bounding the encoded
|
|
25
|
+
* form would silently make the effective limit whatever `maxBytes * 0.75` happens to be.
|
|
26
|
+
*
|
|
27
|
+
* The type check is an **allowlist**, so a type nobody thought about is refused rather than accepted —
|
|
28
|
+
* the opposite default from the mail path, where refusing an unexpected type would lose a customer's
|
|
29
|
+
* bug report. It bounds what lands in the adopter's bucket; it is not what stops a stored-XSS, which
|
|
30
|
+
* is `putAttachment` writing every object as `application/octet-stream` whatever was declared.
|
|
31
|
+
*/
|
|
32
|
+
function checkAttachment(config, input) {
|
|
33
|
+
if (input.bytes > config.attachments.maxBytes) return {
|
|
34
|
+
accepted: false,
|
|
35
|
+
reason: "attachment_too_large",
|
|
36
|
+
detail: `attachment is ${input.bytes} decoded bytes, over the ${config.attachments.maxBytes} byte bound`
|
|
37
|
+
};
|
|
38
|
+
if (!config.attachments.allowedContentTypes.includes(input.contentType)) return {
|
|
39
|
+
accepted: false,
|
|
40
|
+
reason: "attachment_type",
|
|
41
|
+
detail: `attachment declares ${input.contentType}, which is not in the configured allowlist`
|
|
42
|
+
};
|
|
43
|
+
return { accepted: true };
|
|
44
|
+
}
|
|
45
|
+
//#endregion
|
|
46
|
+
export { checkAccountRate, checkAttachment };
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import type { R2Bucket } from "@cloudflare/workers-types";
|
|
2
|
+
import type { AuditEmit } from "@pithy-sh/core/src/audit/recorder";
|
|
3
|
+
import type { Logger } from "@pithy-sh/core/src/logger/logger";
|
|
4
|
+
import type { SupportConfig } from "../config/config";
|
|
5
|
+
import { type SupportCategories } from "../data/categories";
|
|
6
|
+
import { type SupportSubmissionContext } from "../data/message";
|
|
7
|
+
import { type SupportDatabase } from "../data/tables";
|
|
8
|
+
/**
|
|
9
|
+
* The in-app submission path — a signed-in user opening a support thread from inside the app, without
|
|
10
|
+
* leaving it for their mail client.
|
|
11
|
+
*
|
|
12
|
+
* This is `inbound/ingest.ts` for the other channel, and it is deliberately the *same* destination:
|
|
13
|
+
* one threads table, one messages table, one classifier, one taxonomy, one console. A second package
|
|
14
|
+
* would have been a second inbox and a support person with two of them, neither holding the whole
|
|
15
|
+
* conversation — and the reply to an in-app report goes out by email regardless, because that is where
|
|
16
|
+
* the person will read it.
|
|
17
|
+
*
|
|
18
|
+
* ## What this path does not have to do
|
|
19
|
+
*
|
|
20
|
+
* `inbound/authenticity.ts` is two hundred lines earning the right to say a thread belongs to a
|
|
21
|
+
* customer, because a `From:` header is an unauthenticated claim and decorating a spoofed thread with a
|
|
22
|
+
* real customer's billing history is the opening move of support-driven account takeover.
|
|
23
|
+
*
|
|
24
|
+
* **There is no `From:` here to spoof.** `requireAuth()` proved the session before the handler ran, so
|
|
25
|
+
* the account arrives already established — and the thread records that with `accountLinkSource:
|
|
26
|
+
* "session"`, so a console can tell a link that *is* the identity from one that was matched against a
|
|
27
|
+
* header. Nothing in the submitted payload names an account, and nothing here reads one from it.
|
|
28
|
+
*
|
|
29
|
+
* ## The order of operations
|
|
30
|
+
*
|
|
31
|
+
* The mail path's rule, applied to a different shape: **refuse on the cheapest true reason first.**
|
|
32
|
+
* The two shape bounds a client controls the cost of — how many files, and how large each encoded one
|
|
33
|
+
* is — are applied at the transport boundary in `http/handlers.ts` *before* anything is decoded,
|
|
34
|
+
* because `atob` materialises its whole result and a size check after it has already been handed the
|
|
35
|
+
* allocation it meant to refuse. What is left arrives here as bytes:
|
|
36
|
+
*
|
|
37
|
+
* 0. **The declared category**, which needs no I/O at all — it is a comparison against a taxonomy this
|
|
38
|
+
* process already holds, so it is genuinely the cheapest true reason there is.
|
|
39
|
+
* 1. **The account**, because everything else depends on the address a reply will come back to, and a
|
|
40
|
+
* report nobody can answer is not worth storing.
|
|
41
|
+
* 2. **The rate bound**, before anything is written.
|
|
42
|
+
* 3. **The attachments**, every one checked before one is written, so a refusal never leaves half a
|
|
43
|
+
* submission's files in the bucket.
|
|
44
|
+
* 4. **Store**, which must not fail.
|
|
45
|
+
* 5. **Dispatch classification**, which is allowed to fail — the same rule the mail path follows, and
|
|
46
|
+
* for the same reason: a model that is briefly down must never take somebody's report with it.
|
|
47
|
+
*
|
|
48
|
+
* The count bound is checked in both places on purpose. The handler's is what keeps the decode
|
|
49
|
+
* bounded; this one is what keeps the bound true for any caller that reaches this function directly,
|
|
50
|
+
* which is every test and every future transport.
|
|
51
|
+
*/
|
|
52
|
+
/** What a submission produced. */
|
|
53
|
+
export interface SubmitOutcome {
|
|
54
|
+
/** The thread it landed in — new, or the one it continued. */
|
|
55
|
+
threadId: string;
|
|
56
|
+
/** The message row it created. */
|
|
57
|
+
messageId: string;
|
|
58
|
+
/** Whether it opened a thread rather than continuing one. */
|
|
59
|
+
newThread: boolean;
|
|
60
|
+
/** How many attachments were stored. */
|
|
61
|
+
attachments: number;
|
|
62
|
+
/** Whether a classification was dispatched. */
|
|
63
|
+
classifying: boolean;
|
|
64
|
+
}
|
|
65
|
+
/** One file a submitter attached, already decoded. */
|
|
66
|
+
export interface SubmittedAttachment {
|
|
67
|
+
/** The filename as the client declared it. Untrusted; recorded, never honored. */
|
|
68
|
+
filename: string;
|
|
69
|
+
/** The MIME type as the client declared it, checked against the configured allowlist. */
|
|
70
|
+
contentType: string;
|
|
71
|
+
/** The bytes themselves. */
|
|
72
|
+
bytes: Uint8Array;
|
|
73
|
+
}
|
|
74
|
+
/** Everything a submission needs, all injectable — nothing below this reads a binding. */
|
|
75
|
+
export interface SubmitDeps {
|
|
76
|
+
/** The support tables. */
|
|
77
|
+
db: SupportDatabase;
|
|
78
|
+
/** The resolved config. */
|
|
79
|
+
config: SupportConfig;
|
|
80
|
+
/**
|
|
81
|
+
* The effective taxonomy — the shipped defaults plus the adopter's, already merged.
|
|
82
|
+
*
|
|
83
|
+
* Taken as a dep rather than re-derived from `config.categories` here, because two resolutions of one
|
|
84
|
+
* taxonomy are two things free to disagree: the classifier parses against the capability's merged
|
|
85
|
+
* set, and a submitted claim validated against a differently-merged one would be accepted or refused
|
|
86
|
+
* on a vocabulary nothing else in the process uses.
|
|
87
|
+
*/
|
|
88
|
+
categories: SupportCategories;
|
|
89
|
+
/** The R2 bucket attachments are written to. Absent means none are stored. */
|
|
90
|
+
bucket?: R2Bucket;
|
|
91
|
+
/** Whether the FTS5 index is composed. */
|
|
92
|
+
fts: boolean;
|
|
93
|
+
/**
|
|
94
|
+
* The submitter's account, by id. Returns null when `@pithy-sh/auth` is absent or the row is gone —
|
|
95
|
+
* both of which contradict the session that got here, so the caller treats it as a fault rather than
|
|
96
|
+
* as a supported state.
|
|
97
|
+
*/
|
|
98
|
+
resolveAccount: (userId: string) => Promise<{
|
|
99
|
+
email: string;
|
|
100
|
+
name?: string;
|
|
101
|
+
} | null>;
|
|
102
|
+
/** Start a classification for a stored message. Allowed to fail and allowed to decline. */
|
|
103
|
+
dispatchClassify: (messageId: string) => Promise<boolean>;
|
|
104
|
+
/** The audit seam. */
|
|
105
|
+
emit: AuditEmit;
|
|
106
|
+
/** The request logger. */
|
|
107
|
+
log: Logger;
|
|
108
|
+
/** Generate a row id. */
|
|
109
|
+
newId: () => string;
|
|
110
|
+
/** Now. */
|
|
111
|
+
now: () => Date;
|
|
112
|
+
}
|
|
113
|
+
/** What the submitter sent, with the identity taken from the session rather than from the payload. */
|
|
114
|
+
export interface SubmitInput {
|
|
115
|
+
/** The authenticated user id. **From `c.var.auth`, never from the body.** */
|
|
116
|
+
userId: string;
|
|
117
|
+
/** What the report is about. Becomes the thread's name, and the subject of every reply on it. */
|
|
118
|
+
subject: string;
|
|
119
|
+
/** The report itself, as the person wrote it. */
|
|
120
|
+
body: string;
|
|
121
|
+
/**
|
|
122
|
+
* What the submitter says this is about, from the app's own chooser. Their claim, not a
|
|
123
|
+
* classification — validated against the effective taxonomy, stored on the thread it opens, and never
|
|
124
|
+
* read by the classifier. Absent when the client offers no chooser, which stays the ordinary case.
|
|
125
|
+
*
|
|
126
|
+
* Accepted only on a submission that **opens** a thread; sending it with `threadId` is refused rather
|
|
127
|
+
* than ignored (see {@link checkDeclaredCategory}).
|
|
128
|
+
*/
|
|
129
|
+
declaredCategory?: string;
|
|
130
|
+
/** Continue this thread instead of opening one. Refused unless it is this account's own app thread. */
|
|
131
|
+
threadId?: string;
|
|
132
|
+
/** The bounded context the app supplied. */
|
|
133
|
+
context?: SupportSubmissionContext;
|
|
134
|
+
/** The files attached, already decoded. */
|
|
135
|
+
attachments: readonly SubmittedAttachment[];
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Mint an RFC 5322 message id for a submission.
|
|
139
|
+
*
|
|
140
|
+
* **Without this the conversation forks the first time the customer answers.** A reply to an app thread
|
|
141
|
+
* leaves by email carrying `In-Reply-To`, the customer's client puts that id in its `References`, and
|
|
142
|
+
* `parentCandidates` looks it up in `pithy_support_messages` — so a submission stored with no id of its
|
|
143
|
+
* own is a thread whose every answer opens a new one. The whole reason `mime/threading.ts` refuses to
|
|
144
|
+
* match on subject is that fragmented conversations are the failure mode worth engineering against.
|
|
145
|
+
*
|
|
146
|
+
* The domain comes from the inbox address, because that is the domain the reply will actually leave
|
|
147
|
+
* from; with no address configured there is no reply and therefore nothing to thread.
|
|
148
|
+
*/
|
|
149
|
+
export declare function submissionMessageId(messageId: string, inboxAddress: string | null | undefined): string | null;
|
|
150
|
+
/** Take one in-app submission. */
|
|
151
|
+
export declare function submitFeedback(deps: SubmitDeps, input: SubmitInput): Promise<SubmitOutcome>;
|
|
152
|
+
//# sourceMappingURL=submit.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"submit.d.ts","sourceRoot":"","sources":["../../src/submission/submit.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAC;AAGnE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kCAAkC,CAAC;AAG/D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEtD,OAAO,EAAgB,KAAK,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAO,EAAkB,KAAK,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAChF,OAAO,EAIL,KAAK,eAAe,EACrB,MAAM,gBAAgB,CAAC;AAOxB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAEH,kCAAkC;AAClC,MAAM,WAAW,aAAa;IAC5B,8DAA8D;IAC9D,QAAQ,EAAE,MAAM,CAAC;IACjB,kCAAkC;IAClC,SAAS,EAAE,MAAM,CAAC;IAClB,6DAA6D;IAC7D,SAAS,EAAE,OAAO,CAAC;IACnB,wCAAwC;IACxC,WAAW,EAAE,MAAM,CAAC;IACpB,+CAA+C;IAC/C,WAAW,EAAE,OAAO,CAAC;CACtB;AAED,sDAAsD;AACtD,MAAM,WAAW,mBAAmB;IAClC,kFAAkF;IAClF,QAAQ,EAAE,MAAM,CAAC;IACjB,yFAAyF;IACzF,WAAW,EAAE,MAAM,CAAC;IACpB,4BAA4B;IAC5B,KAAK,EAAE,UAAU,CAAC;CACnB;AAED,0FAA0F;AAC1F,MAAM,WAAW,UAAU;IACzB,0BAA0B;IAC1B,EAAE,EAAE,eAAe,CAAC;IACpB,2BAA2B;IAC3B,MAAM,EAAE,aAAa,CAAC;IACtB;;;;;;;OAOG;IACH,UAAU,EAAE,iBAAiB,CAAC;IAC9B,8EAA8E;IAC9E,MAAM,CAAC,EAAE,QAAQ,CAAC;IAClB,0CAA0C;IAC1C,GAAG,EAAE,OAAO,CAAC;IACb;;;;OAIG;IACH,cAAc,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC,CAAC;IACrF,2FAA2F;IAC3F,gBAAgB,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IAC1D,sBAAsB;IACtB,IAAI,EAAE,SAAS,CAAC;IAChB,0BAA0B;IAC1B,GAAG,EAAE,MAAM,CAAC;IACZ,yBAAyB;IACzB,KAAK,EAAE,MAAM,MAAM,CAAC;IACpB,WAAW;IACX,GAAG,EAAE,MAAM,IAAI,CAAC;CACjB;AAED,sGAAsG;AACtG,MAAM,WAAW,WAAW;IAC1B,6EAA6E;IAC7E,MAAM,EAAE,MAAM,CAAC;IACf,iGAAiG;IACjG,OAAO,EAAE,MAAM,CAAC;IAChB,iDAAiD;IACjD,IAAI,EAAE,MAAM,CAAC;IACb;;;;;;;OAOG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,uGAAuG;IACvG,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,4CAA4C;IAC5C,OAAO,CAAC,EAAE,wBAAwB,CAAC;IACnC,2CAA2C;IAC3C,WAAW,EAAE,SAAS,mBAAmB,EAAE,CAAC;CAC7C;AA0MD;;;;;;;;;;;GAWG;AACH,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI,CAG7G;AAED,kCAAkC;AAClC,wBAAsB,cAAc,CAAC,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,aAAa,CAAC,CAmKjG"}
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
import { SupportInvalidCategoryError, SupportNotFoundError, SupportRejectedError } from "../error/errors.js";
|
|
2
|
+
import { categoryEnum } from "../data/categories.js";
|
|
3
|
+
import { SupportAttachment } from "../data/attachment.js";
|
|
4
|
+
import { SupportMessage } from "../data/message.js";
|
|
5
|
+
import { SupportThread, UNCLASSIFIED } from "../data/thread.js";
|
|
6
|
+
import { SUPPORT_ATTACHMENTS_TABLE, SUPPORT_MESSAGES_TABLE, SUPPORT_THREADS_TABLE } from "../data/tables.js";
|
|
7
|
+
import { attachmentKey, putAttachment, sha256Hex } from "../attachment/store.js";
|
|
8
|
+
import { SupportAuditActions } from "../audit/actions.js";
|
|
9
|
+
import { indexMessage } from "../store/search.js";
|
|
10
|
+
import { safeFilename } from "../mime/parse.js";
|
|
11
|
+
import { checkAccountRate, checkAttachment } from "./guard.js";
|
|
12
|
+
import { InternalError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
13
|
+
import { chunkRowsByBoundParameters } from "@pithy-sh/core/src/data/boundParameters";
|
|
14
|
+
//#region src/submission/submit.ts
|
|
15
|
+
/** Record a refusal. Never throws — a guard decision must not become a 500 on top of a 429. */
|
|
16
|
+
async function auditRejection(deps, reason, detail, userId) {
|
|
17
|
+
try {
|
|
18
|
+
await deps.emit({
|
|
19
|
+
action: SupportAuditActions.submissionRejected,
|
|
20
|
+
outcome: "denied",
|
|
21
|
+
severity: "warning",
|
|
22
|
+
actorType: "user",
|
|
23
|
+
actorId: userId,
|
|
24
|
+
resourceType: "support_inbox",
|
|
25
|
+
metadata: {
|
|
26
|
+
reason,
|
|
27
|
+
channel: "app"
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
deps.log.warn("support submission refused", {
|
|
31
|
+
reason,
|
|
32
|
+
detail,
|
|
33
|
+
userId
|
|
34
|
+
});
|
|
35
|
+
} catch (error) {
|
|
36
|
+
deps.log.warn("support submission rejection audit dropped", {
|
|
37
|
+
reason,
|
|
38
|
+
detail,
|
|
39
|
+
error
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Resolve the thread a submission continues.
|
|
45
|
+
*
|
|
46
|
+
* **Both conditions, and a 404 rather than a 403 when either fails.** The thread must be this
|
|
47
|
+
* account's and it must be an app thread: a 403 would confirm that the id names a real conversation,
|
|
48
|
+
* which on an inbox of other people's correspondence is the disclosure the check exists to prevent —
|
|
49
|
+
* so an id belonging to somebody else is indistinguishable from one belonging to nobody.
|
|
50
|
+
*
|
|
51
|
+
* An `email` thread is excluded even when it carries this account's `userId`, and that exclusion is
|
|
52
|
+
* the point rather than an oversight: that link was matched from an address in a header nobody proved,
|
|
53
|
+
* so treating it as ownership would let whoever currently holds an address read a conversation that
|
|
54
|
+
* merely *claims* to be theirs.
|
|
55
|
+
*/
|
|
56
|
+
async function resolveOwnThread(db, threadId, userId) {
|
|
57
|
+
const thread = await db.selectFrom(SUPPORT_THREADS_TABLE).select(["id"]).where("id", "=", threadId).where("userId", "=", userId).where("channel", "=", "app").executeTakeFirst();
|
|
58
|
+
if (!thread) throw new SupportNotFoundError({ detail: `no app thread ${threadId} owned by ${userId}` });
|
|
59
|
+
return thread;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Check a submitter's declared category, before anything else and before any I/O.
|
|
63
|
+
*
|
|
64
|
+
* **An undeclared key is refused, never stored and never downgraded.** Storing it would make
|
|
65
|
+
* `declared_category` a client-writable vocabulary: one client shipping `Billing` or `billng` and the
|
|
66
|
+
* console's filter silently misses those threads forever, while the inbox grows a long tail of one-off
|
|
67
|
+
* keys nobody declared. Downgrading to `uncategorized` is the worse of the two remaining options,
|
|
68
|
+
* because it makes a broken chooser indistinguishable from a submitter who genuinely chose nothing —
|
|
69
|
+
* the exact collapse this column exists to prevent, arrived at from the other side.
|
|
70
|
+
*
|
|
71
|
+
* It is refused rather than tolerated **because the writer can be fixed.** `classifyMessage` falls back
|
|
72
|
+
* to `uncategorized` on a label the model invented, and that is right there: a model cannot be told it
|
|
73
|
+
* was wrong at the call site. A client can, and a 400 is how it gets told — the chooser was built from
|
|
74
|
+
* a taxonomy the adopter declared, so a value outside it is that client's bug and should be loud.
|
|
75
|
+
*
|
|
76
|
+
* **A category may not ride along with a `threadId`.** A thread already carries what it was filed
|
|
77
|
+
* under, and a second, later claim has no honest meaning: ignoring it is a chooser that does nothing —
|
|
78
|
+
* which is the whole defect this seam exists to close — and honoring it would let a follow-up rewrite
|
|
79
|
+
* the premise a conversation was opened on, the way `subject` deliberately cannot. So it is refused,
|
|
80
|
+
* loudly, and a chooser stays what it is: something offered on the form that opens a request.
|
|
81
|
+
*
|
|
82
|
+
* **Nothing the submitter wrote reaches `message`.** The offending value goes in `detail`, which the
|
|
83
|
+
* HTTP codec strips — this capability's whole input is text somebody else chose, and an error that
|
|
84
|
+
* echoed it back would make the error channel a reflection surface.
|
|
85
|
+
*/
|
|
86
|
+
function checkDeclaredCategory(deps, input) {
|
|
87
|
+
const declared = input.declaredCategory;
|
|
88
|
+
if (declared === void 0) return;
|
|
89
|
+
if (input.threadId !== void 0) throw new ValidationError({
|
|
90
|
+
message: "A category is chosen when a request is opened, not on a later message.",
|
|
91
|
+
action: "Send the category with the first message, or leave it off to continue the conversation.",
|
|
92
|
+
detail: `submission declared a category alongside threadId ${input.threadId}`
|
|
93
|
+
});
|
|
94
|
+
if (!categoryEnum(deps.categories).safeParse(declared).success) throw new SupportInvalidCategoryError({
|
|
95
|
+
message: "That is not a category this app offers.",
|
|
96
|
+
action: "Choose one of the categories the app declares, or send the request without one.",
|
|
97
|
+
detail: `submitted category ${JSON.stringify(declared)} is not in the effective taxonomy (${Object.keys(deps.categories).join(", ")})`
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
/** How many columns one `pithy_support_attachments` row binds — derived, so a new column re-chunks. */
|
|
101
|
+
const SUPPORT_ATTACHMENT_COLUMNS = Object.keys(SupportAttachment.shape).length;
|
|
102
|
+
/**
|
|
103
|
+
* Check every attachment before one byte is written.
|
|
104
|
+
*
|
|
105
|
+
* All-or-nothing, and refused rather than skipped — the opposite of the mail path, and the difference
|
|
106
|
+
* is who is on the other end. An oversize part of an email is dropped because the sender is gone and
|
|
107
|
+
* the message is still worth keeping; a submitter is right there, holding the screenshot that is the
|
|
108
|
+
* most valuable thing the report carries, and silently storing the report without it means the first
|
|
109
|
+
* reply asks for a file they believed they had already sent.
|
|
110
|
+
*/
|
|
111
|
+
function checkAttachments(deps, attachments) {
|
|
112
|
+
const bounds = deps.config.submission.attachments;
|
|
113
|
+
if (attachments.length === 0) return;
|
|
114
|
+
if (!bounds.enabled) throw new ValidationError({
|
|
115
|
+
message: "This app does not accept attachments on a support request.",
|
|
116
|
+
action: "Send the report without a file, and describe what you would have attached.",
|
|
117
|
+
detail: "submission.attachments.enabled is false"
|
|
118
|
+
});
|
|
119
|
+
if (attachments.length > bounds.maxCount) throw new ValidationError({
|
|
120
|
+
message: `A support request may carry at most ${bounds.maxCount} attachments.`,
|
|
121
|
+
action: `Send at most ${bounds.maxCount} files.`,
|
|
122
|
+
detail: `submission declared ${attachments.length} attachments, over the ${bounds.maxCount} bound`
|
|
123
|
+
});
|
|
124
|
+
for (const attachment of attachments) {
|
|
125
|
+
const verdict = checkAttachment(deps.config.submission, {
|
|
126
|
+
contentType: attachment.contentType,
|
|
127
|
+
bytes: attachment.bytes.byteLength
|
|
128
|
+
});
|
|
129
|
+
if (verdict.accepted) continue;
|
|
130
|
+
throw new ValidationError({
|
|
131
|
+
message: verdict.reason === "attachment_too_large" ? `An attachment may be at most ${bounds.maxBytes} bytes.` : "That kind of file cannot be attached to a support request.",
|
|
132
|
+
action: verdict.reason === "attachment_too_large" ? "Attach a smaller file." : `Attach one of: ${bounds.allowedContentTypes.join(", ")}.`,
|
|
133
|
+
detail: verdict.detail
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/** Store the checked attachments. Returns how many rows were written. */
|
|
138
|
+
async function storeAttachments(deps, attachments, threadId, messageId, now) {
|
|
139
|
+
const bucket = deps.bucket;
|
|
140
|
+
if (attachments.length === 0) return 0;
|
|
141
|
+
if (!bucket) {
|
|
142
|
+
deps.log.warn("support submission attachments dropped — no bucket bound", {
|
|
143
|
+
threadId,
|
|
144
|
+
messageId
|
|
145
|
+
});
|
|
146
|
+
return 0;
|
|
147
|
+
}
|
|
148
|
+
const rows = [];
|
|
149
|
+
for (const attachment of attachments) {
|
|
150
|
+
const id = deps.newId();
|
|
151
|
+
const key = attachmentKey(threadId, id);
|
|
152
|
+
await putAttachment(bucket, key, attachment.bytes);
|
|
153
|
+
rows.push({
|
|
154
|
+
id,
|
|
155
|
+
messageId,
|
|
156
|
+
threadId,
|
|
157
|
+
filename: safeFilename(attachment.filename),
|
|
158
|
+
contentType: attachment.contentType,
|
|
159
|
+
size: attachment.bytes.byteLength,
|
|
160
|
+
sha256: await sha256Hex(attachment.bytes),
|
|
161
|
+
storageKey: key,
|
|
162
|
+
contentId: null,
|
|
163
|
+
inline: false,
|
|
164
|
+
createdAt: now
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
const encoded = rows.map((row) => SupportAttachment.encode(row));
|
|
168
|
+
for (const chunk of chunkRowsByBoundParameters(encoded, SUPPORT_ATTACHMENT_COLUMNS)) await deps.db.insertInto(SUPPORT_ATTACHMENTS_TABLE).values(chunk).execute();
|
|
169
|
+
return rows.length;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Mint an RFC 5322 message id for a submission.
|
|
173
|
+
*
|
|
174
|
+
* **Without this the conversation forks the first time the customer answers.** A reply to an app thread
|
|
175
|
+
* leaves by email carrying `In-Reply-To`, the customer's client puts that id in its `References`, and
|
|
176
|
+
* `parentCandidates` looks it up in `pithy_support_messages` — so a submission stored with no id of its
|
|
177
|
+
* own is a thread whose every answer opens a new one. The whole reason `mime/threading.ts` refuses to
|
|
178
|
+
* match on subject is that fragmented conversations are the failure mode worth engineering against.
|
|
179
|
+
*
|
|
180
|
+
* The domain comes from the inbox address, because that is the domain the reply will actually leave
|
|
181
|
+
* from; with no address configured there is no reply and therefore nothing to thread.
|
|
182
|
+
*/
|
|
183
|
+
function submissionMessageId(messageId, inboxAddress) {
|
|
184
|
+
const domain = inboxAddress?.split("@")[1];
|
|
185
|
+
return domain ? `${messageId}@${domain}` : null;
|
|
186
|
+
}
|
|
187
|
+
/** Take one in-app submission. */
|
|
188
|
+
async function submitFeedback(deps, input) {
|
|
189
|
+
const now = deps.now();
|
|
190
|
+
checkDeclaredCategory(deps, input);
|
|
191
|
+
const account = await deps.resolveAccount(input.userId);
|
|
192
|
+
if (!account) throw new InternalError({
|
|
193
|
+
message: "Your account could not be read.",
|
|
194
|
+
action: "Retry, and contact support by email if it keeps happening.",
|
|
195
|
+
detail: `no pithy_auth_users row for authenticated user ${input.userId} — is @pithy-sh/auth composed on this Worker?`
|
|
196
|
+
});
|
|
197
|
+
const rate = await checkAccountRate(deps.db, deps.config.submission, {
|
|
198
|
+
userId: input.userId,
|
|
199
|
+
now
|
|
200
|
+
});
|
|
201
|
+
if (!rate.accepted) {
|
|
202
|
+
await auditRejection(deps, rate.reason, rate.detail, input.userId);
|
|
203
|
+
throw new SupportRejectedError({
|
|
204
|
+
message: "You have sent too many support requests recently.",
|
|
205
|
+
action: "Wait an hour and try again, or reply to the email on an existing request.",
|
|
206
|
+
detail: rate.detail
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
checkAttachments(deps, input.attachments);
|
|
210
|
+
const existing = input.threadId ? await resolveOwnThread(deps.db, input.threadId, input.userId) : void 0;
|
|
211
|
+
const threadId = existing?.id ?? deps.newId();
|
|
212
|
+
const newThread = existing === void 0;
|
|
213
|
+
const messageId = deps.newId();
|
|
214
|
+
const inbox = deps.config.reply.replyToAddress ?? deps.config.inboundAddresses[0] ?? null;
|
|
215
|
+
const message = {
|
|
216
|
+
id: messageId,
|
|
217
|
+
threadId,
|
|
218
|
+
direction: "inbound",
|
|
219
|
+
channel: "app",
|
|
220
|
+
submittedByUserId: input.userId,
|
|
221
|
+
context: input.context ?? null,
|
|
222
|
+
mimeMessageId: submissionMessageId(messageId, inbox),
|
|
223
|
+
mimeInReplyTo: null,
|
|
224
|
+
mimeReferences: null,
|
|
225
|
+
fromAddress: account.email,
|
|
226
|
+
fromName: account.name ?? null,
|
|
227
|
+
toAddress: inbox,
|
|
228
|
+
subject: input.subject,
|
|
229
|
+
textBody: input.body,
|
|
230
|
+
htmlBody: null,
|
|
231
|
+
emailJobId: null,
|
|
232
|
+
rawKey: null,
|
|
233
|
+
rawBytes: null,
|
|
234
|
+
receivedAt: now,
|
|
235
|
+
createdAt: now
|
|
236
|
+
};
|
|
237
|
+
await deps.db.insertInto(SUPPORT_MESSAGES_TABLE).values(SupportMessage.encode(message)).execute();
|
|
238
|
+
try {
|
|
239
|
+
if (newThread) {
|
|
240
|
+
const thread = {
|
|
241
|
+
id: threadId,
|
|
242
|
+
channel: "app",
|
|
243
|
+
inboxAddress: inbox,
|
|
244
|
+
subject: input.subject,
|
|
245
|
+
fromAddress: account.email,
|
|
246
|
+
fromName: account.name ?? null,
|
|
247
|
+
senderAuthenticated: true,
|
|
248
|
+
userId: input.userId,
|
|
249
|
+
accountLinkSource: "session",
|
|
250
|
+
declaredCategory: input.declaredCategory ?? null,
|
|
251
|
+
...UNCLASSIFIED,
|
|
252
|
+
archived: false,
|
|
253
|
+
archivedAt: null,
|
|
254
|
+
archivedBy: null,
|
|
255
|
+
messageCount: 1,
|
|
256
|
+
firstMessageAt: now,
|
|
257
|
+
lastMessageAt: now,
|
|
258
|
+
createdAt: now,
|
|
259
|
+
updatedAt: now
|
|
260
|
+
};
|
|
261
|
+
await deps.db.insertInto(SUPPORT_THREADS_TABLE).values(SupportThread.encode(thread)).execute();
|
|
262
|
+
} else await deps.db.updateTable(SUPPORT_THREADS_TABLE).set((eb) => ({
|
|
263
|
+
messageCount: eb("messageCount", "+", 1),
|
|
264
|
+
lastMessageAt: now.getTime(),
|
|
265
|
+
updatedAt: now.getTime(),
|
|
266
|
+
archived: 0,
|
|
267
|
+
archivedAt: null,
|
|
268
|
+
archivedBy: null
|
|
269
|
+
})).where("id", "=", threadId).execute();
|
|
270
|
+
} catch (error) {
|
|
271
|
+
await deps.db.deleteFrom(SUPPORT_MESSAGES_TABLE).where("id", "=", messageId).execute().catch(() => {
|
|
272
|
+
deps.log.error("support submission orphaned — thread write failed and the message could not be removed", {
|
|
273
|
+
messageId,
|
|
274
|
+
threadId
|
|
275
|
+
});
|
|
276
|
+
});
|
|
277
|
+
throw error;
|
|
278
|
+
}
|
|
279
|
+
if (deps.fts) try {
|
|
280
|
+
await indexMessage(deps.db, {
|
|
281
|
+
threadId,
|
|
282
|
+
messageId,
|
|
283
|
+
subject: input.subject,
|
|
284
|
+
body: input.body
|
|
285
|
+
});
|
|
286
|
+
} catch (error) {
|
|
287
|
+
deps.log.warn("support submission not indexed", {
|
|
288
|
+
messageId,
|
|
289
|
+
error
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
let attachments = 0;
|
|
293
|
+
try {
|
|
294
|
+
attachments = await storeAttachments(deps, input.attachments, threadId, messageId, now);
|
|
295
|
+
} catch (error) {
|
|
296
|
+
deps.log.warn("support submission attachments not stored", {
|
|
297
|
+
messageId,
|
|
298
|
+
error
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
const classifying = deps.config.ai.enabled;
|
|
302
|
+
if (classifying) try {
|
|
303
|
+
await deps.dispatchClassify(messageId);
|
|
304
|
+
} catch (error) {
|
|
305
|
+
deps.log.warn("support submission classification dispatch failed", {
|
|
306
|
+
messageId,
|
|
307
|
+
error
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
return {
|
|
311
|
+
threadId,
|
|
312
|
+
messageId,
|
|
313
|
+
newThread,
|
|
314
|
+
attachments,
|
|
315
|
+
classifying
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
//#endregion
|
|
319
|
+
export { submissionMessageId, submitFeedback };
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** This package's npm name — the join key against a release feed. */
|
|
2
|
+
export declare const PACKAGE_NAME = "@pithy-sh/support";
|
|
3
|
+
/** This package's version, stamped from its own package.json at generation time. */
|
|
4
|
+
export declare const PACKAGE_VERSION = "0.1.3";
|
|
5
|
+
//# sourceMappingURL=version.generated.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"version.generated.d.ts","sourceRoot":"","sources":["../src/version.generated.ts"],"names":[],"mappings":"AAWA,qEAAqE;AACrE,eAAO,MAAM,YAAY,sBAAsB,CAAC;AAEhD,oFAAoF;AACpF,eAAO,MAAM,eAAe,UAAU,CAAC"}
|