@theholocron/holocron-plugin-sentry 5.0.0-alpha.222 → 5.0.0-alpha.224

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,7 +1,17 @@
1
- import { AuthError, Errors, ResolveTokenInput, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess } from "@theholocron/cli";
1
+ import { AuthError, EnsureRelayInput, EnsureRelayResult, Errors, ResolveTokenInput, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess } from "@theholocron/cli";
2
2
  import { SentryClient, SentryClientOptions, createSentryClient } from "@theholocron/sentry-client";
3
3
  //#region src/auth.d.ts
4
4
  declare const resolveToken: (input?: ResolveTokenInput) => string;
5
+ /**
6
+ * The token for the Comlink relay: an integration, its client secret and an alert rule need more than the general token
7
+ * (`alerts:write`, `org:write`, `event:read`), so it has its own.
8
+ */
9
+ declare const resolveComlinkToken: (input?: ResolveTokenInput) => string;
10
+ /**
11
+ * The token for the relay: the Comlink one when there is one, else the general Sentry token as the last resort. The
12
+ * fallback only helps if the general token happens to carry the scopes; otherwise Sentry's answer names what is missing.
13
+ */
14
+ declare function resolveRelayToken(input?: ResolveTokenInput): string;
5
15
  //#endregion
6
16
  //#region src/capabilities/errors.d.ts
7
17
  interface SentryErrorsOptions {
@@ -13,9 +23,14 @@ interface SentryErrorsOptions {
13
23
  declare class SentryErrors implements Errors {
14
24
  private readonly client;
15
25
  private readonly opts;
26
+ /** The client for the relay, made with the Comlink token (see `resolveRelayToken`). */
27
+ private readonly relayClient;
16
28
  readonly key: "errors";
17
29
  readonly providerName = "sentry";
18
- constructor(client: () => SentryClient, opts: SentryErrorsOptions);
30
+ constructor(client: () => SentryClient, opts: SentryErrorsOptions,
31
+ /** The client for the relay, made with the Comlink token (see `resolveRelayToken`). */
32
+ relayClient?: () => SentryClient);
33
+ ensureRelay(input: EnsureRelayInput): Promise<EnsureRelayResult>;
19
34
  describe(): Promise<{
20
35
  provider: string;
21
36
  envKeys: string[];
@@ -60,6 +75,8 @@ interface SentryPluginOptions extends ResolveTokenInput, SentryErrorsOptions {
60
75
  interface PluginContext {
61
76
  options: SentryPluginOptions;
62
77
  client: () => SentryClient;
78
+ /** The client for the Comlink relay: its own token (`sentry.comlink`), the general one only as a last resort. */
79
+ relayClient: () => SentryClient;
63
80
  }
64
81
  declare function createContext(options: SentryPluginOptions): PluginContext;
65
82
  declare function errors(ctx: PluginContext): Errors;
@@ -71,4 +88,4 @@ declare function createPlugin(options: SentryPluginOptions): {
71
88
  };
72
89
  declare const AUTH_HINT: string;
73
90
  //#endregion
74
- export { AUTH_HINT, AuthError, PluginContext, type ResolveTokenInput, type SentryClient, type SentryClientOptions, SentryErrors, type SentryErrorsOptions, SentryPluginOptions, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createContext, createPlugin, createSentryClient, errors, resolveToken, verifyToken };
91
+ export { AUTH_HINT, AuthError, PluginContext, type ResolveTokenInput, type SentryClient, type SentryClientOptions, SentryErrors, type SentryErrorsOptions, SentryPluginOptions, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createContext, createPlugin, createSentryClient, errors, resolveComlinkToken, resolveRelayToken, resolveToken, verifyToken };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { AuthError, ProviderApiError, createResolveToken } from "@theholocron/cli";
1
+ import { AuthError, ProviderApiError, createFeatureResolver, createResolveToken } from "@theholocron/cli";
2
2
  import { createSentryClient } from "@theholocron/sentry-client";
3
3
  import { errorMessage } from "@theholocron/misc-utils";
4
4
  //#region src/auth.ts
@@ -8,16 +8,245 @@ const resolveToken = createResolveToken({
8
8
  keyringService: "sentry",
9
9
  errorMessage: "no Sentry auth token found. Pass --token <TOKEN>, set HOLOCRON_SENTRY_TOKEN / SENTRY_AUTH_TOKEN, or run: holocron auth set sentry <TOKEN>"
10
10
  });
11
+ /**
12
+ * The token for the Comlink relay: an integration, its client secret and an alert rule need more than the general token
13
+ * (`alerts:write`, `org:write`, `event:read`), so it has its own.
14
+ */
15
+ const resolveComlinkToken = createFeatureResolver({
16
+ envName: "HOLOCRON_SENTRY_COMLINK_TOKEN",
17
+ keyringKey: "sentry.comlink",
18
+ vendor: "Sentry"
19
+ });
20
+ /**
21
+ * The token for the relay: the Comlink one when there is one, else the general Sentry token as the last resort. The
22
+ * fallback only helps if the general token happens to carry the scopes; otherwise Sentry's answer names what is missing.
23
+ */
24
+ function resolveRelayToken(input = {}) {
25
+ try {
26
+ return resolveComlinkToken(input);
27
+ } catch (err) {
28
+ if (!(err instanceof AuthError)) throw err;
29
+ return resolveToken(input);
30
+ }
31
+ }
32
+ //#endregion
33
+ //#region src/capabilities/relay.ts
34
+ /** What the integration needs to read: the alert's event. It is also why reading its secret needs the same scope. */
35
+ const INTEGRATION_SCOPES = ["event:read"];
36
+ const DEFAULT_FREQUENCY = 5;
37
+ /**
38
+ * The alert action that sends through an integration, in the shape Sentry's own page writes when "Send a notification via
39
+ * an integration" is picked: a `webhook` action named by the integration's slug. (A `sentry_app` action with the numeric
40
+ * id is accepted too, but the page shows it as an unknown integration.)
41
+ */
42
+ const integrationAction = (slug) => ({
43
+ type: "webhook",
44
+ config: {
45
+ targetType: null,
46
+ targetDisplay: null,
47
+ targetIdentifier: slug
48
+ },
49
+ data: {}
50
+ });
51
+ const sendsThrough = (action, slug) => action.type === "webhook" && action.config["targetIdentifier"] === slug;
52
+ /** The `sentry_app` form an earlier version wrote for this integration, which the page cannot name. */
53
+ const isLegacyAction = (action, appId) => action.type === "sentry_app" && String(action.config["targetIdentifier"]) === String(appId);
54
+ /** A workflow as Sentry returned it, as the body to send back (the nested ids are not part of an update). */
55
+ function toInput(wf) {
56
+ return {
57
+ name: wf.name,
58
+ enabled: wf.enabled,
59
+ environment: wf.environment,
60
+ config: wf.config,
61
+ detectorIds: wf.detectorIds,
62
+ triggers: {
63
+ logicType: wf.triggers.logicType,
64
+ conditions: wf.triggers.conditions.map((c) => ({
65
+ type: c.type,
66
+ comparison: c.comparison,
67
+ conditionResult: c.conditionResult
68
+ }))
69
+ },
70
+ actionFilters: wf.actionFilters.map((f) => ({
71
+ logicType: f.logicType,
72
+ conditions: f.conditions.map((c) => ({
73
+ type: c.type,
74
+ comparison: c.comparison,
75
+ conditionResult: c.conditionResult
76
+ })),
77
+ actions: f.actions.map((a) => ({
78
+ type: a.type,
79
+ config: a.config,
80
+ data: a.data
81
+ }))
82
+ }))
83
+ };
84
+ }
85
+ /** Sentry's own "high priority issues" rule, which is the default for a new alert. */
86
+ function newWorkflow(name, frequency, detectorIds, slug) {
87
+ return {
88
+ name,
89
+ enabled: true,
90
+ environment: null,
91
+ config: { frequency },
92
+ detectorIds,
93
+ triggers: {
94
+ logicType: "any-short",
95
+ conditions: [{
96
+ type: "new_high_priority_issue",
97
+ comparison: true,
98
+ conditionResult: true
99
+ }, {
100
+ type: "existing_high_priority_issue",
101
+ comparison: true,
102
+ conditionResult: true
103
+ }]
104
+ },
105
+ actionFilters: [{
106
+ logicType: "all",
107
+ conditions: [],
108
+ actions: [integrationAction(slug)]
109
+ }]
110
+ };
111
+ }
112
+ /** The integration: found by name, made if missing, and its webhook and alert action brought in line. */
113
+ async function ensureIntegration(client, org, input) {
114
+ const existing = (await client.sentryApps.list(org)).find((a) => a.name === input.name);
115
+ if (!existing) return {
116
+ app: await client.sentryApps.create(org, {
117
+ name: input.name,
118
+ scopes: INTEGRATION_SCOPES,
119
+ webhookUrl: input.webhookUrl,
120
+ isAlertable: true
121
+ }),
122
+ created: true,
123
+ updated: []
124
+ };
125
+ const updated = [];
126
+ if (existing.webhookUrl !== input.webhookUrl) updated.push("webhook URL");
127
+ if (!existing.isAlertable) updated.push("alert action");
128
+ const scopes = [.../* @__PURE__ */ new Set([...existing.scopes, ...INTEGRATION_SCOPES])];
129
+ if (scopes.length !== existing.scopes.length) updated.push("scopes");
130
+ if (updated.length === 0) return {
131
+ app: existing,
132
+ created: false,
133
+ updated
134
+ };
135
+ return {
136
+ app: await client.sentryApps.update(existing.slug, {
137
+ name: existing.name,
138
+ scopes,
139
+ webhookUrl: input.webhookUrl,
140
+ isAlertable: true
141
+ }),
142
+ created: false,
143
+ updated
144
+ };
145
+ }
146
+ /** The issue stream detector of each project, so a wrong project fails before anything is changed. */
147
+ async function detectorsFor(client, org, slugs) {
148
+ const [projects, detectors] = await Promise.all([client.projects.list(org), client.workflows.detectors(org)]);
149
+ return slugs.map((slug) => {
150
+ const project = projects.find((p) => p.slug === slug);
151
+ if (!project) throw new Error(`Sentry project \`${slug}\` was not found in ${org}`);
152
+ const detector = detectors.find((d) => d.projectId === project.id && d.type === "issue_stream");
153
+ if (!detector) throw new Error(`Sentry project \`${slug}\` has no issue stream detector to attach an alert to`);
154
+ return detector.id;
155
+ });
156
+ }
157
+ /** The alert rule: one workflow for every project, found by name, made if missing, reconciled if not. */
158
+ async function ensureRule(client, org, input, install, detectorIds) {
159
+ const workflows = await client.workflows.list(org);
160
+ const frequency = input.rule.frequency ?? DEFAULT_FREQUENCY;
161
+ const existing = workflows.find((w) => w.name === input.rule.name);
162
+ if (!existing) {
163
+ await client.workflows.create(org, newWorkflow(input.rule.name, frequency, detectorIds, install.slug));
164
+ return {
165
+ created: true,
166
+ updated: []
167
+ };
168
+ }
169
+ const next = toInput(existing);
170
+ const updated = [];
171
+ if (!existing.enabled) {
172
+ next.enabled = true;
173
+ updated.push("enabled");
174
+ }
175
+ if (input.rule.frequency !== void 0 && existing.config.frequency !== input.rule.frequency) {
176
+ next.config = {
177
+ ...existing.config,
178
+ frequency: input.rule.frequency
179
+ };
180
+ updated.push("frequency");
181
+ }
182
+ const missing = detectorIds.filter((id) => !existing.detectorIds.includes(id));
183
+ if (missing.length > 0) {
184
+ next.detectorIds = [...existing.detectorIds, ...missing];
185
+ updated.push("projects");
186
+ }
187
+ const sends = existing.actionFilters.some((f) => f.actions.some((a) => sendsThrough(a, install.slug)));
188
+ const legacy = existing.actionFilters.some((f) => f.actions.some((a) => isLegacyAction(a, install.appId)));
189
+ if (legacy) for (const f of next.actionFilters) f.actions = f.actions.filter((a) => !isLegacyAction(a, install.appId));
190
+ if (!sends) {
191
+ const open = next.actionFilters.find((f) => f.conditions.length === 0);
192
+ if (open) open.actions.push(integrationAction(install.slug));
193
+ else next.actionFilters.push({
194
+ logicType: "all",
195
+ conditions: [],
196
+ actions: [integrationAction(install.slug)]
197
+ });
198
+ }
199
+ if (legacy || !sends) updated.push("action");
200
+ if (updated.length === 0) return {
201
+ created: false,
202
+ updated
203
+ };
204
+ await client.workflows.update(org, existing.id, next);
205
+ return {
206
+ created: false,
207
+ updated
208
+ };
209
+ }
210
+ /** The signing secret, if the token may see it: a new integration's answer omits it, so it is read again. */
211
+ async function secretOf(client, app) {
212
+ if (app.clientSecret) return app.clientSecret;
213
+ return (await client.sentryApps.get(app.slug)).clientSecret || void 0;
214
+ }
215
+ async function ensureSentryRelay(client, org, input) {
216
+ if (input.projects.length === 0) throw new Error("relay needs at least one Sentry project to alert on");
217
+ const detectorIds = await detectorsFor(client, org, input.projects);
218
+ const integration = await ensureIntegration(client, org, input);
219
+ const install = (await client.sentryApps.installations(org)).find((i) => i.app.slug === integration.app.slug);
220
+ if (!install) throw new Error(`the integration \`${integration.app.name}\` is not installed on ${org}`);
221
+ const rule = await ensureRule(client, org, input, {
222
+ slug: install.app.slug,
223
+ appId: install.app.sentryAppId
224
+ }, detectorIds);
225
+ const clientSecret = await secretOf(client, integration.app);
226
+ return {
227
+ integration: {
228
+ created: integration.created,
229
+ updated: integration.updated
230
+ },
231
+ rule,
232
+ ...clientSecret ? { clientSecret } : {}
233
+ };
234
+ }
11
235
  //#endregion
12
236
  //#region src/capabilities/errors.ts
13
237
  var SentryErrors = class {
14
238
  client;
15
239
  opts;
240
+ relayClient;
16
241
  key = "errors";
17
242
  providerName = "sentry";
18
- constructor(client, opts) {
243
+ constructor(client, opts, relayClient = client) {
19
244
  this.client = client;
20
245
  this.opts = opts;
246
+ this.relayClient = relayClient;
247
+ }
248
+ async ensureRelay(input) {
249
+ return ensureSentryRelay(this.relayClient(), this.requireOrg(), input);
21
250
  }
22
251
  async describe() {
23
252
  return {
@@ -94,12 +323,18 @@ async function verifyToken(token, opts = {}) {
94
323
  //#region src/index.ts
95
324
  function createContext(options) {
96
325
  let client;
326
+ let relayClient;
97
327
  return {
98
328
  options,
99
329
  client: () => client ??= createSentryClient({
100
330
  token: resolveToken(options),
101
331
  baseUrl: options.baseUrl,
102
332
  fetch: options.fetch
333
+ }),
334
+ relayClient: () => relayClient ??= createSentryClient({
335
+ token: resolveRelayToken(options),
336
+ baseUrl: options.baseUrl,
337
+ fetch: options.fetch
103
338
  })
104
339
  };
105
340
  }
@@ -107,7 +342,7 @@ function errors(ctx) {
107
342
  return new SentryErrors(ctx.client, {
108
343
  org: ctx.options.org,
109
344
  team: ctx.options.team
110
- });
345
+ }, ctx.relayClient);
111
346
  }
112
347
  function createPlugin(options) {
113
348
  const ctx = createContext(options);
@@ -118,4 +353,4 @@ function createPlugin(options) {
118
353
  }
119
354
  const AUTH_HINT = "generate an auth token at https://sentry.io/settings/account/api/auth-tokens/ with project:read, project:write, and org:read scopes, then run: holocron auth set sentry <TOKEN>";
120
355
  //#endregion
121
- export { AUTH_HINT, AuthError, SentryErrors, createContext, createPlugin, createSentryClient, errors, resolveToken, verifyToken };
356
+ export { AUTH_HINT, AuthError, SentryErrors, createContext, createPlugin, createSentryClient, errors, resolveComlinkToken, resolveRelayToken, resolveToken, verifyToken };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-sentry",
3
- "version": "5.0.0-alpha.222",
3
+ "version": "5.0.0-alpha.224",
4
4
  "description": "Holocron plugin for Sentry. Implements the errors capability against Sentry's management API — project provisioning and DSN retrieval.",
5
5
  "keywords": [
6
6
  "errors",
@@ -33,7 +33,7 @@
33
33
  "@theholocron/eslint-config": "^8.8.2",
34
34
  "@theholocron/http-client": "^1.43.1",
35
35
  "@theholocron/misc-utils": "^1.16.0",
36
- "@theholocron/sentry-client": "^1.43.1",
36
+ "@theholocron/sentry-client": "^1.54.0",
37
37
  "@theholocron/tsconfig": "^8.8.2",
38
38
  "@theholocron/tsdown-config": "^8.8.2",
39
39
  "@theholocron/vitest-config": "^8.8.2",
@@ -48,12 +48,12 @@
48
48
  "tsx": "4.23.15",
49
49
  "typescript": "^5.9.3",
50
50
  "vitest": "^4.1.11",
51
- "@theholocron/cli": "5.0.0-alpha.222"
51
+ "@theholocron/cli": "5.0.0-alpha.224"
52
52
  },
53
53
  "peerDependencies": {
54
54
  "@theholocron/misc-utils": "^1.16.0",
55
- "@theholocron/sentry-client": "^1.43.1",
56
- "@theholocron/cli": "5.0.0-alpha.222"
55
+ "@theholocron/sentry-client": "^1.54.0",
56
+ "@theholocron/cli": "5.0.0-alpha.224"
57
57
  },
58
58
  "peerDependenciesMeta": {
59
59
  "@theholocron/sentry-client": {}