@kosha-ai/integration-zendesk 0.4.2 → 0.5.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.
package/README.md CHANGED
@@ -26,15 +26,14 @@ Zendesk is per-tenant, so each organization supplies its own account
26
26
  **subdomain** when it creates a configuration in the admin. It is the label
27
27
  only: `acme` for `https://acme.zendesk.com`.
28
28
 
29
- Every URL is derived from it, and the subdomain is recorded on the connection so
30
- the proxy routes later calls to `https://{subdomain}.zendesk.com/api/v2`.
31
-
32
- > **Connecting is not wired up yet.** A strategy is handed only the OAuth client
33
- > context (`clientId`, `clientSecret`, `redirectUri`, `scopes`), so a package
34
- > cannot read its own configuration column. Zendesk is the first provider that
35
- > needs to, and the mechanism is being decided separately. Until it lands, the
36
- > authorize, token and identity steps fail with a clear error rather than
37
- > guessing at a host.
29
+ Every URL is derived from it: the authorize redirect, the token exchange, the
30
+ refresh, the identity call, and the proxy's base URL of
31
+ `https://{subdomain}.zendesk.com/api/v2`.
32
+
33
+ It is read from the configuration rather than the connection, because Zendesk
34
+ needs the host before anyone logs in. The login page itself lives on the
35
+ tenant, so there is nothing to discover from a token the way Atlassian
36
+ discovers its `cloudId`.
38
37
 
39
38
  ## Scopes
40
39
 
@@ -1 +1 @@
1
- {"version":3,"file":"integration-zendesk.d.ts","sourceRoot":"","sources":["../../src/lib/integration-zendesk.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAOlE,eAAO,MAAM,OAAO,GAAI,WAAW,MAAM,WACL,CAAC;AAqGrC,wBAAgB,OAAO,IAAI,gBAAgB,CA4E1C;AAED,eAAe,OAAO,CAAC"}
1
+ {"version":3,"file":"integration-zendesk.d.ts","sourceRoot":"","sources":["../../src/lib/integration-zendesk.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAEV,gBAAgB,EACjB,MAAM,2BAA2B,CAAC;AAcnC,eAAO,MAAM,OAAO,GAAI,WAAW,MAAM,WACL,CAAC;AA2JrC,wBAAgB,OAAO,IAAI,gBAAgB,CAiG1C;AAED,eAAe,OAAO,CAAC"}
@@ -1,7 +1,14 @@
1
1
  import { defineIntegration, oauth2, packageDirs, } from '@kosha-ai/integration-sdk';
2
2
  const { docsPath, migrationsPath } = packageDirs(import.meta.url);
3
- /** A bare DNS label: `acme`, never `acme.zendesk.com`, a URL, or a path. */
4
- const SUBDOMAIN_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
3
+ /**
4
+ * A bare DNS label: `acme`, never `acme.zendesk.com`, a URL, or a path.
5
+ *
6
+ * Declared unanchored so the same source serves both the `configFields`
7
+ * pattern, which core anchors and the browser checks, and the runtime test
8
+ * below. Two spellings of this rule would be one spelling too many.
9
+ */
10
+ const SUBDOMAIN_SOURCE = '[a-z0-9](?:[a-z0-9\\-]{0,61}[a-z0-9])?';
11
+ const SUBDOMAIN_PATTERN = new RegExp(`^(?:${SUBDOMAIN_SOURCE})$`, 'v');
5
12
  export const hostFor = (subdomain) => `https://${subdomain}.zendesk.com`;
6
13
  /**
7
14
  * Zendesk's full OAuth scope catalogue: the broad tiers plus every
@@ -82,43 +89,80 @@ const SCOPES_AVAILABLE = [
82
89
  */
83
90
  const SCOPES_REQUESTED = ['users:read', 'tickets:read'];
84
91
  /**
85
- * Zendesk needs its configuration's `subdomain` column before it can address
86
- * anything, and a strategy is currently handed only `clientId`,
87
- * `clientSecret`, `redirectUri` and `scopes` (`clientContextFor` in
88
- * `connect.service.ts`). A package therefore has no way to read its own
89
- * configuration column yet.
92
+ * The subdomain this configuration addresses, from the package's own
93
+ * `zendesk_configuration.subdomain` column.
94
+ *
95
+ * The pattern is the security boundary, not a nicety. The value is
96
+ * operator-entered and goes straight into a hostname, so restricting it to a
97
+ * bare DNS label is what keeps a configuration pointing at
98
+ * `*.zendesk.com` and nowhere else. A `.`, `/` or `@` would otherwise be
99
+ * enough to send an authorization code or a token exchange to another host.
100
+ *
101
+ * A dedicated DNS check (`assertAllowedUrl`) is deliberately not used here:
102
+ * the host is always Zendesk's by construction, and `buildAuthorizationUrl`
103
+ * is synchronous.
104
+ */
105
+ function subdomainFrom(fields) {
106
+ const subdomain = fields?.['subdomain'];
107
+ if (typeof subdomain !== 'string' || subdomain.trim() === '') {
108
+ // The column is nullable, so a configuration created before the field was
109
+ // declared reads back NULL. Fail here rather than build
110
+ // "https://undefined.zendesk.com".
111
+ throw new Error('This Zendesk configuration has no subdomain. Set it on the ' +
112
+ 'configuration before connecting.');
113
+ }
114
+ if (!SUBDOMAIN_PATTERN.test(subdomain)) {
115
+ throw new Error(`"${subdomain}" is not a valid Zendesk subdomain. Use the label on its ` +
116
+ 'own, e.g. "acme" for acme.zendesk.com.');
117
+ }
118
+ return subdomain;
119
+ }
120
+ /**
121
+ * Everything about Zendesk's OAuth that does not depend on the host.
122
+ *
123
+ * Zendesk's token endpoint takes JSON, not a form body, and a
124
+ * space-separated `scope` string. Refresh hits the same endpoint with the
125
+ * standard parameters, so oauth2()'s default refresh already fits.
90
126
  *
91
- * Zendesk is the first provider to need this, and the mechanism is being
92
- * decided separately rather than guessed at here. Until it lands, connecting
93
- * fails loudly instead of inventing a host.
127
+ * There is no `revokeUrl`: Zendesk revokes by token *id* through
128
+ * `DELETE /api/v2/oauth/tokens/{id}`, an admin call rather than the usual
129
+ * "post the token back" endpoint. See docs/setup.md.
130
+ */
131
+ const COMMON = {
132
+ tokenRequest: 'json',
133
+ scopeSeparator: ' ',
134
+ scopesAvailable: SCOPES_AVAILABLE,
135
+ scopesRequested: SCOPES_REQUESTED,
136
+ };
137
+ /**
138
+ * Zendesk is per-tenant: authorize and token both live on the account's own
139
+ * host, so neither endpoint is knowable until a configuration is in hand.
140
+ * `oauth2()` takes static URLs, so rather than teach the SDK to interpolate,
141
+ * the strategy is rebuilt per call against the resolved host. Everything
142
+ * else about the exchange is standard, so the rest is still `oauth2()`.
94
143
  */
95
- function subdomainNotReadable() {
96
- throw new Error('Zendesk cannot read the subdomain from its configuration yet. ' +
97
- 'A strategy receives only the OAuth client context, so the per-tenant ' +
98
- 'host is unavailable until that is extended.');
144
+ function strategyFor(fields) {
145
+ const host = hostFor(subdomainFrom(fields));
146
+ return oauth2({
147
+ ...COMMON,
148
+ authorizationUrl: `${host}/oauth/authorizations/new`,
149
+ tokenUrl: `${host}/oauth/tokens`,
150
+ });
99
151
  }
100
152
  export function zendesk() {
101
- // The declared endpoints are templates: the catalogue shows the shape, and
102
- // each call will rebuild them from the configuration's subdomain once a
103
- // package can read it.
153
+ // The declared endpoints stay templates: nothing reads them, and a real
154
+ // host here would be a lie about one tenant. Each call rebuilds them from
155
+ // the configuration's own subdomain.
104
156
  const auth = oauth2({
157
+ ...COMMON,
105
158
  authorizationUrl: 'https://{subdomain}.zendesk.com/oauth/authorizations/new',
106
159
  tokenUrl: 'https://{subdomain}.zendesk.com/oauth/tokens',
107
- // Zendesk's token endpoint takes JSON, not a form body, and a
108
- // space-separated `scope` string. Refresh hits the same endpoint with the
109
- // standard parameters, so oauth2()'s default refresh already fits.
110
- //
111
- // There is no `revokeUrl`: Zendesk revokes by token *id* through
112
- // `DELETE /api/v2/oauth/tokens/{id}`, an admin call rather than the usual
113
- // "post the token back" endpoint. See docs/setup.md.
114
- tokenRequest: 'json',
115
- scopeSeparator: ' ',
116
- scopesAvailable: SCOPES_AVAILABLE,
117
- scopesRequested: SCOPES_REQUESTED,
118
160
  });
119
- auth.buildAuthorizationUrl = () => subdomainNotReadable();
120
- auth.exchangeCode = () => subdomainNotReadable();
121
- auth.refresh = () => subdomainNotReadable();
161
+ auth.buildAuthorizationUrl = (args) => strategyFor(args.client.fields).buildAuthorizationUrl(args);
162
+ auth.exchangeCode = (args) => strategyFor(args.client.fields).exchangeCode(args);
163
+ // `refresh?` is optional for strategies that cannot refresh at all; one
164
+ // built by `oauth2()` always has it.
165
+ auth.refresh = (args) => strategyFor(args.client.fields).refresh(args);
122
166
  return defineIntegration({
123
167
  key: 'zendesk',
124
168
  name: 'Zendesk',
@@ -129,30 +173,26 @@ export function zendesk() {
129
173
  // The subdomain is known before anyone authorizes, so it is configuration
130
174
  // rather than connection metadata. Declaring it here is what makes the
131
175
  // admin ask for it and what lets core accept it as a `fields` key; the
132
- // matching column lives in this package's own migration. Until #88 lands
133
- // nothing reads or writes it, so it stays NULL and the auth steps below
134
- // still throw.
176
+ // matching column lives in this package's own migration.
135
177
  configFields: [
136
178
  {
137
179
  key: 'subdomain',
138
180
  label: 'Subdomain',
139
181
  type: 'string',
140
182
  required: true,
183
+ // Refused on save as well as on use, so a typo surfaces on the form
184
+ // rather than when the first person tries to connect.
185
+ pattern: SUBDOMAIN_SOURCE,
141
186
  help: 'The part before .zendesk.com, e.g. acme',
142
187
  },
143
188
  ],
144
189
  api: {
145
- // No static base: every account is a different host. The subdomain is
146
- // recorded on the connection when the account is linked, so the proxy
147
- // resolves from there. Rooted at /api/v2 so the proxy's path-escape
148
- // guard also keeps callers away from /oauth/*.
149
- resolveBaseUrl: ({ metadata }) => {
150
- const subdomain = metadata?.['subdomain'];
151
- return typeof subdomain === 'string' &&
152
- SUBDOMAIN_PATTERN.test(subdomain)
153
- ? `${hostFor(subdomain)}/api/v2`
154
- : undefined;
155
- },
190
+ // No static base: every account is a different host. Resolved from the
191
+ // configuration rather than the connection, because the subdomain is
192
+ // what an operator set up the OAuth client with, not something
193
+ // discovered from a token. Rooted at /api/v2 so the proxy's
194
+ // path-escape guard also keeps callers away from /oauth/*.
195
+ resolveBaseUrl: ({ fields }) => `${hostFor(subdomainFrom(fields))}/api/v2`,
156
196
  authHeaders: ({ accessToken }) => ({
157
197
  Authorization: `Bearer ${accessToken}`,
158
198
  Accept: 'application/json',
@@ -161,9 +201,32 @@ export function zendesk() {
161
201
  egress: [{ hosts: ['*.zendesk.com'] }],
162
202
  },
163
203
  identity: {
164
- // Also blocked: `GET /users/me.json` lives on the tenant host, so this
165
- // needs the same configuration column the auth steps do.
166
- fetchAccount: () => subdomainNotReadable(),
204
+ // `GET /users/me.json` lives on the tenant host too, so the URL is
205
+ // built from the same column rather than going through `http`, which is
206
+ // bound to a static `api.baseUrl` this provider does not have.
207
+ async fetchAccount({ accessToken, fields }) {
208
+ const subdomain = subdomainFrom(fields);
209
+ const response = await fetch(`${hostFor(subdomain)}/api/v2/users/me.json`, {
210
+ headers: {
211
+ Authorization: `Bearer ${accessToken}`,
212
+ Accept: 'application/json',
213
+ },
214
+ });
215
+ if (!response.ok) {
216
+ throw new Error(`Failed to fetch the Zendesk profile: ${response.status}`);
217
+ }
218
+ const { user } = (await response.json());
219
+ if (user?.id === undefined) {
220
+ throw new Error('Zendesk profile contained no user id');
221
+ }
222
+ return {
223
+ // Namespaced by subdomain: a Zendesk user id is unique within a
224
+ // tenant, not across them, so the bare number would be ambiguous
225
+ // the moment a second tenant connects.
226
+ externalAccountId: `${subdomain}:${user.id}`,
227
+ label: user.email ?? user.name ?? String(user.id),
228
+ };
229
+ },
167
230
  },
168
231
  });
169
232
  }
package/docs/setup.md CHANGED
@@ -130,15 +130,15 @@ any Admin Center page:
130
130
 
131
131
  ![Where to find your Zendesk subdomain](./images/zendesk-subdomain.png)
132
132
 
133
- - It must be a **bare DNS label**. Not `acme.zendesk.com`, not a URL, and
133
+ - It must be a **lowercase bare DNS label**. Not `ACME`, not `acme.zendesk.com`, not a URL, and
134
134
  nothing containing `/`, `@`, a space, or a scheme.
135
135
  - Kosha validates it on every use and refuses anything else. The value is
136
136
  interpolated into the host Kosha calls, so an unchecked subdomain would let a
137
137
  configuration redirect Kosha's server-side requests (SSRF).
138
- - It is recorded on the connection when the account is linked, and the proxy
139
- routes to `https://{subdomain}.zendesk.com/api/v2` from there. Rooting at
140
- `/api/v2` means a caller cannot reach `/oauth/*` or anything else outside the
141
- REST API.
138
+ - Every endpoint is built from it, including the authorize and token URLs, so
139
+ it must be set before anyone can connect. The proxy routes to
140
+ `https://{subdomain}.zendesk.com/api/v2`; rooting at `/api/v2` means a
141
+ caller cannot reach `/oauth/*` or anything else outside the REST API.
142
142
  - Each configuration carries its own subdomain, so one Kosha deployment can
143
143
  serve several Zendesk accounts.
144
144
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kosha-ai/integration-zendesk",
3
- "version": "0.4.2",
3
+ "version": "0.5.1",
4
4
  "description": "Zendesk integration for Kosha",
5
5
  "keywords": [
6
6
  "kosha",
@@ -48,9 +48,9 @@
48
48
  "key": "zendesk"
49
49
  },
50
50
  "peerDependencies": {
51
- "@kosha-ai/integration-sdk": "0.4.2"
51
+ "@kosha-ai/integration-sdk": "0.5.1"
52
52
  },
53
53
  "devDependencies": {
54
- "@kosha-ai/integration-sdk": "0.4.2"
54
+ "@kosha-ai/integration-sdk": "0.5.1"
55
55
  }
56
56
  }