@volter/twin-hubspot 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +197 -0
  3. package/client/hubspot-mirror.css +43 -0
  4. package/client/hubspot-mirror.tsx +132 -0
  5. package/dist/client/hubspot-mirror.bundle.js +449 -0
  6. package/dist/client/hubspot-mirror.css +43 -0
  7. package/dist/client/hubspot-mirror.d.ts +15 -0
  8. package/dist/client/hubspot-mirror.js +59 -0
  9. package/dist/client/hubspot-mirror.tsx +132 -0
  10. package/dist/src/accounts.d.ts +30 -0
  11. package/dist/src/accounts.js +122 -0
  12. package/dist/src/cli.d.ts +2 -0
  13. package/dist/src/cli.js +31 -0
  14. package/dist/src/generated/surface.gen.json +1 -0
  15. package/dist/src/generated/ui.gen.json +1 -0
  16. package/dist/src/hubspot-areas.d.ts +10 -0
  17. package/dist/src/hubspot-areas.js +114 -0
  18. package/dist/src/hubspot-budget.d.ts +58 -0
  19. package/dist/src/hubspot-budget.js +176 -0
  20. package/dist/src/hubspot-capabilities.d.ts +3 -0
  21. package/dist/src/hubspot-capabilities.js +1588 -0
  22. package/dist/src/hubspot-conformance.d.ts +16 -0
  23. package/dist/src/hubspot-conformance.js +523 -0
  24. package/dist/src/hubspot-connector.d.ts +125 -0
  25. package/dist/src/hubspot-connector.js +390 -0
  26. package/dist/src/hubspot-deferred-capabilities.d.ts +6 -0
  27. package/dist/src/hubspot-deferred-capabilities.js +64 -0
  28. package/dist/src/hubspot-mirror-ui.d.ts +62 -0
  29. package/dist/src/hubspot-mirror-ui.js +152 -0
  30. package/dist/src/hubspot-oauth.d.ts +8 -0
  31. package/dist/src/hubspot-oauth.js +291 -0
  32. package/dist/src/hubspot-server.d.ts +24 -0
  33. package/dist/src/hubspot-server.js +116 -0
  34. package/dist/src/hubspot-twin.d.ts +65 -0
  35. package/dist/src/hubspot-twin.js +1558 -0
  36. package/dist/src/index.d.ts +11 -0
  37. package/dist/src/index.js +94 -0
  38. package/dist/src/manifest.d.ts +2 -0
  39. package/dist/src/manifest.js +68 -0
  40. package/dist/src/portal.d.ts +20 -0
  41. package/dist/src/portal.js +30 -0
  42. package/dist/src/screens/account.d.ts +1 -0
  43. package/dist/src/screens/account.js +139 -0
  44. package/dist/src/screens/crm.d.ts +2 -0
  45. package/dist/src/screens/crm.js +153 -0
  46. package/dist/src/screens/developer.d.ts +4 -0
  47. package/dist/src/screens/developer.js +191 -0
  48. package/dist/src/screens/forms.d.ts +5 -0
  49. package/dist/src/screens/forms.js +126 -0
  50. package/dist/src/screens/page.d.ts +21 -0
  51. package/dist/src/screens/page.js +49 -0
  52. package/dist/src/screens/session.d.ts +1 -0
  53. package/dist/src/screens/session.js +32 -0
  54. package/dist/src/semantics/crm.d.ts +8 -0
  55. package/dist/src/semantics/crm.js +101 -0
  56. package/dist/src/webhooks.d.ts +12 -0
  57. package/dist/src/webhooks.js +77 -0
  58. package/package.json +75 -0
  59. package/src/accounts.ts +127 -0
  60. package/src/cli.ts +29 -0
  61. package/src/generated/surface.gen.json +1 -0
  62. package/src/generated/ui.gen.json +1 -0
  63. package/src/hubspot-areas.ts +155 -0
  64. package/src/hubspot-budget.ts +202 -0
  65. package/src/hubspot-capabilities.ts +1523 -0
  66. package/src/hubspot-conformance.ts +537 -0
  67. package/src/hubspot-connector.ts +419 -0
  68. package/src/hubspot-deferred-capabilities.ts +99 -0
  69. package/src/hubspot-journey.uitest.ts +104 -0
  70. package/src/hubspot-mirror-ui.ts +166 -0
  71. package/src/hubspot-oauth.tsx +296 -0
  72. package/src/hubspot-server.ts +115 -0
  73. package/src/hubspot-twin.ts +1534 -0
  74. package/src/index.ts +152 -0
  75. package/src/manifest.ts +96 -0
  76. package/src/portal.ts +40 -0
  77. package/src/screens/account.tsx +129 -0
  78. package/src/screens/crm.tsx +154 -0
  79. package/src/screens/developer.tsx +181 -0
  80. package/src/screens/forms.tsx +117 -0
  81. package/src/screens/page.tsx +55 -0
  82. package/src/screens/session.tsx +36 -0
  83. package/src/semantics/crm.ts +116 -0
  84. package/src/webhooks.ts +80 -0
@@ -0,0 +1,181 @@
1
+ // AN ACCOUNT'S APPS — the developer projects an account builds and the pages it manages each app on
2
+ // (https://developers.hubspot.com/docs/apps/developer-platform/build-apps/manage-apps-in-hubspot).
3
+ //
4
+ // - POST /_twin/accounts/:hubId/projects {name, uploadedBy, platformVersion, app, webhooks?}: stands in for `hs project
5
+ // upload`, the HubSpot CLI's upload of a project to the account's developer file system, whose API HubSpot does not
6
+ // document (the CLI's requests are its own: a zip of the project and the intermediate representation
7
+ // @hubspot/project-parsing-lib makes of it, then a build and a deploy it polls). `app` is the project's
8
+ // `app-hsmeta.json` and `webhooks` its `webhooks/*-hsmeta.json`, as the configuration pages define them
9
+ // (https://developers.hubspot.com/docs/apps/developer-platform/build-apps/app-configuration,
10
+ // https://developers.hubspot.com/docs/apps/developer-platform/add-features/configure-webhooks); a second upload of a
11
+ // project updates its app, keeping the app's id, client ID and secret. 201 with the build's app.
12
+ // - /developer-projects/:hubId/project/:name/component/:uid/auth: the app's authentication details, "Your app's
13
+ // *Client ID* and *Client secret* will appear in the *Client credentials* section", and its redirect URLs and scopes.
14
+ // - /developer-projects/:hubId/project/:name/component/:uid/distribution: for an OAuth marketplace app, **Begin
15
+ // publishing** and the Acceptable Use Policy ("Until the AUP is signed, you won't be able to install your app in
16
+ // accounts other than developer test accounts"), then the sample install URL and the installed accounts ("Until your
17
+ // app is reviewed … you'll be limited to 25 installs"); for a static-token app, **Install now**, HubSpot's consent
18
+ // (**Connect app**), and the access token, which **Show** reveals.
19
+ // - POST /developer-projects/:hubId/project/:name/delete: deletes the project and its app.
20
+ //
21
+ // Where the documentation stops and the twin decides: the pages' paths and layout; an app id counts from 30000001; a
22
+ // client ID and secret are UUIDs (the OAuth page's `client_id=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`), a static token is
23
+ // `pat-na1-` and a UUID (the authentication overview masks one as `***-***-*********-…`); only a super admin of the
24
+ // account may manage its apps; the AUP panel's text is the twin's summary, not HubSpot's policy; no app the World builds
25
+ // is ever reviewed, so every install of a marketplace app is of an unverified app.
26
+ import { accountOf, appsOf, hex, installOf, keep, personOf, stored, type Row } from '../accounts.ts';
27
+ import { CSS, formOf, page, personFor, portalPage, redirect, who } from './page.tsx';
28
+ import { Consent } from '@volter/world-ui';
29
+
30
+ const uuid = (seed: string): string => { const h = hex(seed); return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20, 32)}`; };
31
+ const INSTALL_CAP = 25;
32
+
33
+ type Hsmeta = { uid?: unknown; type?: unknown; config?: Row };
34
+
35
+ /** The door standing in for `hs project upload`. */
36
+ export async function uploadDoor(hubId: number, request: Request, root: string | undefined, at: string): Promise<Response> {
37
+ let body: Row = {};
38
+ try { body = JSON.parse(await request.text()) as Row; } catch { /* refused below */ }
39
+ const refuse = (message: string): Response => Response.json({ status: 'error', message, category: 'VALIDATION_ERROR' }, { status: 400 });
40
+ const account = accountOf(hubId, root);
41
+ const uploader = personOf(String(body.uploadedBy ?? ''), root);
42
+ if (!account || account.closed_at) return refuse(`no open account ${hubId}`);
43
+ if (!uploader || uploader.hubId !== hubId || uploader.superAdmin !== true) return refuse('uploadedBy must be a super admin of the account');
44
+ const name = typeof body.name === 'string' ? body.name.trim() : '';
45
+ const app = body.app as Hsmeta | undefined;
46
+ const c = app?.config;
47
+ const auth = c?.auth as Row | undefined;
48
+ if (!name || !app || app.type !== 'app' || typeof app.uid !== 'string' || !c) return refuse('a project name and its app component (app-hsmeta.json: uid, type "app", config) are required');
49
+ if (typeof c.name !== 'string' || typeof c.description !== 'string') return refuse('app config requires name and description');
50
+ if (c.distribution !== 'marketplace' && c.distribution !== 'private') return refuse('distribution must be marketplace or private');
51
+ if (!auth || (auth.type !== 'oauth' && auth.type !== 'static')) return refuse('auth.type must be oauth or static');
52
+ if (c.distribution === 'marketplace' && auth.type !== 'oauth') return refuse('a marketplace app must use oauth');
53
+ const redirectUrls = Array.isArray(auth.redirectUrls) ? auth.redirectUrls.map(String) : [];
54
+ // "Each app must have at least one auth redirect URL, and it must use HTTPS. The only exception is that http://localhost is allowed"
55
+ if (auth.type === 'oauth' && (!redirectUrls.length || redirectUrls.some((u) => !u.startsWith('https://') && !u.startsWith('http://localhost')))) return refuse('an oauth app needs at least one redirect URL, each HTTPS (or http://localhost)');
56
+ const requiredScopes = Array.isArray(auth.requiredScopes) ? auth.requiredScopes.map(String) : [];
57
+ if (!requiredScopes.length) return refuse('an app must include at least one required scope');
58
+ const hooks = body.webhooks as Hsmeta | undefined;
59
+ const settings = (hooks?.config?.settings ?? {}) as Row;
60
+ const crmObjects = (((hooks?.config?.subscriptions ?? {}) as Row).crmObjects ?? []) as Row[];
61
+ if (hooks && (hooks.type !== 'webhooks' || typeof settings.targetUrl !== 'string')) return refuse('the webhooks component needs type "webhooks" and settings.targetUrl');
62
+ const existing = stored('_app', root).find((a) => a.hubId === hubId && a.project === name && !a.deleted_at);
63
+ const appId = existing ? Number(existing.appId) : 30000000 + stored('_app', root).length + 1;
64
+ const fields: Row = {
65
+ appId, hubId, project: name, uid: app.uid, name: c.name, description: c.description, distribution: c.distribution,
66
+ authType: auth.type, redirectUrls, requiredScopes,
67
+ optionalScopes: Array.isArray(auth.optionalScopes) ? auth.optionalScopes.map(String) : [],
68
+ platformVersion: typeof body.platformVersion === 'string' ? body.platformVersion : '2026.03',
69
+ client_id: existing?.client_id ?? uuid(`hubspot-client:${appId}`),
70
+ client_secret: existing?.client_secret ?? uuid(`hubspot-secret:${appId}:${at}`),
71
+ webhooks: hooks ? {
72
+ targetUrl: settings.targetUrl,
73
+ subscriptions: crmObjects.map((s, i) => ({ id: appId * 100 + i + 1, subscriptionType: s.subscriptionType, objectType: s.objectType, ...(s.propertyName ? { propertyName: s.propertyName } : {}), active: s.active !== false })),
74
+ } : null,
75
+ publishing: existing?.publishing ?? null, aup_signed_at: existing?.aup_signed_at ?? null, aup_signed_by: existing?.aup_signed_by ?? null,
76
+ created_at: existing?.created_at ?? at, uploaded_at: at, uploaded_by: uploader.email, deleted_at: null,
77
+ };
78
+ await keep('_app', `app:${appId}`, fields, root, at, String(uploader.email));
79
+ return Response.json({ project: name, appId, uid: app.uid, url: `/developer-projects/${hubId}/project/${encodeURIComponent(name)}/component/${encodeURIComponent(String(app.uid))}/auth` }, { status: 201 });
80
+ }
81
+
82
+ const base = (a: Row): string => `/developer-projects/${String(a.hubId)}/project/${encodeURIComponent(String(a.project))}/component/${encodeURIComponent(String(a.uid))}`;
83
+
84
+ function authPage(a: Row, account: Row, person: Row): Response {
85
+ return portalPage(`${String(a.name)} · Auth`, {
86
+ merchant: who(account, person), back: { href: `${base(a)}/distribution`, label: 'Distribution' },
87
+ sections: [
88
+ { heading: 'Client credentials', items: a.authType === 'oauth'
89
+ ? [{ title: 'Client ID', detail: String(a.client_id) }, { title: 'Client secret', detail: String(a.client_secret) }]
90
+ : [], empty: 'A static-token app has no client credentials; its access token is on the Distribution tab.' },
91
+ { heading: 'Redirect URLs', items: (a.redirectUrls as string[]).map((u) => ({ title: u })), empty: 'None.' },
92
+ { heading: 'Scopes', items: [...(a.requiredScopes as string[]).map((s) => ({ title: s, detail: 'Required' })), ...(a.optionalScopes as string[]).map((s) => ({ title: s, detail: 'Optional' }))] },
93
+ ],
94
+ });
95
+ }
96
+
97
+ function installUrl(a: Row): string {
98
+ const q = new URLSearchParams({ client_id: String(a.client_id), redirect_uri: (a.redirectUrls as string[])[0] ?? '', scope: ['oauth', ...(a.requiredScopes as string[])].join(' ') });
99
+ return `https://app.hubspot.com/oauth/authorize?${q.toString()}`;
100
+ }
101
+
102
+ function distributionPage(a: Row, account: Row, person: Row, root: string | undefined, opts: { notice?: string; show?: boolean; aup?: boolean } = {}): Response {
103
+ const installs = stored('_install', root).filter((i) => i.appId === a.appId && !i.uninstalled_at);
104
+ const d = `${base(a)}/distribution`;
105
+ if (a.authType === 'static') {
106
+ const install = installOf(Number(a.appId), Number(a.hubId), root);
107
+ return portalPage(`${String(a.name)} · Distribution`, {
108
+ merchant: who(account, person), back: { href: `${base(a)}/auth`, label: 'Auth' }, ...(opts.notice ? { notice: opts.notice } : {}),
109
+ sections: [{ heading: 'Manage distribution', items: [install
110
+ ? { title: String(account.name), detail: `Access token: ${opts.show ? String(install.static_token) : `${String(install.static_token).slice(0, 8)}${'•'.repeat(12)}`}`, note: `Installed ${String(install.installed_at).slice(0, 10)}`, actions: opts.show ? [] : [{ label: 'Show', action: `${d}?show=token`, method: 'get' as const }] }
111
+ : { title: String(account.name), detail: 'Not installed', actions: [{ label: 'Install now', action: `${d}/install` }] }] }],
112
+ });
113
+ }
114
+ const published = !!a.publishing;
115
+ const signed = !!a.aup_signed_at;
116
+ return portalPage(`${String(a.name)} · Distribution`, {
117
+ merchant: who(account, person), back: { href: `${base(a)}/auth`, label: 'Auth' }, ...(opts.notice ? { notice: opts.notice } : {}),
118
+ sections: [
119
+ { heading: 'Distribution', items: [signed
120
+ ? { title: 'Unlisted marketplace app', detail: `Install URL: ${installUrl(a)}`, note: `${installs.length} of ${INSTALL_CAP} installs before listing` }
121
+ : { title: 'Not published', detail: 'Until the AUP is signed, you won\'t be able to install your app in accounts other than developer test accounts.', actions: [{ label: published ? 'Continue publishing' : 'Begin publishing', action: `${d}/begin-publishing`, tone: 'primary' as const }] }] },
122
+ ...(opts.aup && !signed ? [{ heading: 'Acceptable Use Policy', items: [{ title: 'HubSpot App Acceptable Use Policy', detail: 'Review and sign the policy to install this app in accounts other than developer test accounts.', actions: [{ label: 'Sign', action: `${d}/aup`, tone: 'primary' as const, fields: { accept: 'yes' } }] }] }] : []),
123
+ { heading: 'Installed accounts', items: installs.map((i) => ({ title: String(accountOf(Number(i.hubId), root)?.name ?? i.hubId), note: `Installed ${String(i.installed_at).slice(0, 10)}` })), empty: 'No installs yet.' },
124
+ ],
125
+ });
126
+ }
127
+
128
+ /** app.hubspot.com/developer-projects/…, or undefined for another path. */
129
+ export async function developerPages(request: Request, root: string | undefined, at: string): Promise<Response | undefined> {
130
+ const url = new URL(request.url);
131
+ const m = /^\/developer-projects\/(\d+)\/project\/([^/]+)(?:\/component\/([^/]+)\/(auth|distribution)(?:\/(begin-publishing|aup|install|install\/confirm))?|\/(delete))$/.exec(url.pathname.replace(/\/+$/, ''));
132
+ if (!m) return undefined;
133
+ const hubId = Number(m[1]);
134
+ const got = personFor(request, hubId, root);
135
+ if (got instanceof Response) return got;
136
+ const { person, account } = got;
137
+ if (person.superAdmin !== true) return page('HubSpot', CSS.portal, <main className="portal-main"><h1>Only a super admin can manage this account's apps.</h1></main>, 403);
138
+ const app = appsOf(hubId, root).find((a) => a.project === decodeURIComponent(m[2]!) && (m[3] === undefined || a.uid === decodeURIComponent(m[3])));
139
+ if (!app) return page('HubSpot', CSS.portal, <main className="portal-main"><h1>This project doesn't exist.</h1></main>, 404);
140
+ const actor = String(person.email);
141
+ if (m[6] === 'delete') {
142
+ if (request.method !== 'POST') return undefined;
143
+ await keep('_app', `app:${String(app.appId)}`, { ...app, deleted_at: at, deleted_by: actor }, root, at, actor);
144
+ return portalPage('Projects', { merchant: who(account, person), notice: `Project ${String(app.project)} deleted.`, sections: [] });
145
+ }
146
+ const tab = m[4]!;
147
+ const act = m[5];
148
+ if (!act) {
149
+ if (request.method !== 'GET') return undefined;
150
+ return tab === 'auth' ? authPage(app, account, person) : distributionPage(app, account, person, root, { show: url.searchParams.get('show') === 'token' });
151
+ }
152
+ if (request.method !== 'POST' || tab !== 'distribution') return undefined;
153
+ if (act === 'begin-publishing' && app.distribution === 'marketplace') {
154
+ const withPanel = { ...app, publishing: app.publishing ?? at };
155
+ if (!app.publishing) await keep('_app', `app:${String(app.appId)}`, withPanel, root, at, actor);
156
+ return distributionPage(withPanel, account, person, root, { aup: true });
157
+ }
158
+ if (act === 'aup' && app.distribution === 'marketplace' && app.publishing) {
159
+ if ((await formOf(request)).accept !== 'yes') return distributionPage(app, account, person, root, { aup: true, notice: 'Sign the Acceptable Use Policy to continue.' });
160
+ const signed = { ...app, aup_signed_at: at, aup_signed_by: actor };
161
+ await keep('_app', `app:${String(app.appId)}`, signed, root, at, actor);
162
+ return distributionPage(signed, account, person, root, { notice: 'Acceptable Use Policy signed. You can install this app with its install URL.' });
163
+ }
164
+ if (act === 'install' && app.authType === 'static') {
165
+ return page(`Connect ${String(app.name)}`, CSS.consent, (
166
+ <Consent heading={`Connect ${String(app.name)} to ${String(account.name)}`} app={{ name: String(app.name) }}
167
+ request={`${String(account.name)} · Hub ID ${hubId}`}
168
+ permissions={(app.requiredScopes as string[]).map((s) => ({ title: s, detail: 'Requested scope' }))}
169
+ action={`${base(app)}/distribution/install/confirm`} fields={{}}
170
+ deny={{ name: 'answer', value: 'cancel', label: 'Cancel' }} allow={{ name: 'answer', value: 'allow', label: 'Connect app' }} />
171
+ ));
172
+ }
173
+ if (act === 'install/confirm' && app.authType === 'static') {
174
+ if ((await formOf(request)).answer !== 'allow') return redirect(`${base(app)}/distribution`);
175
+ if (installOf(Number(app.appId), hubId, root)) return distributionPage(app, account, person, root, { notice: 'This app is already installed.' });
176
+ const token = `pat-na1-${uuid(`hubspot-static:${String(app.appId)}:${at}`)}`;
177
+ await keep('_install', `install:${String(app.appId)}:${hubId}:${at}`, { appId: app.appId, hubId, installed_by: actor, scopes: app.requiredScopes, installed_at: at, uninstalled_at: null, static_token: token }, root, at, actor);
178
+ return redirect(`${base(app)}/distribution`);
179
+ }
180
+ return undefined;
181
+ }
@@ -0,0 +1,117 @@
1
+ // HUBSPOT FORMS — an account's forms, built on its form builder and filled in on a website
2
+ // (https://knowledge.hubspot.com/forms/create-forms; Dub's guide, https://dub.co/docs/integrations/hubspot, "Option 1: Using HubSpot
3
+ // Forms": "In the HubSpot form builder, add a hidden field and map it to the **Dub Id** contact property").
4
+ //
5
+ // - app.hubspot.com/forms/:hubId: the account's forms, and **Create form** with its name (a form starts with Email,
6
+ // First name and Last name, contact fields).
7
+ // - app.hubspot.com/forms/:hubId/editor/:formGuid/edit: the form's fields, and **Add hidden field** mapped to a contact
8
+ // property a form may use (a property with `formField`, as Dub makes its Dub Click ID: `formField: true`, "Allow the
9
+ // property to be used in a HubSpot form").
10
+ // - POST https://api.hsforms.com/submissions/v3/integration/submit/:portalId/:formGuid: a visitor's submission, as HubSpot's
11
+ // Forms API takes it ("Submit data to a form (unauthenticated)",
12
+ // https://developers.hubspot.com/docs/api-reference/legacy/marketing/forms/v3-legacy/submit-data-unauthenticated):
13
+ // `fields`, each `{objectTypeId, name, value}`, and `context`; a field the form does not have is refused
14
+ // (`FIELD_NOT_IN_FORM_DEFINITION`), and an accepted submission answers `inlineMessage`. It makes or updates the
15
+ // contact with that email in the form's account (portal.ts: `FORM`), whose webhook events follow.
16
+ //
17
+ // Where the documentation stops and the twin decides: the builder's paths and layout; a new form's three fields and its
18
+ // thank-you message ("Thanks for submitting the form."); the embed Dub's guide puts on a site (js.hsforms.net) submits
19
+ // through a request HubSpot does not document, so a visitor's submission is the Forms API's documented one; a submission
20
+ // without an email, or with one that is not an address, is refused as `INVALID_EMAIL`; a contact is found by its email
21
+ // to be updated, as HubSpot deduplicates contacts by email.
22
+ import { accountOf, hex, keep, stored, type Row } from '../accounts.ts';
23
+ import { handleHubspotTwinRequest } from '../hubspot-twin.ts';
24
+ import { inPortal } from '../portal.ts';
25
+ import { formOf, personFor, portalPage, redirect, who } from './page.tsx';
26
+
27
+ export const FORMS_HOST = 'api.hsforms.com';
28
+ const DEFAULT_FIELDS = [
29
+ { name: 'email', label: 'Email', hidden: false },
30
+ { name: 'firstname', label: 'First name', hidden: false },
31
+ { name: 'lastname', label: 'Last name', hidden: false },
32
+ ];
33
+
34
+ const formsOf = (hub: number, root?: string): Row[] => stored('_form', root).filter((f) => f.hubId === hub && !f.archived);
35
+ const uuid = (seed: string): string => { const h = hex(seed); return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20, 32)}`; };
36
+
37
+ /** app.hubspot.com/forms/…, or undefined for another path. */
38
+ export async function formPages(request: Request, root: string | undefined, at: string): Promise<Response | undefined> {
39
+ const path = new URL(request.url).pathname.replace(/\/+$/, '');
40
+ const m = /^\/forms\/(\d+)(?:\/editor\/([0-9a-f-]+)\/edit)?$/.exec(path);
41
+ if (!m) return undefined;
42
+ const hub = Number(m[1]);
43
+ const got = personFor(request, hub, root);
44
+ if (got instanceof Response) return got;
45
+ const { person, account } = got;
46
+ const actor = String(person.email);
47
+ if (!m[2]) {
48
+ if (request.method === 'POST') {
49
+ const name = ((await formOf(request)).name ?? '').trim();
50
+ if (!name) return listPage(hub, account, person, root, 'A form needs a name.', 422);
51
+ const guid = uuid(`hubspot-form:${hub}:${name}:${at}`);
52
+ await keep('_form', `form:${guid}`, { guid, hubId: hub, name, fields: DEFAULT_FIELDS, created_at: at, created_by: actor, archived: false }, root, at, actor);
53
+ return redirect(`/forms/${hub}/editor/${guid}/edit`);
54
+ }
55
+ return listPage(hub, account, person, root);
56
+ }
57
+ const form = formsOf(hub, root).find((f) => f.guid === m[2]);
58
+ if (!form) return portalPage('Forms', { merchant: who(account, person), notice: 'This form does not exist.', sections: [] }, 404);
59
+ const properties = await inPortal({ hub, source: 'CRM_UI' }, () => handleHubspotTwinRequest({ method: 'GET', path: '/crm/v3/properties/contacts', root, occurredAt: at }));
60
+ const usable = (((properties.body as Row).results ?? []) as Row[]).filter((p) => p.formField === true && p.archived !== true);
61
+ let notice: string | undefined;
62
+ if (request.method === 'POST') {
63
+ const wanted = (await formOf(request)).property;
64
+ const property = usable.find((p) => p.name === wanted);
65
+ const fields = form.fields as Row[];
66
+ if (!property) notice = 'Choose a contact property that can be used in forms.';
67
+ else if (fields.some((f) => f.name === property.name)) notice = `${String(property.label)} is already on this form.`;
68
+ else {
69
+ await keep('_form', `form:${String(form.guid)}`, { ...form, fields: [...fields, { name: property.name, label: property.label, hidden: true }], updated_at: at }, root, at, actor);
70
+ return redirect(`/forms/${hub}/editor/${String(form.guid)}/edit`);
71
+ }
72
+ }
73
+ return portalPage(String(form.name), { merchant: who(account, person), back: { href: `/forms/${hub}`, label: 'Forms' }, ...(notice ? { notice } : {}),
74
+ sections: [{ heading: 'Fields', items: (form.fields as Row[]).map((f) => ({ title: String(f.label), detail: String(f.name), ...(f.hidden ? { badge: 'Hidden' } : {}) })) },
75
+ { heading: 'Embed', items: [{ title: 'Form ID', detail: String(form.guid) }, { title: 'Portal ID', detail: String(hub) }] }],
76
+ forms: [{ heading: 'Add hidden field', action: `/forms/${hub}/editor/${String(form.guid)}/edit`, submit: { label: 'Add' },
77
+ fields: [{ id: 'property', label: 'Contact property', options: usable.map((p) => ({ value: String(p.name), label: String(p.label) })) }] }] });
78
+ }
79
+
80
+ function listPage(hub: number, account: Row, person: Row, root: string | undefined, notice?: string, status = 200): Response {
81
+ return portalPage('Forms', { merchant: who(account, person), ...(notice ? { notice } : {}),
82
+ sections: [{ heading: 'Forms', empty: 'No forms yet.', items: formsOf(hub, root).map((f) => ({ title: String(f.name), detail: String(f.guid), actions: [{ label: 'Edit', action: `/forms/${hub}/editor/${String(f.guid)}/edit`, method: 'get' as const }] })) }],
83
+ forms: [{ heading: 'Create form', action: `/forms/${hub}`, submit: { label: 'Create form' }, fields: [{ id: 'name', label: 'Form name' }] }] }, status);
84
+ }
85
+
86
+ const submitError = (errorType: string, message: string): Response => Response.json({ status: 'error', message: 'The request is not valid', errors: [{ message, errorType }] }, { status: 400 });
87
+
88
+ /** api.hsforms.com's submission, or undefined for another request. */
89
+ export async function formSubmission(request: Request, root: string | undefined, at: string): Promise<Response | undefined> {
90
+ const m = /^\/submissions\/v3\/integration\/submit\/(\d+)\/([0-9a-f-]+)$/.exec(new URL(request.url).pathname.replace(/\/+$/, ''));
91
+ if (!m || request.method !== 'POST') return undefined;
92
+ const hub = Number(m[1]);
93
+ const form = accountOf(hub, root)?.closed_at ? undefined : formsOf(hub, root).find((f) => f.guid === m[2]);
94
+ if (!form) return Response.json({ status: 'error', message: 'Form not found', category: 'OBJECT_NOT_FOUND' }, { status: 404 });
95
+ let body: Row = {};
96
+ try { body = JSON.parse(await request.text()) as Row; } catch { return submitError('INVALID_METADATA', 'The request body is not valid JSON.'); }
97
+ const fields = Array.isArray(body.fields) ? (body.fields as Row[]) : [];
98
+ const names = new Set((form.fields as Row[]).map((f) => String(f.name)));
99
+ const properties: Record<string, string> = {};
100
+ for (const f of fields) {
101
+ if (!names.has(String(f.name))) return submitError('FIELD_NOT_IN_FORM_DEFINITION', `${String(f.name)} is not a field of this form.`);
102
+ properties[String(f.name)] = String(f.value ?? '');
103
+ }
104
+ const email = (properties.email ?? '').trim().toLowerCase();
105
+ if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) return submitError('INVALID_EMAIL', 'Email address is invalid.');
106
+ properties.email = email;
107
+ await inPortal({ hub, source: 'FORM', sourceId: String(form.guid) }, async () => {
108
+ const found = await handleHubspotTwinRequest({ method: 'POST', path: '/crm/v3/objects/contacts/search', body: JSON.stringify({ filterGroups: [{ filters: [{ propertyName: 'email', operator: 'EQ', value: email }] }], limit: 1 }), root, occurredAt: at });
109
+ const id = ((((found.body as Row).results ?? []) as Row[])[0])?.id;
110
+ await handleHubspotTwinRequest(id === undefined
111
+ ? { method: 'POST', path: '/crm/v3/objects/contacts', body: JSON.stringify({ properties }), root, occurredAt: at }
112
+ : { method: 'PATCH', path: `/crm/v3/objects/contacts/${String(id)}`, body: JSON.stringify({ properties }), root, occurredAt: at });
113
+ });
114
+ const n = stored('_form_submission', root).length + 1;
115
+ await keep('_form_submission', `submission:${n}`, { n, formGuid: form.guid, hubId: hub, fields, context: body.context ?? null, submitted_at: at }, root, at, email);
116
+ return Response.json({ inlineMessage: 'Thanks for submitting the form.' });
117
+ }
@@ -0,0 +1,55 @@
1
+ // What every HubSpot page the twin serves shares: HubSpot's skin over @volter/world-ui's pieces, the signed-in person a
2
+ // page requires, and a form body. Nothing of HubSpot's pages is copied.
3
+ import type { ReactElement } from 'react';
4
+ import { CONSENT_CSS, flowPage, Portal, PORTAL_CSS, SIGN_IN_CSS, type PortalProps } from '@volter/world-ui';
5
+ import { accountOf, signedIn, type Row } from '../accounts.ts';
6
+
7
+ // HubSpot's skin: its slate ink, light grey panels and orange primary buttons
8
+ export const SKIN = `
9
+ body { background: #ffffff; color: #33475b; font-family: "Lexend Deca", Helvetica, Arial, sans-serif; }
10
+ .sign-in-mark, .consent-vendor { background: #ff7a59; }
11
+ .sign-in-box, .consent-box { background: #ffffff; border-color: #cbd6e2; }
12
+ .sign-in-error { background: #fdedee; border-color: #f2545b; }
13
+ .sign-in-submit, .consent-allow, .portal-primary { background: #ff7a59; border-color: #ff7a59; color: #ffffff; }
14
+ .consent-badge { background: #f5f8fa; border: 1px solid #cbd6e2; color: #33475b; }
15
+ .consent-link, .consent-actions { border-color: #cbd6e2; }
16
+ .consent-who small, .consent-permission summary small, .consent-note { color: #516f90; }
17
+ .consent-deny { background: #ffffff; border-color: #cbd6e2; color: #33475b; }
18
+ .portal-side { background: #f5f8fa; border-right: 1px solid #cbd6e2; }
19
+ .portal-section h2 { border-color: #cbd6e2; color: #516f90; }
20
+ .portal-notice { background: #e5f5f8; border: 1px solid #7fd1de; word-break: break-all; }
21
+ .portal-button { background: #ffffff; border-color: #cbd6e2; color: #33475b; }
22
+ .portal-danger { color: #d94c53; }
23
+ `;
24
+ export const CSS = { signIn: [SIGN_IN_CSS, SKIN], consent: [CONSENT_CSS, SKIN], portal: [PORTAL_CSS, SKIN] };
25
+
26
+ /** A settings or record page: the account and person on the left, the page's sections and forms. */
27
+ export function portalPage(title: string, props: PortalProps, status = 200): Response {
28
+ return flowPage({ title: `${title} | HubSpot`, css: CSS.portal, status, body: <Portal {...props} /> });
29
+ }
30
+
31
+ export function page(title: string, css: string[], body: ReactElement, status = 200): Response {
32
+ return flowPage({ title: `${title} | HubSpot`, css, status, body });
33
+ }
34
+
35
+ export function redirect(location: string): Response {
36
+ return new Response(null, { status: 302, headers: { location } });
37
+ }
38
+
39
+ export async function formOf(request: Request): Promise<Record<string, string>> {
40
+ return Object.fromEntries(new URLSearchParams(await request.text()));
41
+ }
42
+
43
+ /** The person a page needs, signed in to the account the page is of; a redirect to the sign-in, or a refusal, if not. */
44
+ export function personFor(request: Request, hubId: number | undefined, root?: string): { person: Row; account: Row } | Response {
45
+ const person = signedIn(request, root);
46
+ const url = new URL(request.url);
47
+ if (!person) return redirect(`/login?loginRedirectUrl=${encodeURIComponent(url.pathname + url.search)}`);
48
+ const account = accountOf(Number(person.hubId), root);
49
+ if (!account || (hubId !== undefined && Number(person.hubId) !== hubId)) return page('HubSpot', CSS.portal, <main className="portal-main"><h1>You don't have access to this account.</h1></main>, 403);
50
+ if (account.closed_at) return page('HubSpot', CSS.portal, <main className="portal-main"><h1>This account has been closed.</h1></main>, 403);
51
+ return { person, account };
52
+ }
53
+
54
+ /** The left column every account page carries. */
55
+ export const who = (account: Row, person: Row): string => `${String(account.name)} · ${String(person.email)}`;
@@ -0,0 +1,36 @@
1
+ // HUBSPOT'S SIGN-IN — app.hubspot.com/login (docs/contributing/architecture.md, "Who is on a screen"): a person gives
2
+ // the email and password the World gave them (accounts.ts's sign-up door), and the session cookie names them to every
3
+ // page after; a page asked for by nobody signed in sends its visitor here with `loginRedirectUrl`, and the sign-in returns
4
+ // them there. Built from @volter/world-ui's sign-in under HubSpot's skin.
5
+ //
6
+ // Where the documentation stops and the twin decides: the cookie is `hs_session`; a refused sign-in shows the form again
7
+ // with "The email or password you entered is incorrect." (200); HubSpot's own sign-in also offers Google, Microsoft and
8
+ // single sign-on, which the twin does not model.
9
+ import { SignIn } from '@volter/world-ui';
10
+ import { hex, keep, passwordHash, personOf, SESSION_COOKIE, stored } from '../accounts.ts';
11
+ import { CSS, formOf, page } from './page.tsx';
12
+
13
+ /** A return address on app.hubspot.com, never another site. */
14
+ const back = (raw: string | null | undefined): string => (raw && raw.startsWith('/') && !raw.startsWith('//') ? raw : '/');
15
+
16
+ function signInPage(to: string, email?: string, error?: string): Response {
17
+ return page('Log in', CSS.signIn, (
18
+ <SignIn heading="Log in to HubSpot" action="/login" fields={{ loginRedirectUrl: to }}
19
+ account={{ name: 'email', label: 'Email address', ...(email ? { value: email } : {}) }}
20
+ password={{ name: 'password', label: 'Password' }} submit="Log in" {...(error ? { error } : {})} />
21
+ ));
22
+ }
23
+
24
+ export async function signIn(request: Request, root: string | undefined, at: string): Promise<Response> {
25
+ if (request.method === 'GET') return signInPage(back(new URL(request.url).searchParams.get('loginRedirectUrl')));
26
+ const f = await formOf(request);
27
+ const email = (f.email ?? '').trim().toLowerCase();
28
+ const to = back(f.loginRedirectUrl);
29
+ const person = personOf(email, root);
30
+ if (!person || person.hash !== passwordHash(email, f.password ?? '')) return signInPage(to, email, 'The email or password you entered is incorrect.');
31
+ const token = hex(`hubspot-session:${email}:${at}:${stored('_web_session', root).length + 1}`).slice(0, 40);
32
+ await keep('_web_session', `session:${token}`, { token, email, created_at: at }, root, at, email);
33
+ const headers = new Headers({ location: to });
34
+ headers.append('set-cookie', `${SESSION_COOKIE}=${token}; Path=/; HttpOnly; Secure; SameSite=Lax`);
35
+ return new Response(null, { status: 302, headers });
36
+ }
@@ -0,0 +1,116 @@
1
+ // HubSpot's handlers, by operationId (docs/contributing/architecture.md, "The semantics layer"): every operation of the
2
+ // nine documents' union (../generated/surface.gen.json) the twin serves. Each CRM operation delegates to the pack's
3
+ // request handler (../hubspot-twin.ts), which keeps HubSpot's records, properties, pipelines, owners and associations
4
+ // and answers in HubSpot's `{status: "error", message, correlationId, category}` body; each OAuth operation to the
5
+ // install's token endpoints (../hubspot-oauth.tsx). An operation of the surface not named here is the gap: a contact's
6
+ // GDPR delete, the properties' batch read and batch archive, the pipeline and stage audits, the associations' batch
7
+ // default and label-archive calls and high-usage report, and the refresh-token reads and deletes.
8
+ //
9
+ // These are dispatch handlers, not `bindSemantics` ones, as turbopuffer's are: a record write is one kernel action
10
+ // over the record and the associations it names, which a semantics context's single-subject write cannot make, and the
11
+ // request handler's store is the vendor's behaviour.
12
+ import type { DerivedCall, DerivedHandler } from '@volter/world-core';
13
+
14
+ /** The operations served by the pack's request handler, every CRM operation the twin serves. */
15
+ export const CRM_HANDLED = [
16
+ // /crm/v3/objects
17
+ 'delete-/crm/v3/objects/0-3/{dealId}_archive',
18
+ 'delete-/crm/v3/objects/companies/{companyId}_archive',
19
+ 'delete-/crm/v3/objects/contacts/{contactId}_archive',
20
+ 'delete-/crm/v3/objects/tickets/{ticketId}_archive',
21
+ 'get-/crm/v3/objects/0-3_getPage',
22
+ 'get-/crm/v3/objects/0-3/{dealId}_getById',
23
+ 'get-/crm/v3/objects/companies_getPage',
24
+ 'get-/crm/v3/objects/companies/{companyId}_getById',
25
+ 'get-/crm/v3/objects/contacts_getPage',
26
+ 'get-/crm/v3/objects/contacts/{contactId}_getById',
27
+ 'get-/crm/v3/objects/tickets_getPage',
28
+ 'get-/crm/v3/objects/tickets/{ticketId}_getById',
29
+ 'patch-/crm/v3/objects/0-3/{dealId}_update',
30
+ 'patch-/crm/v3/objects/companies/{companyId}_update',
31
+ 'patch-/crm/v3/objects/contacts/{contactId}_update',
32
+ 'patch-/crm/v3/objects/tickets/{ticketId}_update',
33
+ 'post-/crm/v3/objects/0-3_create',
34
+ 'post-/crm/v3/objects/0-3/batch/archive_archive',
35
+ 'post-/crm/v3/objects/0-3/batch/create_create',
36
+ 'post-/crm/v3/objects/0-3/batch/read_read',
37
+ 'post-/crm/v3/objects/0-3/batch/update_update',
38
+ 'post-/crm/v3/objects/0-3/batch/upsert_upsert',
39
+ 'post-/crm/v3/objects/0-3/merge_merge',
40
+ 'post-/crm/v3/objects/0-3/search_doSearch',
41
+ 'post-/crm/v3/objects/companies_create',
42
+ 'post-/crm/v3/objects/companies/batch/archive_archive',
43
+ 'post-/crm/v3/objects/companies/batch/create_create',
44
+ 'post-/crm/v3/objects/companies/batch/read_read',
45
+ 'post-/crm/v3/objects/companies/batch/update_update',
46
+ 'post-/crm/v3/objects/companies/batch/upsert_upsert',
47
+ 'post-/crm/v3/objects/companies/merge_merge',
48
+ 'post-/crm/v3/objects/companies/search_doSearch',
49
+ 'post-/crm/v3/objects/contacts_create',
50
+ 'post-/crm/v3/objects/contacts/batch/archive_archive',
51
+ 'post-/crm/v3/objects/contacts/batch/create_create',
52
+ 'post-/crm/v3/objects/contacts/batch/read_read',
53
+ 'post-/crm/v3/objects/contacts/batch/update_update',
54
+ 'post-/crm/v3/objects/contacts/batch/upsert_upsert',
55
+ 'post-/crm/v3/objects/contacts/merge_merge',
56
+ 'post-/crm/v3/objects/contacts/search_doSearch',
57
+ 'post-/crm/v3/objects/tickets_create',
58
+ 'post-/crm/v3/objects/tickets/batch/archive_archive',
59
+ 'post-/crm/v3/objects/tickets/batch/create_create',
60
+ 'post-/crm/v3/objects/tickets/batch/read_read',
61
+ 'post-/crm/v3/objects/tickets/batch/update_update',
62
+ 'post-/crm/v3/objects/tickets/batch/upsert_upsert',
63
+ 'post-/crm/v3/objects/tickets/merge_merge',
64
+ 'post-/crm/v3/objects/tickets/search_doSearch',
65
+ // /crm/v3/owners
66
+ 'get-/crm/v3/owners/{ownerId}_getById',
67
+ 'get-/crm/v3/owners_/crm/v3/owners',
68
+ // /crm/v3/pipelines
69
+ 'delete-/crm/v3/pipelines/{objectType}/{pipelineId}_archive',
70
+ 'delete-/crm/v3/pipelines/{objectType}/{pipelineId}/stages/{stageId}_archive',
71
+ 'get-/crm/v3/pipelines/{objectType}_getAll',
72
+ 'get-/crm/v3/pipelines/{objectType}/{pipelineId}_getById',
73
+ 'get-/crm/v3/pipelines/{objectType}/{pipelineId}/stages_getAll',
74
+ 'get-/crm/v3/pipelines/{objectType}/{pipelineId}/stages/{stageId}_getById',
75
+ 'patch-/crm/v3/pipelines/{objectType}/{pipelineId}_update',
76
+ 'patch-/crm/v3/pipelines/{objectType}/{pipelineId}/stages/{stageId}_update',
77
+ 'post-/crm/v3/pipelines/{objectType}_create',
78
+ 'post-/crm/v3/pipelines/{objectType}/{pipelineId}/stages_create',
79
+ 'put-/crm/v3/pipelines/{objectType}/{pipelineId}_replace',
80
+ 'put-/crm/v3/pipelines/{objectType}/{pipelineId}/stages/{stageId}_replace',
81
+ // /crm/v3/properties
82
+ 'delete-/crm/v3/properties/{objectType}/{propertyName}_archive',
83
+ 'delete-/crm/v3/properties/{objectType}/groups/{groupName}_archive',
84
+ 'get-/crm/v3/properties/{objectType}_getAll',
85
+ 'get-/crm/v3/properties/{objectType}/{propertyName}_getByName',
86
+ 'get-/crm/v3/properties/{objectType}/groups_getAll',
87
+ 'get-/crm/v3/properties/{objectType}/groups/{groupName}_getByName',
88
+ 'patch-/crm/v3/properties/{objectType}/{propertyName}_update',
89
+ 'patch-/crm/v3/properties/{objectType}/groups/{groupName}_update',
90
+ 'post-/crm/v3/properties/{objectType}_create',
91
+ 'post-/crm/v3/properties/{objectType}/batch/create_create',
92
+ 'post-/crm/v3/properties/{objectType}/groups_create',
93
+ // /crm/v4/associations
94
+ 'post-/crm/v4/associations/{fromObjectType}/{toObjectType}/batch/archive_archive',
95
+ 'post-/crm/v4/associations/{fromObjectType}/{toObjectType}/batch/create_create',
96
+ 'post-/crm/v4/associations/{fromObjectType}/{toObjectType}/batch/read_getPage',
97
+ // /crm/v4/objects
98
+ 'delete-/crm/v4/objects/{objectType}/{objectId}/associations/{toObjectType}/{toObjectId}_archive',
99
+ 'get-/crm/v4/objects/{objectType}/{objectId}/associations/{toObjectType}_getPage',
100
+ 'put-/crm/v4/objects/{fromObjectType}/{fromObjectId}/associations/default/{toObjectType}/{toObjectId}_createDefault',
101
+ 'put-/crm/v4/objects/{objectType}/{objectId}/associations/{toObjectType}/{toObjectId}_create',
102
+ ] as const;
103
+
104
+ /** The operations served by the OAuth install's token endpoints. */
105
+ export const OAUTH_HANDLED = [
106
+ 'get-/oauth/v1/access-tokens/{token}_get',
107
+ 'post-/oauth/v1/token_create',
108
+ ] as const;
109
+
110
+ /** A handler per operation above: the CRM ones answer through `answer` (the pack's request handler as a fetch), the
111
+ * OAuth ones through `oauth`. */
112
+ export function hubspotHandlers(answer: (request: Request) => Promise<Response>, oauth: (request: Request) => Promise<Response>): Record<string, DerivedHandler> {
113
+ const crm: DerivedHandler = ({ request }: DerivedCall) => answer(request);
114
+ const token: DerivedHandler = ({ request }: DerivedCall) => oauth(request);
115
+ return { ...Object.fromEntries(CRM_HANDLED.map((id) => [id, crm])), ...Object.fromEntries(OAUTH_HANDLED.map((id) => [id, token])) };
116
+ }
@@ -0,0 +1,80 @@
1
+ // HUBSPOT'S WEBHOOK EVENTS — what HubSpot sends an installed app when a record changes in the account it is installed
2
+ // in (docs/contributing/architecture.md, "Events and webhooks"). An app declares its subscriptions in its project's
3
+ // webhooks component: a `targetUrl` and, in `crmObjects`, the `object.*` events it wants by `subscriptionType`,
4
+ // `objectType` and, for a property change, `propertyName`
5
+ // (https://developers.hubspot.com/docs/apps/developer-platform/add-features/configure-webhooks). Every write the request
6
+ // handler stores (hubspot-twin.ts, whoever made it: an app's API call, a person on a record's page, a form's submission)
7
+ // is announced here, and each live install in the account whose app subscribes to it is sent a POST to its target URL:
8
+ // a JSON array of events, each with `objectId`, `eventId`, `subscriptionId`, `portalId`, `appId`, `occurredAt`,
9
+ // `attemptNumber`, `changeSource`, `subscriptionType`, `objectTypeId`, `sourceId`, and for a property change
10
+ // `propertyName` and `propertyValue` (the generic payload's fields,
11
+ // https://developers.hubspot.com/docs/apps/legacy-apps/public-apps/create-generic-webhook-subscriptions).
12
+ //
13
+ // Signed as HubSpot's request-validation page says: `X-HubSpot-Signature-v3`, the base64 HMAC SHA-256 of the method,
14
+ // the URI, the body and `X-HubSpot-Request-Timestamp` with the app's client secret, and "for backwards compatibility"
15
+ // the older signature, `X-HubSpot-Signature` with `X-HubSpot-Signature-Version: v1`, the SHA-256 of "Client secret +
16
+ // request body" (https://developers.hubspot.com/docs/apps/developer-platform/build-apps/authentication/request-validation).
17
+ //
18
+ // The app's server is outside HubSpot, so what it received is read at a door, `GET /_twin/deliveries?to=<target URL>`,
19
+ // as slack's deliveries are; each delivery is also POSTed to the target URL where the World lets it out.
20
+ //
21
+ // Where the documentation stops and the twin decides: one event per request (HubSpot may batch up to a hundred); the
22
+ // event's `eventId` counts the account's events; `subscriptionId` is the subscription's index in the app, from the app's
23
+ // id; `changeSource` is `CRM_UI` for a person on a page, `FORM` for a form's submission, `INTEGRATION` for an app's API
24
+ // call and `API` otherwise, and `sourceId` is `userId:<id>` or `<appId>`; the v1 signature is sent on every event, which
25
+ // the page does not promise for a developer-platform app's `object.*` event.
26
+ import { createHash, createHmac } from 'node:crypto';
27
+ import { worldEgressRefusal } from '@volter/world-core/network-policy';
28
+ import { appById, installsIn, keep, stored, type Row } from './accounts.ts';
29
+ import { currentPortal } from './portal.ts';
30
+
31
+ const OBJECT_TYPE_ID: Record<string, string> = { contacts: '0-1', companies: '0-2', deals: '0-3', tickets: '0-5' };
32
+ const SUBSCRIPTION_OBJECT: Record<string, string> = { contacts: 'contact', companies: 'company', deals: 'deal', tickets: 'ticket' };
33
+
34
+ export type WriteEvent = { objectType: string; objectId: string; kind: 'creation' | 'propertyChange'; propertyName?: string; propertyValue?: string | null };
35
+
36
+ /** Announce a stored write to every app installed in the request's account that subscribes to it. */
37
+ export async function announceWrite(e: WriteEvent, root: string | undefined, at: string): Promise<void> {
38
+ const { hub, source, sourceId } = currentPortal();
39
+ for (const install of installsIn(hub, root)) {
40
+ const app = appById(Number(install.appId), root);
41
+ const hooks = app?.webhooks as { targetUrl?: string; subscriptions?: Row[] } | undefined;
42
+ if (!app || !hooks?.targetUrl) continue;
43
+ const subscription = (hooks.subscriptions ?? []).find((s) => s.active !== false
44
+ && s.subscriptionType === `object.${e.kind}` && s.objectType === SUBSCRIPTION_OBJECT[e.objectType]
45
+ && (e.kind !== 'propertyChange' || s.propertyName === e.propertyName));
46
+ if (!subscription) continue;
47
+ const eventId = stored('_webhook_delivery', root).filter((d) => d.portalId === hub).length + 1;
48
+ const event: Row = {
49
+ objectId: Number(e.objectId), eventId, subscriptionId: Number(subscription.id), portalId: hub, appId: app.appId,
50
+ occurredAt: Date.parse(at), attemptNumber: 0, changeSource: source, subscriptionType: `object.${e.kind}`,
51
+ objectTypeId: OBJECT_TYPE_ID[e.objectType], ...(sourceId ? { sourceId } : {}),
52
+ ...(e.kind === 'propertyChange' ? { propertyName: e.propertyName, propertyValue: e.propertyValue ?? '' } : {}),
53
+ };
54
+ await deliver(String(hooks.targetUrl), String(app.client_secret), [event], hub, root, at);
55
+ }
56
+ }
57
+
58
+ async function deliver(to: string, secret: string, events: Row[], hub: number, root: string | undefined, at: string): Promise<void> {
59
+ const body = JSON.stringify(events);
60
+ const timestamp = String(Date.parse(at));
61
+ const headers: Record<string, string> = {
62
+ 'content-type': 'application/json',
63
+ 'x-hubspot-signature': createHash('sha256').update(secret + body).digest('hex'),
64
+ 'x-hubspot-signature-version': 'v1',
65
+ 'x-hubspot-signature-v3': createHmac('sha256', secret).update(`POST${to}${body}${timestamp}`).digest('base64'),
66
+ 'x-hubspot-request-timestamp': timestamp,
67
+ };
68
+ const n = stored('_webhook_delivery', root).length + 1;
69
+ await keep('_webhook_delivery', `delivery:${n}`, { n, to, portalId: hub, body, headers, delivered_at: at }, root, at);
70
+ if (worldEgressRefusal(to) === null) await fetch(to, { method: 'POST', headers, body }).then((r) => r.text()).catch(() => undefined);
71
+ }
72
+
73
+ /** GET /_twin/deliveries?to=<url>: what an app's server received from HubSpot, oldest first — each request's headers,
74
+ * its body as sent, and the events in it. */
75
+ export function deliveriesDoor(request: Request, root?: string): Response {
76
+ const to = new URL(request.url).searchParams.get('to') ?? '';
77
+ const deliveries = stored('_webhook_delivery', root).filter((d) => d.to === to).sort((a, b) => Number(a.n) - Number(b.n))
78
+ .map((d) => ({ n: d.n, delivered_at: d.delivered_at, headers: d.headers, body: d.body, events: JSON.parse(String(d.body)) as unknown }));
79
+ return Response.json({ to, deliveries });
80
+ }