@frigear-nu/inbox 0.0.0-stage → 0.0.1

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 (174) hide show
  1. package/README.md +39 -2
  2. package/dist/module.d.mts +452 -0
  3. package/dist/module.json +9 -0
  4. package/dist/module.mjs +242 -0
  5. package/dist/runtime/access.d.ts +1 -0
  6. package/dist/runtime/access.js +62 -0
  7. package/dist/runtime/app/components/InboxChannelSlideover.d.vue.ts +12 -0
  8. package/dist/runtime/app/components/InboxChannelSlideover.vue +171 -0
  9. package/dist/runtime/app/components/InboxChannelSlideover.vue.d.ts +12 -0
  10. package/dist/runtime/app/components/InboxComposer.d.vue.ts +12 -0
  11. package/dist/runtime/app/components/InboxComposer.vue +71 -0
  12. package/dist/runtime/app/components/InboxComposer.vue.d.ts +12 -0
  13. package/dist/runtime/app/components/InboxConversation.d.vue.ts +8 -0
  14. package/dist/runtime/app/components/InboxConversation.vue +82 -0
  15. package/dist/runtime/app/components/InboxConversation.vue.d.ts +8 -0
  16. package/dist/runtime/app/components/InboxHideSlideover.d.vue.ts +12 -0
  17. package/dist/runtime/app/components/InboxHideSlideover.vue +54 -0
  18. package/dist/runtime/app/components/InboxHideSlideover.vue.d.ts +12 -0
  19. package/dist/runtime/app/components/InboxMailboxSlideover.d.vue.ts +11 -0
  20. package/dist/runtime/app/components/InboxMailboxSlideover.vue +125 -0
  21. package/dist/runtime/app/components/InboxMailboxSlideover.vue.d.ts +11 -0
  22. package/dist/runtime/app/composables/index.d.ts +6 -0
  23. package/dist/runtime/app/composables/index.js +5 -0
  24. package/dist/runtime/app/composables/useInboxChannelActions.d.ts +15 -0
  25. package/dist/runtime/app/composables/useInboxChannelActions.js +45 -0
  26. package/dist/runtime/app/composables/useInboxLinks.d.ts +11 -0
  27. package/dist/runtime/app/composables/useInboxLinks.js +17 -0
  28. package/dist/runtime/app/composables/useInboxMailboxActions.d.ts +14 -0
  29. package/dist/runtime/app/composables/useInboxMailboxActions.js +47 -0
  30. package/dist/runtime/app/composables/useInboxThreadActions.d.ts +29 -0
  31. package/dist/runtime/app/composables/useInboxThreadActions.js +76 -0
  32. package/dist/runtime/app/composables/useInboxTranslate.d.ts +3 -0
  33. package/dist/runtime/app/composables/useInboxTranslate.js +7 -0
  34. package/dist/runtime/app/dashboard/InboxMine.d.vue.ts +3 -0
  35. package/dist/runtime/app/dashboard/InboxMine.vue +25 -0
  36. package/dist/runtime/app/dashboard/InboxMine.vue.d.ts +3 -0
  37. package/dist/runtime/app/dashboard/InboxUnassigned.d.vue.ts +3 -0
  38. package/dist/runtime/app/dashboard/InboxUnassigned.vue +25 -0
  39. package/dist/runtime/app/dashboard/InboxUnassigned.vue.d.ts +3 -0
  40. package/dist/runtime/app/pages/admin-settings.d.vue.ts +3 -0
  41. package/dist/runtime/app/pages/admin-settings.vue +161 -0
  42. package/dist/runtime/app/pages/admin-settings.vue.d.ts +3 -0
  43. package/dist/runtime/app/pages/admin-thread.d.vue.ts +3 -0
  44. package/dist/runtime/app/pages/admin-thread.vue +234 -0
  45. package/dist/runtime/app/pages/admin-thread.vue.d.ts +3 -0
  46. package/dist/runtime/app/pages/admin.d.vue.ts +3 -0
  47. package/dist/runtime/app/pages/admin.vue +211 -0
  48. package/dist/runtime/app/pages/admin.vue.d.ts +3 -0
  49. package/dist/runtime/channels/email.d.ts +2 -0
  50. package/dist/runtime/channels/email.js +8 -0
  51. package/dist/runtime/channels/form.d.ts +2 -0
  52. package/dist/runtime/channels/form.js +9 -0
  53. package/dist/runtime/channels/instagram.d.ts +2 -0
  54. package/dist/runtime/channels/instagram.js +5 -0
  55. package/dist/runtime/channels/messenger.d.ts +2 -0
  56. package/dist/runtime/channels/messenger.js +5 -0
  57. package/dist/runtime/channels/whatsapp.d.ts +2 -0
  58. package/dist/runtime/channels/whatsapp.js +5 -0
  59. package/dist/runtime/i18n/lang/da.json +247 -0
  60. package/dist/runtime/i18n/lang/en.json +247 -0
  61. package/dist/runtime/menus.d.ts +2 -0
  62. package/dist/runtime/menus.js +19 -0
  63. package/dist/runtime/server/db/schema.postgresql.d.ts +1216 -0
  64. package/dist/runtime/server/db/schema.postgresql.js +154 -0
  65. package/dist/runtime/server/db/schema.sqlite.d.ts +1294 -0
  66. package/dist/runtime/server/db/schema.sqlite.js +154 -0
  67. package/dist/runtime/server/plugins/forms.d.ts +2 -0
  68. package/dist/runtime/server/plugins/forms.js +55 -0
  69. package/dist/runtime/server/plugins/links.d.ts +2 -0
  70. package/dist/runtime/server/plugins/links.js +18 -0
  71. package/dist/runtime/server/plugins/notify.d.ts +2 -0
  72. package/dist/runtime/server/plugins/notify.js +24 -0
  73. package/dist/runtime/server/plugins/seed.d.ts +2 -0
  74. package/dist/runtime/server/plugins/seed.js +7 -0
  75. package/dist/runtime/server/plugins/teams.d.ts +2 -0
  76. package/dist/runtime/server/plugins/teams.js +3 -0
  77. package/dist/runtime/server/policies.d.ts +2 -0
  78. package/dist/runtime/server/policies.js +15 -0
  79. package/dist/runtime/server/routes/admin/audit.get.d.ts +2 -0
  80. package/dist/runtime/server/routes/admin/audit.get.js +43 -0
  81. package/dist/runtime/server/routes/admin/channel.delete.d.ts +2 -0
  82. package/dist/runtime/server/routes/admin/channel.delete.js +13 -0
  83. package/dist/runtime/server/routes/admin/channel.patch.d.ts +2 -0
  84. package/dist/runtime/server/routes/admin/channel.patch.js +24 -0
  85. package/dist/runtime/server/routes/admin/channels.get.d.ts +2 -0
  86. package/dist/runtime/server/routes/admin/channels.get.js +10 -0
  87. package/dist/runtime/server/routes/admin/channels.post.d.ts +2 -0
  88. package/dist/runtime/server/routes/admin/channels.post.js +21 -0
  89. package/dist/runtime/server/routes/admin/contact-erase.post.d.ts +2 -0
  90. package/dist/runtime/server/routes/admin/contact-erase.post.js +20 -0
  91. package/dist/runtime/server/routes/admin/contact-export.get.d.ts +2 -0
  92. package/dist/runtime/server/routes/admin/contact-export.get.js +41 -0
  93. package/dist/runtime/server/routes/admin/mailbox.delete.d.ts +2 -0
  94. package/dist/runtime/server/routes/admin/mailbox.delete.js +14 -0
  95. package/dist/runtime/server/routes/admin/mailbox.get.d.ts +2 -0
  96. package/dist/runtime/server/routes/admin/mailbox.get.js +9 -0
  97. package/dist/runtime/server/routes/admin/mailbox.patch.d.ts +2 -0
  98. package/dist/runtime/server/routes/admin/mailbox.patch.js +17 -0
  99. package/dist/runtime/server/routes/admin/mailboxes.get.d.ts +2 -0
  100. package/dist/runtime/server/routes/admin/mailboxes.get.js +5 -0
  101. package/dist/runtime/server/routes/admin/mailboxes.post.d.ts +2 -0
  102. package/dist/runtime/server/routes/admin/mailboxes.post.js +22 -0
  103. package/dist/runtime/server/routes/admin/summary.get.d.ts +2 -0
  104. package/dist/runtime/server/routes/admin/summary.get.js +19 -0
  105. package/dist/runtime/server/routes/admin/thread-assignees.get.d.ts +2 -0
  106. package/dist/runtime/server/routes/admin/thread-assignees.get.js +11 -0
  107. package/dist/runtime/server/routes/admin/thread-hide.post.d.ts +2 -0
  108. package/dist/runtime/server/routes/admin/thread-hide.post.js +23 -0
  109. package/dist/runtime/server/routes/admin/thread-messages.post.d.ts +2 -0
  110. package/dist/runtime/server/routes/admin/thread-messages.post.js +10 -0
  111. package/dist/runtime/server/routes/admin/thread-notes.post.d.ts +2 -0
  112. package/dist/runtime/server/routes/admin/thread-notes.post.js +10 -0
  113. package/dist/runtime/server/routes/admin/thread.get.d.ts +2 -0
  114. package/dist/runtime/server/routes/admin/thread.get.js +27 -0
  115. package/dist/runtime/server/routes/admin/thread.patch.d.ts +2 -0
  116. package/dist/runtime/server/routes/admin/thread.patch.js +23 -0
  117. package/dist/runtime/server/routes/admin/threads.get.d.ts +2 -0
  118. package/dist/runtime/server/routes/admin/threads.get.js +49 -0
  119. package/dist/runtime/server/routes/webhooks/channel.post.d.ts +2 -0
  120. package/dist/runtime/server/routes/webhooks/channel.post.js +11 -0
  121. package/dist/runtime/server/routes/webhooks/email.post.d.ts +2 -0
  122. package/dist/runtime/server/routes/webhooks/email.post.js +38 -0
  123. package/dist/runtime/server/routes/webhooks/meta.get.d.ts +2 -0
  124. package/dist/runtime/server/routes/webhooks/meta.get.js +19 -0
  125. package/dist/runtime/server/routes/webhooks/meta.post.d.ts +2 -0
  126. package/dist/runtime/server/routes/webhooks/meta.post.js +29 -0
  127. package/dist/runtime/server/search-index.d.ts +2 -0
  128. package/dist/runtime/server/search-index.js +7 -0
  129. package/dist/runtime/server/tasks/retention.d.ts +2 -0
  130. package/dist/runtime/server/tasks/retention.js +12 -0
  131. package/dist/runtime/server/utils/inbox-audit.d.ts +17 -0
  132. package/dist/runtime/server/utils/inbox-audit.js +35 -0
  133. package/dist/runtime/server/utils/inbox-channels.d.ts +42 -0
  134. package/dist/runtime/server/utils/inbox-channels.js +73 -0
  135. package/dist/runtime/server/utils/inbox-config.d.ts +12 -0
  136. package/dist/runtime/server/utils/inbox-config.js +8 -0
  137. package/dist/runtime/server/utils/inbox-dto.d.ts +19 -0
  138. package/dist/runtime/server/utils/inbox-dto.js +92 -0
  139. package/dist/runtime/server/utils/inbox-ingest.d.ts +43 -0
  140. package/dist/runtime/server/utils/inbox-ingest.js +136 -0
  141. package/dist/runtime/server/utils/inbox-integrations.d.ts +7 -0
  142. package/dist/runtime/server/utils/inbox-integrations.js +13 -0
  143. package/dist/runtime/server/utils/inbox-mailboxes.d.ts +14 -0
  144. package/dist/runtime/server/utils/inbox-mailboxes.js +27 -0
  145. package/dist/runtime/server/utils/inbox-registry.d.ts +7 -0
  146. package/dist/runtime/server/utils/inbox-registry.js +10 -0
  147. package/dist/runtime/server/utils/inbox-retention.d.ts +57 -0
  148. package/dist/runtime/server/utils/inbox-retention.js +167 -0
  149. package/dist/runtime/server/utils/inbox-schemas.d.ts +123 -0
  150. package/dist/runtime/server/utils/inbox-schemas.js +78 -0
  151. package/dist/runtime/server/utils/inbox-search.d.ts +8 -0
  152. package/dist/runtime/server/utils/inbox-search.js +2 -0
  153. package/dist/runtime/server/utils/inbox-seed.d.ts +9 -0
  154. package/dist/runtime/server/utils/inbox-seed.js +35 -0
  155. package/dist/runtime/server/utils/inbox-send.d.ts +25 -0
  156. package/dist/runtime/server/utils/inbox-send.js +84 -0
  157. package/dist/runtime/server/utils/inbox-tombstones.d.ts +25 -0
  158. package/dist/runtime/server/utils/inbox-tombstones.js +47 -0
  159. package/dist/runtime/server/utils/inbox-webhooks.d.ts +8 -0
  160. package/dist/runtime/server/utils/inbox-webhooks.js +10 -0
  161. package/dist/runtime/server/utils/inbox.d.ts +79 -0
  162. package/dist/runtime/server/utils/inbox.js +134 -0
  163. package/dist/runtime/utils/api.d.ts +40 -0
  164. package/dist/runtime/utils/api.js +43 -0
  165. package/dist/runtime/utils/index.d.ts +44 -0
  166. package/dist/runtime/utils/index.js +27 -0
  167. package/dist/runtime/utils/payloads.d.ts +99 -0
  168. package/dist/runtime/utils/payloads.js +173 -0
  169. package/dist/runtime/utils/registry.d.ts +17 -0
  170. package/dist/runtime/utils/registry.js +29 -0
  171. package/dist/runtime/utils/signature.d.ts +14 -0
  172. package/dist/runtime/utils/signature.js +16 -0
  173. package/dist/types.d.mts +7 -0
  174. package/package.json +118 -3
@@ -0,0 +1,134 @@
1
+ import { db, schema } from "@nuxthub/db";
2
+ import { asc, eq } from "drizzle-orm";
3
+ import { PUBLIC_GRANT_KIND, SIGNED_IN_GRANT_KIND, readGrants } from "@frigear-nu/auth/grants";
4
+ import { apiError, notFound, searchContains, validationError } from "@frigear-nu/module-kit/server";
5
+ import { inboxAccess } from "../../access.js";
6
+ export const INBOX_CHUNK = 90;
7
+ export async function findInboxMailbox(id) {
8
+ const [row] = await db.select().from(schema.inboxMailboxes).where(eq(schema.inboxMailboxes.id, id)).limit(1);
9
+ return row;
10
+ }
11
+ export async function findInboxMailboxByKey(key) {
12
+ const [row] = await db.select().from(schema.inboxMailboxes).where(eq(schema.inboxMailboxes.key, key)).limit(1);
13
+ return row;
14
+ }
15
+ export async function findInboxThread(id) {
16
+ const [row] = await db.select().from(schema.inboxThreads).where(eq(schema.inboxThreads.id, id)).limit(1);
17
+ return row;
18
+ }
19
+ export async function findInboxContact(id) {
20
+ const [row] = await db.select().from(schema.inboxContacts).where(eq(schema.inboxContacts.id, id)).limit(1);
21
+ return row;
22
+ }
23
+ export async function findInboxChannelAccount(id) {
24
+ const [row] = await db.select().from(schema.inboxChannelAccounts).where(eq(schema.inboxChannelAccounts.id, id)).limit(1);
25
+ return row;
26
+ }
27
+ export async function getInboxMailboxOr404(id) {
28
+ const row = await findInboxMailbox(id);
29
+ if (!row) throw notFound("Mailbox not found.");
30
+ return row;
31
+ }
32
+ export function listInboxMailboxes() {
33
+ return db.select().from(schema.inboxMailboxes).orderBy(asc(schema.inboxMailboxes.key));
34
+ }
35
+ export async function inboxUserRefs(ids) {
36
+ const refs = /* @__PURE__ */ new Map();
37
+ for (const ref of (await loadUserRefs(ids)).values()) refs.set(ref.id, { id: ref.id, name: ref.name });
38
+ return refs;
39
+ }
40
+ export function inboxCallerRoles(event) {
41
+ const context = event.context;
42
+ context.inboxRoles ??= (async () => {
43
+ const principal = await getAuth(event);
44
+ return principal?.user ? getEffectiveRoles(event, principal.user) : [];
45
+ })();
46
+ return context.inboxRoles;
47
+ }
48
+ export function inboxCallerSubject(event, user) {
49
+ return {
50
+ user,
51
+ manages: () => allows(event, inboxAccess.permissions.manage),
52
+ roles: () => inboxCallerRoles(event)
53
+ };
54
+ }
55
+ export function inboxUserSubject(event, user) {
56
+ let roles;
57
+ return {
58
+ user,
59
+ manages: () => subjectAllowed(event, user, inboxAccess.permissions.manage),
60
+ roles: () => roles ??= getEffectiveRoles(event, user)
61
+ };
62
+ }
63
+ export async function inboxSeesHidden(subject, hiddenBelow) {
64
+ if (!hiddenBelow) return true;
65
+ return (await subject.roles()).includes(hiddenBelow);
66
+ }
67
+ export async function inboxCanAccessMailbox(event, subject, mailbox) {
68
+ if (await subject.manages()) return true;
69
+ if (mailbox.ownerType === "team" && mailbox.ownerId && await inboxIsTeamLead(event, subject.user.id, mailbox.ownerId)) return true;
70
+ const grants = readGrants(mailbox.grants).filter((grant) => grant.kind !== PUBLIC_GRANT_KIND && grant.kind !== SIGNED_IN_GRANT_KIND);
71
+ return grants.length > 0 && grantsMatch(event, subject.user, grants);
72
+ }
73
+ export async function inboxCanAccessThread(event, subject, thread, mailbox) {
74
+ if (!await inboxSeesHidden(subject, thread.hiddenBelow)) return false;
75
+ const box = mailbox ?? await findInboxMailbox(thread.mailboxId);
76
+ return !!box && inboxCanAccessMailbox(event, subject, box);
77
+ }
78
+ export async function inboxReadableMailboxes(event) {
79
+ const readable = [];
80
+ for (const mailbox of await listInboxMailboxes()) {
81
+ if (await allows(event, inboxAccess.permissions.read, mailbox)) readable.push(mailbox);
82
+ }
83
+ return readable;
84
+ }
85
+ export async function inboxVisibleThreads(event, threads) {
86
+ if (!threads.length) return [];
87
+ const readable = new Set((await inboxReadableMailboxes(event)).map((mailbox) => mailbox.id));
88
+ const roles = await inboxCallerRoles(event);
89
+ return threads.filter((thread) => readable.has(thread.mailboxId) && (!thread.hiddenBelow || roles.includes(thread.hiddenBelow)));
90
+ }
91
+ export async function getReadableInboxThreadOr404(event, id) {
92
+ const thread = await findInboxThread(id);
93
+ if (!thread || !await allows(event, inboxAccess.permissions.read, thread)) throw notFound("Thread not found.");
94
+ return thread;
95
+ }
96
+ export async function inboxAbilities(event, thread) {
97
+ const [reply, assign, hide, pii, audit, manage] = await Promise.all([
98
+ allows(event, inboxAccess.permissions.reply, thread),
99
+ allows(event, inboxAccess.permissions.assign),
100
+ allows(event, inboxAccess.permissions.hide),
101
+ allows(event, inboxAccess.permissions.pii),
102
+ allows(event, inboxAccess.permissions["inbox-audit:pii"]),
103
+ allows(event, inboxAccess.permissions.manage)
104
+ ]);
105
+ return { reply, assign, hide, pii, audit, erase: manage && pii };
106
+ }
107
+ export async function inboxUserCanAccessThread(event, userId, thread) {
108
+ const user = await loadAuthUser(userId);
109
+ if (!user) return false;
110
+ if (!await subjectAllowed(event, user, inboxAccess.permissions.reply)) return false;
111
+ return inboxCanAccessThread(event, inboxUserSubject(event, user), thread);
112
+ }
113
+ export async function inboxAssertAssignee(event, userId, thread) {
114
+ if (!await loadAuthUser(userId)) throw validationError([{ path: ["assigneeId"], message: "This user does not exist." }], "Invalid assignee");
115
+ if (!await inboxUserCanAccessThread(event, userId, thread)) {
116
+ throw apiError(409, "assignee_no_access", "This user cannot read and answer this thread: they lack access to its mailbox or the role it is hidden below.");
117
+ }
118
+ }
119
+ export const INBOX_ASSIGNEE_LIMIT = 50;
120
+ const INBOX_ASSIGNEE_SCAN = 1e3;
121
+ export async function inboxAssigneeCandidates(event, thread, options = {}) {
122
+ const users = schema.users;
123
+ const where = options.q ? searchContains(users.searchText, options.q) : void 0;
124
+ const found = [];
125
+ for (let offset = 0; offset < INBOX_ASSIGNEE_SCAN && found.length < INBOX_ASSIGNEE_LIMIT; offset += INBOX_CHUNK) {
126
+ const rows = await db.select({ id: users.id, name: users.name }).from(users).where(where).orderBy(asc(users.name), asc(users.id)).limit(INBOX_CHUNK).offset(offset);
127
+ const allowed = await Promise.all(rows.map((row) => inboxUserCanAccessThread(event, Number(row.id), thread)));
128
+ rows.forEach((row, index) => {
129
+ if (allowed[index] && found.length < INBOX_ASSIGNEE_LIMIT) found.push({ id: Number(row.id), name: row.name ?? null });
130
+ });
131
+ if (rows.length < INBOX_CHUNK) break;
132
+ }
133
+ return found;
134
+ }
@@ -0,0 +1,40 @@
1
+ export declare const inboxApi: {
2
+ readonly webhooks: {
3
+ /** `POST` an inbound email (provider-agnostic JSON, `X-Inbox-Signature: sha256=<hmac>`). */
4
+ readonly email: "/api/inbox/webhooks/email";
5
+ /** `GET` (verify token) / `POST` (`X-Hub-Signature-256`) the Meta webhook: WhatsApp, Messenger and Instagram. */
6
+ readonly meta: "/api/inbox/webhooks/meta";
7
+ /** `POST` to a channel a module registered with an `inbound` reader. */
8
+ readonly channel: (channel: string) => string;
9
+ };
10
+ readonly admin: {
11
+ /** `GET` open, unassigned and own thread counts. */
12
+ readonly summary: "/api/admin/inbox/summary";
13
+ /** `GET` the mailboxes the caller reads / `POST` a mailbox (`inbox:manage`). */
14
+ readonly mailboxes: "/api/admin/inbox/mailboxes";
15
+ /** `GET` / `PATCH` / `DELETE` one mailbox. */
16
+ readonly mailbox: (id: string) => string;
17
+ /** `GET` (paginated, `?mailbox&status&assignee&channel`) threads. */
18
+ readonly threads: "/api/admin/inbox/threads";
19
+ /** `GET` one thread with its messages / `PATCH` its status or assignee. */
20
+ readonly thread: (id: string) => string;
21
+ /** `GET` (`?q`) the people the thread can be assigned to. */
22
+ readonly assignees: (id: string) => string;
23
+ /** `POST` a reply, sent through the thread's channel. */
24
+ readonly messages: (id: string) => string;
25
+ /** `POST` an internal note. */
26
+ readonly notes: (id: string) => string;
27
+ /** `POST` `{ role }` to hide a thread below a role (`null` shows it again). */
28
+ readonly hide: (id: string) => string;
29
+ /** `GET` / `POST` channel accounts (session only). */
30
+ readonly channels: "/api/admin/inbox/channels";
31
+ /** `PATCH` / `DELETE` one channel account (session only). */
32
+ readonly channel: (id: string) => string;
33
+ /** `GET` (paginated, `?threadId&contactId&action`) the audit log. */
34
+ readonly audit: "/api/admin/inbox/audit";
35
+ /** `GET` everything stored about a contact (GDPR access request). */
36
+ readonly contactExport: (id: string) => string;
37
+ /** `POST` to anonymise a contact and blank their messages (GDPR erasure). */
38
+ readonly contactErase: (id: string) => string;
39
+ };
40
+ };
@@ -0,0 +1,43 @@
1
+ const enc = encodeURIComponent;
2
+ const ADMIN_BASE = "/api/admin/inbox";
3
+ const WEBHOOK_BASE = "/api/inbox/webhooks";
4
+ export const inboxApi = {
5
+ webhooks: {
6
+ /** `POST` an inbound email (provider-agnostic JSON, `X-Inbox-Signature: sha256=<hmac>`). */
7
+ email: `${WEBHOOK_BASE}/email`,
8
+ /** `GET` (verify token) / `POST` (`X-Hub-Signature-256`) the Meta webhook: WhatsApp, Messenger and Instagram. */
9
+ meta: `${WEBHOOK_BASE}/meta`,
10
+ /** `POST` to a channel a module registered with an `inbound` reader. */
11
+ channel: (channel) => `${WEBHOOK_BASE}/${enc(channel)}`
12
+ },
13
+ admin: {
14
+ /** `GET` open, unassigned and own thread counts. */
15
+ summary: `${ADMIN_BASE}/summary`,
16
+ /** `GET` the mailboxes the caller reads / `POST` a mailbox (`inbox:manage`). */
17
+ mailboxes: `${ADMIN_BASE}/mailboxes`,
18
+ /** `GET` / `PATCH` / `DELETE` one mailbox. */
19
+ mailbox: (id) => `${ADMIN_BASE}/mailboxes/${enc(id)}`,
20
+ /** `GET` (paginated, `?mailbox&status&assignee&channel`) threads. */
21
+ threads: `${ADMIN_BASE}/threads`,
22
+ /** `GET` one thread with its messages / `PATCH` its status or assignee. */
23
+ thread: (id) => `${ADMIN_BASE}/threads/${enc(id)}`,
24
+ /** `GET` (`?q`) the people the thread can be assigned to. */
25
+ assignees: (id) => `${ADMIN_BASE}/threads/${enc(id)}/assignees`,
26
+ /** `POST` a reply, sent through the thread's channel. */
27
+ messages: (id) => `${ADMIN_BASE}/threads/${enc(id)}/messages`,
28
+ /** `POST` an internal note. */
29
+ notes: (id) => `${ADMIN_BASE}/threads/${enc(id)}/notes`,
30
+ /** `POST` `{ role }` to hide a thread below a role (`null` shows it again). */
31
+ hide: (id) => `${ADMIN_BASE}/threads/${enc(id)}/hide`,
32
+ /** `GET` / `POST` channel accounts (session only). */
33
+ channels: `${ADMIN_BASE}/channels`,
34
+ /** `PATCH` / `DELETE` one channel account (session only). */
35
+ channel: (id) => `${ADMIN_BASE}/channels/${enc(id)}`,
36
+ /** `GET` (paginated, `?threadId&contactId&action`) the audit log. */
37
+ audit: `${ADMIN_BASE}/audit`,
38
+ /** `GET` everything stored about a contact (GDPR access request). */
39
+ contactExport: (id) => `${ADMIN_BASE}/contacts/${enc(id)}/export`,
40
+ /** `POST` to anonymise a contact and blank their messages (GDPR erasure). */
41
+ contactErase: (id) => `${ADMIN_BASE}/contacts/${enc(id)}/erase`
42
+ }
43
+ };
@@ -0,0 +1,44 @@
1
+ import type { Nuxt } from '@nuxt/schema';
2
+ import type { InboxChannelAdapter, InboxChannelDefinition, InboxExtension } from '../../types.js';
3
+ export * from './api.js';
4
+ export * from './signature.js';
5
+ export * from './payloads.js';
6
+ export { buildInboxRegistry, INBOX_CHANNEL_ID } from './registry.js';
7
+ export type { BuiltInboxRegistry } from './registry.js';
8
+ export type { InboxAttachment, InboxAuditAction, InboxAuditDto, InboxBuiltInChannel, InboxChannelAccountDto, InboxChannelAdapter, InboxChannelDefinition, InboxChannelId, InboxChannelInfo, InboxContactDetails, InboxContactDto, InboxContactExportDto, InboxExtension, InboxInboundContext, InboxInboundMessage, InboxMailboxDto, InboxMailboxOwnerType, InboxMailboxSeed, InboxMessageContext, InboxMessageDirection, InboxMessageDto, InboxRetentionMode, InboxRetentionResult, InboxSendContext, InboxSendResult, InboxSummaryDto, InboxThreadAbilities, InboxThreadAssignedContext, InboxThreadDetailDto, InboxThreadDto, InboxThreadListItemDto, InboxThreadStatus, InboxThreadStatusContext, InboxUserRef, ModuleOptions, Translated, } from '../../types.js';
9
+ /** Thread statuses, in the order the UI lists them. */
10
+ export declare const INBOX_THREAD_STATUSES: readonly ["open", "pending", "closed"];
11
+ /** English fallbacks of the status labels (`inbox.status.*`). */
12
+ export declare const INBOX_STATUS_LABELS: Record<string, string>;
13
+ /** English fallbacks of the audit actions (`inbox.audit.actions.*`). */
14
+ export declare const INBOX_AUDIT_LABELS: Record<string, string>;
15
+ /**
16
+ * Types a channel adapter: the default export of the server file a channel registration names. `send` delivers a
17
+ * reply; `inbound` (optional) reads `POST /api/inbox/webhooks/:channel`.
18
+ *
19
+ * ```ts
20
+ * export default defineInboxChannel({
21
+ * id: 'acme.sms',
22
+ * async send({ contact, message, secret }) {
23
+ * const sent = await $fetch('https://sms.example/send', { method: 'POST', headers: { authorization: `Bearer ${secret}` }, body: { to: contact.phone, text: message.body } })
24
+ * return { externalId: sent.id }
25
+ * },
26
+ * })
27
+ * ```
28
+ */
29
+ export declare const defineInboxChannel: (adapter: InboxChannelAdapter) => InboxChannelAdapter;
30
+ /** Types a channel registration (for registrations kept in their own file). */
31
+ export declare const defineInboxChannelRegistration: (channel: InboxChannelDefinition) => InboxChannelDefinition;
32
+ /**
33
+ * Registers channels from a module's `setup()`. Order between modules does not matter: the inbox reads them once every
34
+ * module is done. A channel with an id that exists already replaces it; an invalid one fails the build.
35
+ *
36
+ * ```ts
37
+ * import { extendInbox } from '@frigear-nu/inbox/utils'
38
+ *
39
+ * extendInbox(nuxt, {
40
+ * channels: [{ id: 'acme.sms', label: { da: 'SMS', en: 'Text message' }, icon: 'i-lucide-message-square', adapter: resolver.resolve('./runtime/inbox/sms') }],
41
+ * })
42
+ * ```
43
+ */
44
+ export declare function extendInbox(nuxt: Nuxt, extension: InboxExtension): void;
@@ -0,0 +1,27 @@
1
+ export * from "./api.js";
2
+ export * from "./signature.js";
3
+ export * from "./payloads.js";
4
+ export { buildInboxRegistry, INBOX_CHANNEL_ID } from "./registry.js";
5
+ export const INBOX_THREAD_STATUSES = ["open", "pending", "closed"];
6
+ export const INBOX_STATUS_LABELS = { open: "Open", pending: "Pending", closed: "Closed" };
7
+ export const INBOX_AUDIT_LABELS = {
8
+ viewed: "Viewed",
9
+ replied: "Replied",
10
+ noted: "Added a note",
11
+ assigned: "Assigned",
12
+ status: "Changed the status",
13
+ hidden: "Changed who sees it",
14
+ exported: "Exported the contact",
15
+ erased: "Erased the contact",
16
+ retention: "Retention",
17
+ linked: "Linked"
18
+ };
19
+ export const defineInboxChannel = (adapter) => adapter;
20
+ export const defineInboxChannelRegistration = (channel) => channel;
21
+ export function extendInbox(nuxt, extension) {
22
+ const options = nuxt.options;
23
+ if (options.inbox === false) return;
24
+ options.inbox ||= {};
25
+ const list = options.inbox._extensions ||= [];
26
+ list.push({ channels: [...extension.channels ?? []] });
27
+ }
@@ -0,0 +1,99 @@
1
+ import { z } from 'zod';
2
+ import type { InboxInboundMessage } from '../../types.js';
3
+ /** Longest message body stored; longer ones are cut. */
4
+ export declare const INBOX_MAX_BODY = 50000;
5
+ /**
6
+ * The provider-agnostic JSON of `POST /api/inbox/webhooks/email`. An inbound-email provider (Postmark, Mailgun,
7
+ * SendGrid, Cloudflare Email Workers, ...) is pointed at it through a small mapping, so the inbox depends on none.
8
+ */
9
+ export declare const inboxEmailPayload: z.ZodObject<{
10
+ messageId: z.ZodString;
11
+ from: z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
12
+ email: z.ZodString;
13
+ name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
14
+ }, z.core.$strip>]>;
15
+ to: z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
16
+ email: z.ZodString;
17
+ name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
18
+ }, z.core.$strip>]>, z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
19
+ email: z.ZodString;
20
+ name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
21
+ }, z.core.$strip>]>>]>;
22
+ cc: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
23
+ email: z.ZodString;
24
+ name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
25
+ }, z.core.$strip>]>, z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
26
+ email: z.ZodString;
27
+ name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
28
+ }, z.core.$strip>]>>]>>>;
29
+ subject: z.ZodOptional<z.ZodNullable<z.ZodString>>;
30
+ text: z.ZodOptional<z.ZodNullable<z.ZodString>>;
31
+ html: z.ZodOptional<z.ZodNullable<z.ZodString>>;
32
+ attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
33
+ filename: z.ZodString;
34
+ contentType: z.ZodOptional<z.ZodString>;
35
+ size: z.ZodOptional<z.ZodNumber>;
36
+ url: z.ZodOptional<z.ZodURL>;
37
+ }, z.core.$strip>>>;
38
+ authenticated: z.ZodOptional<z.ZodBoolean>;
39
+ }, z.core.$strip>;
40
+ export type InboxEmailPayload = z.infer<typeof inboxEmailPayload>;
41
+ /** `Kari <kari@example.com>` -> `kari@example.com`, lower case. */
42
+ export declare function normaliseEmail(value: string): string;
43
+ /** The display name of `Kari Nordmann <kari@example.com>`, or `null`. */
44
+ export declare function displayNameOf(value: string): string | null;
45
+ /** The thread id an email answers, from the `[ibt_...]` marker replies carry in their subject. */
46
+ export declare function threadIdFromSubject(subject: string | null | undefined): string | null;
47
+ /** A subject without the `[ibt_...]` marker and leading `Re:`/`Fwd:`/`SV:` prefixes. */
48
+ export declare function cleanSubject(subject: string | null | undefined): string | null;
49
+ /** Plain text of an HTML body: tags dropped, entities of the common characters decoded. */
50
+ export declare function htmlToText(html: string): string;
51
+ /**
52
+ * The recipients of an email payload a mailbox can be found by: `To`, then `Cc` (a mailbox copied on an email gets it
53
+ * too), lower case, once each.
54
+ */
55
+ export declare function emailRecipients(payload: InboxEmailPayload): string[];
56
+ /** The `Cc` recipients of an email payload, lower case, without `exclude` (the mailbox's own address) or repeats. */
57
+ export declare function emailCc(payload: InboxEmailPayload, exclude?: string): string[];
58
+ /** Most cc recipients stored on one message. */
59
+ export declare const INBOX_MAX_CC = 100;
60
+ /** Whether `value` is one plain email address (`kari@example.org`, no display name, no list). */
61
+ export declare function isEmailAddress(value: string): boolean;
62
+ /**
63
+ * A list of cc recipients as it is sent and stored: lower case, without display names and repeats, and only valid
64
+ * email addresses (anything else is dropped, so a malformed header never reaches a reply), at most `INBOX_MAX_CC`.
65
+ */
66
+ export declare function inboxCcList(values: ReadonlyArray<string | null | undefined> | null | undefined): string[];
67
+ /**
68
+ * The `Cc` of a reply: the stored cc recipients of the message being answered, lower case, without repeats and without
69
+ * any of `own` (the inbox's own addresses and the person the reply goes to), so a reply never copies one of our
70
+ * mailboxes back into the inbox.
71
+ */
72
+ export declare function replyCc(stored: readonly string[] | null | undefined, own: ReadonlyArray<string | null | undefined>): string[];
73
+ /** An email payload as an inbound message for the account at `address`. */
74
+ export declare function emailToInbound(payload: InboxEmailPayload, accountAddress: string): InboxInboundMessage;
75
+ /** The channels behind the Meta webhook. */
76
+ export type InboxMetaChannel = 'whatsapp' | 'messenger' | 'instagram';
77
+ export type InboxMetaInbound = InboxInboundMessage & {
78
+ channel: InboxMetaChannel;
79
+ };
80
+ /**
81
+ * The messages in a Meta webhook body: WhatsApp Cloud API (`object: 'whatsapp_business_account'`), Messenger
82
+ * (`object: 'page'`) and Instagram (`object: 'instagram'`). Delivery and read statuses, echoes of our own replies and
83
+ * anything unknown are skipped. `address` is the account the message arrived on: the WhatsApp phone number id, the
84
+ * page id or the Instagram account id.
85
+ */
86
+ export declare function parseMetaWebhook(body: unknown): InboxMetaInbound[];
87
+ /** The Graph API call that sends `text` to `recipient` from the account `accountId` (a phone number id or page id). */
88
+ export declare function metaSendRequest(channel: InboxMetaChannel, options: {
89
+ apiBase: string;
90
+ apiVersion: string;
91
+ accountId: string;
92
+ recipient: string;
93
+ text: string;
94
+ }): {
95
+ url: string;
96
+ body: Record<string, unknown>;
97
+ };
98
+ /** The id of the sent message in a Graph API response (`messages[0].id` for WhatsApp, `message_id` otherwise). */
99
+ export declare function metaSentId(response: unknown): string | null;
@@ -0,0 +1,173 @@
1
+ import { z } from "zod";
2
+ export const INBOX_MAX_BODY = 5e4;
3
+ const clip = (value) => value.length > INBOX_MAX_BODY ? value.slice(0, INBOX_MAX_BODY) : value;
4
+ const address = z.union([
5
+ z.string().trim().min(3),
6
+ z.object({ email: z.string().trim().min(3), name: z.string().trim().nullish() })
7
+ ]);
8
+ const attachment = z.object({
9
+ filename: z.string().trim().min(1).max(255),
10
+ contentType: z.string().max(255).optional(),
11
+ size: z.number().int().nonnegative().optional(),
12
+ url: z.url().optional()
13
+ });
14
+ export const inboxEmailPayload = z.object({
15
+ /** The provider's `Message-ID`: a retry with the same id is stored once. */
16
+ messageId: z.string().trim().min(1).max(998),
17
+ from: address,
18
+ to: z.union([address, z.array(address).min(1)]),
19
+ /** The `Cc` recipients, stored with the message and shown to staff with `inbox:pii`. */
20
+ cc: z.union([address, z.array(address).max(100)]).nullish(),
21
+ subject: z.string().max(998).nullish(),
22
+ text: z.string().nullish(),
23
+ html: z.string().nullish(),
24
+ attachments: z.array(attachment).max(50).optional(),
25
+ /**
26
+ * The provider's verdict that the sender is who they say (SPF, DKIM or DMARC passed). Without it the email always
27
+ * starts a new thread: a forged sender cannot write into someone else's conversation.
28
+ */
29
+ authenticated: z.boolean().optional()
30
+ });
31
+ const emailOf = (value) => typeof value === "string" ? value : value.email;
32
+ const nameOf = (value) => typeof value === "string" ? null : value.name ?? null;
33
+ export function normaliseEmail(value) {
34
+ const angled = /<([^<>]+)>/.exec(value);
35
+ return (angled ? angled[1] : value).trim().toLowerCase();
36
+ }
37
+ export function displayNameOf(value) {
38
+ const index = value.indexOf("<");
39
+ if (index <= 0 || !value.trimEnd().endsWith(">")) return null;
40
+ const name = value.slice(0, index).trim().replace(/^"|"$/g, "").trim();
41
+ return name || null;
42
+ }
43
+ export function threadIdFromSubject(subject) {
44
+ const match = /\[(ibt_[a-z0-9]{8,64})\]/i.exec(subject ?? "");
45
+ return match ? match[1].toLowerCase() : null;
46
+ }
47
+ export function cleanSubject(subject) {
48
+ const cleaned = (subject ?? "").replace(/\[ibt_[a-z0-9]{8,64}\]/gi, "").replace(/^\s*((re|fwd?|sv|vs|aw)\s*:\s*)+/i, "").trim();
49
+ return cleaned || null;
50
+ }
51
+ export function htmlToText(html) {
52
+ return html.replace(/<(script|style)[\s\S]*?<\/\1>/gi, "").replace(/<br\s*\/?>/gi, "\n").replace(/<\/(p|div|li|h[1-6]|tr)>/gi, "\n").replace(/<[^>]+>/g, "").replace(/&nbsp;/g, " ").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&").replace(/\n{3,}/g, "\n\n").trim();
53
+ }
54
+ export function emailRecipients(payload) {
55
+ const to = Array.isArray(payload.to) ? payload.to : [payload.to];
56
+ const cc = payload.cc ? Array.isArray(payload.cc) ? payload.cc : [payload.cc] : [];
57
+ return [...new Set([...to, ...cc].map((entry) => normaliseEmail(emailOf(entry))))];
58
+ }
59
+ export function emailCc(payload, exclude) {
60
+ const list2 = payload.cc ? Array.isArray(payload.cc) ? payload.cc : [payload.cc] : [];
61
+ const skip = exclude ? normaliseEmail(exclude) : void 0;
62
+ return inboxCcList(list2.map(emailOf)).filter((email) => email !== skip);
63
+ }
64
+ const emailAddress = z.email();
65
+ export const INBOX_MAX_CC = 100;
66
+ export function isEmailAddress(value) {
67
+ return value.length <= 254 && emailAddress.safeParse(value).success;
68
+ }
69
+ export function inboxCcList(values) {
70
+ const emails = (values ?? []).filter((value) => typeof value === "string").map(normaliseEmail);
71
+ return [...new Set(emails)].filter(isEmailAddress).slice(0, INBOX_MAX_CC);
72
+ }
73
+ export function replyCc(stored, own) {
74
+ const skip = new Set(own.filter((value) => !!value).map(normaliseEmail));
75
+ return inboxCcList(stored).filter((email) => !skip.has(email));
76
+ }
77
+ export function emailToInbound(payload, accountAddress) {
78
+ const from = emailOf(payload.from);
79
+ const email = normaliseEmail(from);
80
+ const body = payload.text?.trim() || (payload.html ? htmlToText(payload.html) : "");
81
+ return {
82
+ address: accountAddress,
83
+ contact: { externalId: email, email, name: nameOf(payload.from) ?? displayNameOf(from) },
84
+ externalId: payload.messageId,
85
+ subject: cleanSubject(payload.subject),
86
+ authenticated: payload.authenticated === true,
87
+ body: clip(body),
88
+ attachments: (payload.attachments ?? []).map((file) => ({ filename: file.filename, contentType: file.contentType, size: file.size, url: file.url })),
89
+ cc: emailCc(payload, accountAddress),
90
+ threadId: threadIdFromSubject(payload.subject)
91
+ };
92
+ }
93
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
94
+ const list = (value) => Array.isArray(value) ? value : [];
95
+ const str = (value) => typeof value === "string" && value ? value : void 0;
96
+ function whatsappBody(message) {
97
+ const type = str(message.type) ?? "unknown";
98
+ if (type === "text" && isObject(message.text)) return { body: str(message.text.body) ?? "", attachments: [] };
99
+ if (type === "button" && isObject(message.button)) return { body: str(message.button.text) ?? "", attachments: [] };
100
+ if (type === "interactive" && isObject(message.interactive)) {
101
+ const reply = isObject(message.interactive.button_reply) ? message.interactive.button_reply : isObject(message.interactive.list_reply) ? message.interactive.list_reply : void 0;
102
+ return { body: str(reply?.title) ?? "[interactive]", attachments: [] };
103
+ }
104
+ const media = isObject(message[type]) ? message[type] : void 0;
105
+ const caption = str(media?.caption) ?? "";
106
+ const attachments = media ? [{ filename: str(media.filename) ?? `${type}${str(media.id) ? `-${str(media.id)}` : ""}`, contentType: str(media.mime_type) }] : [];
107
+ return { body: caption || `[${type}]`, attachments };
108
+ }
109
+ function messagingBody(message) {
110
+ const attachments = list(message.attachments).filter(isObject).map((item, index) => {
111
+ const payload = isObject(item.payload) ? item.payload : {};
112
+ return { filename: `${str(item.type) ?? "file"}-${index + 1}`, url: str(payload.url) };
113
+ });
114
+ const text = str(message.text) ?? "";
115
+ return { body: text || (attachments.length ? `[${attachments.map((item) => item.filename).join(", ")}]` : ""), attachments };
116
+ }
117
+ export function parseMetaWebhook(body) {
118
+ if (!isObject(body)) return [];
119
+ const out = [];
120
+ if (body.object === "whatsapp_business_account") {
121
+ for (const entry of list(body.entry).filter(isObject)) {
122
+ for (const change of list(entry.changes).filter(isObject)) {
123
+ const value = isObject(change.value) ? change.value : void 0;
124
+ const phoneNumberId = str(isObject(value?.metadata) ? value.metadata.phone_number_id : void 0);
125
+ if (!value || !phoneNumberId) continue;
126
+ const names = new Map(list(value.contacts).filter(isObject).map((contact) => [str(contact.wa_id), str(isObject(contact.profile) ? contact.profile.name : void 0)]));
127
+ for (const message of list(value.messages).filter(isObject)) {
128
+ const from = str(message.from);
129
+ const id = str(message.id);
130
+ if (!from || !id) continue;
131
+ const { body: text, attachments } = whatsappBody(message);
132
+ out.push({
133
+ channel: "whatsapp",
134
+ address: phoneNumberId,
135
+ contact: { externalId: from, phone: `+${from.replace(/^\+/, "")}`, name: names.get(from) ?? null },
136
+ externalId: id,
137
+ body: clip(text),
138
+ attachments,
139
+ authenticated: true
140
+ });
141
+ }
142
+ }
143
+ }
144
+ return out;
145
+ }
146
+ if (body.object === "page" || body.object === "instagram") {
147
+ const channel = body.object === "page" ? "messenger" : "instagram";
148
+ for (const entry of list(body.entry).filter(isObject)) {
149
+ for (const event of list(entry.messaging).filter(isObject)) {
150
+ const message = isObject(event.message) ? event.message : void 0;
151
+ const sender = str(isObject(event.sender) ? event.sender.id : void 0);
152
+ const recipient = str(isObject(event.recipient) ? event.recipient.id : void 0) ?? str(entry.id);
153
+ const id = str(message?.mid);
154
+ if (!message || !sender || !recipient || !id || message.is_echo === true) continue;
155
+ const { body: text, attachments } = messagingBody(message);
156
+ out.push({ channel, address: recipient, contact: { externalId: sender }, externalId: id, body: clip(text), attachments, authenticated: true });
157
+ }
158
+ }
159
+ }
160
+ return out;
161
+ }
162
+ export function metaSendRequest(channel, options) {
163
+ const url = `${options.apiBase.replace(/\/+$/, "")}/${options.apiVersion}/${encodeURIComponent(options.accountId)}/messages`;
164
+ if (channel === "whatsapp") {
165
+ return { url, body: { messaging_product: "whatsapp", recipient_type: "individual", to: options.recipient, type: "text", text: { preview_url: false, body: options.text } } };
166
+ }
167
+ return { url, body: { recipient: { id: options.recipient }, messaging_type: "RESPONSE", message: { text: options.text } } };
168
+ }
169
+ export function metaSentId(response) {
170
+ if (!isObject(response)) return null;
171
+ const first = list(response.messages).find(isObject);
172
+ return str(first?.id) ?? str(response.message_id) ?? null;
173
+ }
@@ -0,0 +1,17 @@
1
+ import type { InboxChannelInfo, InboxExtension } from '../../types.js';
2
+ /** Channel ids: lower case words joined by `.`, `_` or `-` (`email`, `acme.sms`). */
3
+ export declare const INBOX_CHANNEL_ID: RegExp;
4
+ /** The built registry: what the app sees of each channel, and the server file of each adapter. */
5
+ export type BuiltInboxRegistry = {
6
+ channels: Record<string, InboxChannelInfo>;
7
+ adapters: Record<string, string>;
8
+ };
9
+ /**
10
+ * Merges channel registrations in order (built-ins, then every `extendInbox` call, then the host's own): a later
11
+ * definition with the same id replaces an earlier one, so a host can swap the adapter of a built-in channel. Returns
12
+ * the issues of invalid definitions instead of throwing, so the module can list them all.
13
+ */
14
+ export declare function buildInboxRegistry(extensions: InboxExtension[]): {
15
+ registry: BuiltInboxRegistry;
16
+ issues: string[];
17
+ };
@@ -0,0 +1,29 @@
1
+ export const INBOX_CHANNEL_ID = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/;
2
+ export function buildInboxRegistry(extensions) {
3
+ const issues = [];
4
+ const merged = /* @__PURE__ */ new Map();
5
+ for (const extension of extensions) {
6
+ for (const channel of extension.channels ?? []) {
7
+ const id = typeof channel?.id === "string" ? channel.id : "";
8
+ if (!INBOX_CHANNEL_ID.test(id)) {
9
+ issues.push(`channel "${id}": the id must be lower case words joined by ".", "_" or "-"`);
10
+ continue;
11
+ }
12
+ if (!channel.label || typeof channel.label !== "string" && typeof channel.label !== "object") {
13
+ issues.push(`channel "${id}": a label is required`);
14
+ continue;
15
+ }
16
+ if (typeof channel.adapter !== "string" || !channel.adapter) {
17
+ issues.push(`channel "${id}": \`adapter\` must be the path of a server file default-exporting defineInboxChannel()`);
18
+ continue;
19
+ }
20
+ merged.set(id, channel);
21
+ }
22
+ }
23
+ const registry = { channels: {}, adapters: {} };
24
+ for (const [id, channel] of merged) {
25
+ registry.channels[id] = { id, label: channel.label, ...channel.icon ? { icon: channel.icon } : {} };
26
+ registry.adapters[id] = channel.adapter;
27
+ }
28
+ return { registry, issues };
29
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Compares a secret a caller sent with the configured one in constant time, whatever their lengths: both are HMAC-ed
3
+ * with a fresh random key and the equal-length digests are compared, so neither the secret's length nor where the two
4
+ * differ shows in the timing. For tokens compared as text (Meta's `hub.verify_token`).
5
+ */
6
+ export declare function secretsEqual(given: string, expected: string): Promise<boolean>;
7
+ /**
8
+ * Whether `header` (`sha256=<hex>`, the shape of Meta's `X-Hub-Signature-256` and of the inbox email webhook's
9
+ * `X-Inbox-Signature`) signs `body` with `secret`. An empty secret, a missing header or another algorithm never
10
+ * verifies.
11
+ */
12
+ export declare function verifySha256Signature(secret: string | undefined, body: string | Uint8Array, header: string | null | undefined): Promise<boolean>;
13
+ /** The header value that signs `body`: what a provider (or a test) sends. */
14
+ export declare function signSha256(secret: string, body: string | Uint8Array): Promise<string>;
@@ -0,0 +1,16 @@
1
+ import { hmacSha256Hex, timingSafeEqual } from "@frigear-nu/module-kit/crypto";
2
+ import { randomToken } from "@frigear-nu/module-kit/id";
3
+ export async function secretsEqual(given, expected) {
4
+ const key = randomToken(32, "hex");
5
+ const [a, b] = await Promise.all([hmacSha256Hex(key, given), hmacSha256Hex(key, expected)]);
6
+ return timingSafeEqual(a, b);
7
+ }
8
+ export async function verifySha256Signature(secret, body, header) {
9
+ if (!secret || !header) return false;
10
+ const match = /^sha256=([0-9a-f]{64})$/i.exec(header.trim());
11
+ if (!match) return false;
12
+ return timingSafeEqual(match[1].toLowerCase(), await hmacSha256Hex(secret, body));
13
+ }
14
+ export async function signSha256(secret, body) {
15
+ return `sha256=${await hmacSha256Hex(secret, body)}`;
16
+ }
@@ -0,0 +1,7 @@
1
+ export { type Grant } from '@frigear-nu/auth/grants'
2
+
3
+ export { type OwnerRef } from '@frigear-nu/teams'
4
+
5
+ export { default } from './module.mjs'
6
+
7
+ export { type InboxAttachment, type InboxAuditAction, type InboxAuditDto, type InboxBuiltInChannel, type InboxChannelAccountDto, type InboxChannelAdapter, type InboxChannelDefinition, type InboxChannelId, type InboxChannelInfo, type InboxContactDetails, type InboxContactDto, type InboxContactExportDto, type InboxExtension, type InboxInboundContext, type InboxInboundMessage, type InboxMailboxDto, type InboxMailboxOwnerType, type InboxMailboxSeed, type InboxMessageContext, type InboxMessageDirection, type InboxMessageDto, type InboxRetentionMode, type InboxRetentionResult, type InboxRuntimeConfig, type InboxSendContext, type InboxSendResult, type InboxSummaryDto, type InboxThreadAbilities, type InboxThreadActionContext, type InboxThreadAssignedContext, type InboxThreadDetailDto, type InboxThreadDto, type InboxThreadLinkedContext, type InboxThreadListItemDto, type InboxThreadStatus, type InboxThreadStatusContext, type InboxUserRef, type ModuleOptions, type PublicModuleOptions, type Translated } from './module.mjs'