@volter/twin-hubspot 0.1.36 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -193
- package/dist/generated/pack-facts.json +42 -0
- package/dist/journeys/coverage.json +60 -0
- package/dist/journeys/customer-life.json +7 -0
- package/dist/journeys/customer-life.outline.md +6 -0
- package/dist/journeys/decisions.json +623 -0
- package/dist/journeys/demand.json +171 -0
- package/dist/journeys/score.json +82 -0
- package/dist/journeys/unreachable.json +12 -0
- package/dist/journeys/vendor-examples.json +7 -0
- package/dist/spec/SOURCE.md +40 -0
- package/dist/spec/openapi/associations.json.gz +0 -0
- package/dist/spec/openapi/companies.json.gz +0 -0
- package/dist/spec/openapi/contacts.json.gz +0 -0
- package/dist/spec/openapi/deals.json.gz +0 -0
- package/dist/spec/openapi/meetings.json.gz +0 -0
- package/dist/spec/openapi/oauth.json.gz +0 -0
- package/dist/spec/openapi/owners.json.gz +0 -0
- package/dist/spec/openapi/pipelines.json.gz +0 -0
- package/dist/spec/openapi/properties.json.gz +0 -0
- package/dist/spec/openapi/tickets.json.gz +0 -0
- package/dist/spec/patches.json +235 -0
- package/dist/spec/sources.json +32 -0
- package/dist/src/cli.js +10 -22
- package/dist/src/fetch.d.ts +2 -0
- package/dist/src/fetch.js +13 -0
- package/dist/src/generated/surface.gen.json +1 -1
- package/dist/src/index.d.ts +5 -11
- package/dist/src/index.js +10 -94
- package/dist/src/manifest.js +32 -66
- package/dist/src/semantics/index.d.ts +2 -0
- package/dist/src/semantics/index.js +1 -0
- package/dist/src/semantics/states.d.ts +1 -0
- package/dist/src/semantics/states.js +2 -0
- package/dist/src/server.d.ts +7 -0
- package/dist/src/server.js +7 -0
- package/generated/pack-facts.json +42 -0
- package/journeys/coverage.json +60 -0
- package/journeys/customer-life.json +7 -0
- package/journeys/customer-life.outline.md +6 -0
- package/journeys/decisions.json +623 -0
- package/journeys/demand.json +171 -0
- package/journeys/score.json +82 -0
- package/journeys/unreachable.json +12 -0
- package/journeys/vendor-examples.json +7 -0
- package/package.json +10 -23
- package/spec/SOURCE.md +40 -0
- package/spec/openapi/associations.json.gz +0 -0
- package/spec/openapi/companies.json.gz +0 -0
- package/spec/openapi/contacts.json.gz +0 -0
- package/spec/openapi/deals.json.gz +0 -0
- package/spec/openapi/meetings.json.gz +0 -0
- package/spec/openapi/oauth.json.gz +0 -0
- package/spec/openapi/owners.json.gz +0 -0
- package/spec/openapi/pipelines.json.gz +0 -0
- package/spec/openapi/properties.json.gz +0 -0
- package/spec/openapi/tickets.json.gz +0 -0
- package/spec/patches.json +235 -0
- package/spec/sources.json +32 -0
- package/src/cli.ts +10 -19
- package/src/fetch.ts +14 -0
- package/src/generated/surface.gen.json +1 -1
- package/src/index.ts +12 -152
- package/src/manifest.ts +33 -92
- package/src/semantics/index.ts +6 -0
- package/src/semantics/states.ts +2 -0
- package/src/server.ts +8 -0
- package/client/hubspot-mirror.css +0 -43
- package/client/hubspot-mirror.tsx +0 -132
- package/dist/client/hubspot-mirror.bundle.js +0 -516
- package/dist/client/hubspot-mirror.css +0 -43
- package/dist/client/hubspot-mirror.d.ts +0 -15
- package/dist/client/hubspot-mirror.js +0 -59
- package/dist/client/hubspot-mirror.tsx +0 -132
- package/dist/src/accounts.d.ts +0 -30
- package/dist/src/accounts.js +0 -122
- package/dist/src/hubspot-areas.d.ts +0 -10
- package/dist/src/hubspot-areas.js +0 -114
- package/dist/src/hubspot-budget.d.ts +0 -58
- package/dist/src/hubspot-budget.js +0 -176
- package/dist/src/hubspot-capabilities.d.ts +0 -3
- package/dist/src/hubspot-capabilities.js +0 -1588
- package/dist/src/hubspot-conformance.d.ts +0 -16
- package/dist/src/hubspot-conformance.js +0 -523
- package/dist/src/hubspot-connector.d.ts +0 -125
- package/dist/src/hubspot-connector.js +0 -390
- package/dist/src/hubspot-deferred-capabilities.d.ts +0 -6
- package/dist/src/hubspot-deferred-capabilities.js +0 -64
- package/dist/src/hubspot-mirror-ui.d.ts +0 -62
- package/dist/src/hubspot-mirror-ui.js +0 -152
- package/dist/src/hubspot-oauth.d.ts +0 -8
- package/dist/src/hubspot-oauth.js +0 -291
- package/dist/src/hubspot-server.d.ts +0 -24
- package/dist/src/hubspot-server.js +0 -116
- package/dist/src/hubspot-twin.d.ts +0 -65
- package/dist/src/hubspot-twin.js +0 -1558
- package/dist/src/portal.d.ts +0 -20
- package/dist/src/portal.js +0 -30
- package/dist/src/screens/account.d.ts +0 -1
- package/dist/src/screens/account.js +0 -139
- package/dist/src/screens/crm.d.ts +0 -2
- package/dist/src/screens/crm.js +0 -153
- package/dist/src/screens/developer.d.ts +0 -4
- package/dist/src/screens/developer.js +0 -191
- package/dist/src/screens/forms.d.ts +0 -5
- package/dist/src/screens/forms.js +0 -126
- package/dist/src/screens/page.d.ts +0 -21
- package/dist/src/screens/page.js +0 -49
- package/dist/src/screens/session.d.ts +0 -1
- package/dist/src/screens/session.js +0 -32
- package/dist/src/semantics/crm.d.ts +0 -8
- package/dist/src/semantics/crm.js +0 -101
- package/dist/src/webhooks.d.ts +0 -12
- package/dist/src/webhooks.js +0 -79
- package/src/accounts.ts +0 -127
- package/src/hubspot-areas.ts +0 -155
- package/src/hubspot-budget.ts +0 -202
- package/src/hubspot-capabilities.ts +0 -1523
- package/src/hubspot-conformance.ts +0 -537
- package/src/hubspot-connector.ts +0 -419
- package/src/hubspot-deferred-capabilities.ts +0 -99
- package/src/hubspot-journey.uitest.ts +0 -104
- package/src/hubspot-mirror-ui.ts +0 -166
- package/src/hubspot-oauth.tsx +0 -296
- package/src/hubspot-server.ts +0 -115
- package/src/hubspot-twin.ts +0 -1534
- package/src/portal.ts +0 -40
- package/src/screens/account.tsx +0 -129
- package/src/screens/crm.tsx +0 -154
- package/src/screens/developer.tsx +0 -181
- package/src/screens/forms.tsx +0 -117
- package/src/screens/page.tsx +0 -55
- package/src/screens/session.tsx +0 -36
- package/src/semantics/crm.ts +0 -116
- package/src/webhooks.ts +0 -82
package/src/screens/forms.tsx
DELETED
|
@@ -1,117 +0,0 @@
|
|
|
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
|
-
}
|
package/src/screens/page.tsx
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
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)}`;
|
package/src/screens/session.tsx
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
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
|
-
}
|
package/src/semantics/crm.ts
DELETED
|
@@ -1,116 +0,0 @@
|
|
|
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
|
-
}
|
package/src/webhooks.ts
DELETED
|
@@ -1,82 +0,0 @@
|
|
|
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 { appDestination, appFetch } from '@volter/world-core/app-route';
|
|
28
|
-
import { worldEgressRefusal } from '@volter/world-core/network-policy';
|
|
29
|
-
import { appById, installsIn, keep, stored, type Row } from './accounts.ts';
|
|
30
|
-
import { currentPortal } from './portal.ts';
|
|
31
|
-
|
|
32
|
-
const OBJECT_TYPE_ID: Record<string, string> = { contacts: '0-1', companies: '0-2', deals: '0-3', tickets: '0-5' };
|
|
33
|
-
const SUBSCRIPTION_OBJECT: Record<string, string> = { contacts: 'contact', companies: 'company', deals: 'deal', tickets: 'ticket' };
|
|
34
|
-
|
|
35
|
-
export type WriteEvent = { objectType: string; objectId: string; kind: 'creation' | 'propertyChange'; propertyName?: string; propertyValue?: string | null };
|
|
36
|
-
|
|
37
|
-
/** Announce a stored write to every app installed in the request's account that subscribes to it. */
|
|
38
|
-
export async function announceWrite(e: WriteEvent, root: string | undefined, at: string): Promise<void> {
|
|
39
|
-
const { hub, source, sourceId } = currentPortal();
|
|
40
|
-
for (const install of installsIn(hub, root)) {
|
|
41
|
-
const app = appById(Number(install.appId), root);
|
|
42
|
-
const hooks = app?.webhooks as { targetUrl?: string; subscriptions?: Row[] } | undefined;
|
|
43
|
-
if (!app || !hooks?.targetUrl) continue;
|
|
44
|
-
const subscription = (hooks.subscriptions ?? []).find((s) => s.active !== false
|
|
45
|
-
&& s.subscriptionType === `object.${e.kind}` && s.objectType === SUBSCRIPTION_OBJECT[e.objectType]
|
|
46
|
-
&& (e.kind !== 'propertyChange' || s.propertyName === e.propertyName));
|
|
47
|
-
if (!subscription) continue;
|
|
48
|
-
const eventId = stored('_webhook_delivery', root).filter((d) => d.portalId === hub).length + 1;
|
|
49
|
-
const event: Row = {
|
|
50
|
-
objectId: Number(e.objectId), eventId, subscriptionId: Number(subscription.id), portalId: hub, appId: app.appId,
|
|
51
|
-
occurredAt: Date.parse(at), attemptNumber: 0, changeSource: source, subscriptionType: `object.${e.kind}`,
|
|
52
|
-
objectTypeId: OBJECT_TYPE_ID[e.objectType], ...(sourceId ? { sourceId } : {}),
|
|
53
|
-
...(e.kind === 'propertyChange' ? { propertyName: e.propertyName, propertyValue: e.propertyValue ?? '' } : {}),
|
|
54
|
-
};
|
|
55
|
-
await deliver(String(hooks.targetUrl), String(app.client_secret), [event], hub, root, at);
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
async function deliver(to: string, secret: string, events: Row[], hub: number, root: string | undefined, at: string): Promise<void> {
|
|
60
|
-
const body = JSON.stringify(events);
|
|
61
|
-
const timestamp = String(Date.parse(at));
|
|
62
|
-
const headers: Record<string, string> = {
|
|
63
|
-
'content-type': 'application/json',
|
|
64
|
-
'x-hubspot-signature': createHash('sha256').update(secret + body).digest('hex'),
|
|
65
|
-
'x-hubspot-signature-version': 'v1',
|
|
66
|
-
'x-hubspot-signature-v3': createHmac('sha256', secret).update(`POST${to}${body}${timestamp}`).digest('base64'),
|
|
67
|
-
'x-hubspot-request-timestamp': timestamp,
|
|
68
|
-
};
|
|
69
|
-
const n = stored('_webhook_delivery', root).length + 1;
|
|
70
|
-
await keep('_webhook_delivery', `delivery:${n}`, { n, to, portalId: hub, body, headers, delivered_at: at }, root, at);
|
|
71
|
-
// the application's own hostnames reach it inside the World; elsewhere, the World's egress rule decides
|
|
72
|
-
if (appDestination(to) || worldEgressRefusal(to) === null) await appFetch(to, { method: 'POST', headers, body }).then((r) => r.text()).catch(() => undefined);
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/** GET /_twin/deliveries?to=<url>: what an app's server received from HubSpot, oldest first — each request's headers,
|
|
76
|
-
* its body as sent, and the events in it. */
|
|
77
|
-
export function deliveriesDoor(request: Request, root?: string): Response {
|
|
78
|
-
const to = new URL(request.url).searchParams.get('to') ?? '';
|
|
79
|
-
const deliveries = stored('_webhook_delivery', root).filter((d) => d.to === to).sort((a, b) => Number(a.n) - Number(b.n))
|
|
80
|
-
.map((d) => ({ n: d.n, delivered_at: d.delivered_at, headers: d.headers, body: d.body, events: JSON.parse(String(d.body)) as unknown }));
|
|
81
|
-
return Response.json({ to, deliveries });
|
|
82
|
-
}
|