@theholocron/holocron-plugin-sentry 5.0.0-alpha.42 → 5.0.0-alpha.421

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
@@ -47,12 +47,15 @@ user-owned and org-owned tokens are accepted.
47
47
 
48
48
  | Method | What it does |
49
49
  | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
50
- | `describe` | Returns `{ provider: "sentry", envKeys: ["SENTRY_DSN", "NEXT_PUBLIC_SENTRY_DSN"] }` — the env vars the app reads at runtime. |
50
+ | `describe` | Returns `{ provider: "sentry", envKeys: ["SENTRY_DSN"], frameworkEnvKeys: { next: ["NEXT_PUBLIC_SENTRY_DSN"] } }` — the env vars the app reads at runtime. |
51
51
  | `whoami` | Fetches the org by slug to verify the token and confirm the org exists. |
52
52
  | `ensureProject` | Looks up the project by slug (derived from `name`); creates it under the configured team if absent. Returns the DSN and an `alreadyExists` flag. Idempotent. |
53
53
 
54
54
  A provider entry in `holocron.config` is only needed to enable `holocron
55
- setup` provisioning (`ensureProject` + pushing `SENTRY_DSN` /
56
- `NEXT_PUBLIC_SENTRY_DSN` to Secrets) and `holocron doctor` connectivity
55
+ setup` provisioning (`ensureProject` + pushing `SENTRY_DSN` to Secrets, and
56
+ `NEXT_PUBLIC_SENTRY_DSN` too when Next.js is detected: the root `package.json`
57
+ or any workspace package's lists `next`) and `holocron doctor` connectivity
57
58
  checks — not for runtime error reporting, which the CLI activates directly
58
- from `HOLOCRON_SENTRY_DSN` (fallback `SENTRY_DSN`).
59
+ from `HOLOCRON_SENTRY_DSN` (fallback `SENTRY_DSN`). A DSN is built to be embedded in
60
+ client code, so it is not a true secret.
61
+ Setup never removes `NEXT_PUBLIC_SENTRY_DSN`: a repo that drops Next.js deletes that secret by hand.
package/dist/index.d.mts CHANGED
@@ -1,28 +1,52 @@
1
- import { AuthError, Errors, ResolveTokenInput } from "@theholocron/cli";
1
+ import { AuthError, EnsureRelayInput, EnsureRelayResult, Errors, InspectRelayInput, PluginToken, RelayState, ResolveTokenInput, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess } from "@theholocron/cli";
2
2
  import { SentryClient, SentryClientOptions, createSentryClient } from "@theholocron/sentry-client";
3
- //#region src/auth.d.ts
4
- declare const resolveToken: (input?: ResolveTokenInput) => string;
5
- //#endregion
6
- //#region src/capabilities/errors.d.ts
3
+ /** Resolves the Sentry token from `--token`, `HOLOCRON_SENTRY_TOKEN`, `SENTRY_AUTH_TOKEN` or the keyring, and throws an `AuthError` when none is set. */
4
+ export declare const resolveToken: import("@theholocron/cli").TokenResolver;
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
+ export declare const resolveComlinkToken: import("@theholocron/cli").FeatureResolver;
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
+ export declare function resolveRelayToken(input?: ResolveTokenInput): string;
15
+ /** Every token this plugin takes, for `holocron doctor tokens`: the general one and the Comlink relay's own. */
16
+ export declare const tokens: PluginToken[];
17
+ /** Options for the Sentry `errors` capability. */
7
18
  interface SentryErrorsOptions {
8
19
  /** Sentry organization slug. Required for `whoami` and `ensureProject`. */
9
20
  org?: string;
10
21
  /** Default team slug for project creation. Defaults to org slug. */
11
22
  team?: string;
12
23
  }
13
- declare class SentryErrors implements Errors {
24
+ /** The `errors` capability for Sentry: finds or creates a project and reports its DSN, and manages the Comlink relay. */
25
+ export declare class SentryErrors implements Errors {
14
26
  private readonly client;
15
27
  private readonly opts;
28
+ /** The client for the relay, made with the Comlink token (see `resolveRelayToken`). */
29
+ private readonly relayClient;
30
+ /** The capability key, always `errors`. */
16
31
  readonly key: "errors";
32
+ /** The provider name, `sentry`. */
17
33
  readonly providerName = "sentry";
18
- constructor(client: () => SentryClient, opts: SentryErrorsOptions);
34
+ constructor(client: () => SentryClient, opts: SentryErrorsOptions,
35
+ /** The client for the relay, made with the Comlink token (see `resolveRelayToken`). */
36
+ relayClient?: () => SentryClient);
37
+ ensureRelay(input: EnsureRelayInput): Promise<EnsureRelayResult>;
38
+ inspectRelay(input: InspectRelayInput): Promise<RelayState>;
19
39
  describe(): Promise<{
20
40
  provider: string;
21
41
  envKeys: string[];
42
+ frameworkEnvKeys: {
43
+ next: string[];
44
+ };
22
45
  }>;
23
46
  whoami(): Promise<{
24
47
  org: string;
25
- }>;
48
+ } | null>;
49
+ /** Returns the public DSN of the project named `input.name` (matched by its slug), creating it when missing; needs `org`, and the new project uses `team` (default the org slug) and `platform` (default `node`). */
26
50
  ensureProject(input: {
27
51
  name: string;
28
52
  platform?: string;
@@ -37,25 +61,14 @@ declare class SentryErrors implements Errors {
37
61
  */
38
62
  private requireOrg;
39
63
  }
40
- //#endregion
41
- //#region src/verify-token.d.ts
42
- interface VerifyTokenSuccess {
43
- ok: true;
44
- subject: string;
45
- }
46
- interface VerifyTokenFailure {
47
- ok: false;
48
- message: string;
49
- }
50
- type VerifyTokenResult = VerifyTokenSuccess | VerifyTokenFailure;
51
64
  interface VerifyTokenOptions {
52
65
  baseUrl?: string;
53
66
  fetch?: typeof fetch;
54
67
  }
55
- declare function verifyToken(token: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult>;
56
- //#endregion
57
- //#region src/index.d.ts
58
- interface SentryPluginOptions extends ResolveTokenInput, SentryErrorsOptions {
68
+ /** Checks a Sentry token by listing its organizations; the success subject is `org:` and the first organization's slug, the failure carries the error message. */
69
+ export declare function verifyToken(token: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult$1>;
70
+ /** Options for the Sentry plugin: token resolution, the organization and team, and test overrides. */
71
+ export interface SentryPluginOptions extends ResolveTokenInput, SentryErrorsOptions {
59
72
  /**
60
73
  * Sentry organization slug. Optional at load time — the `errors` capability
61
74
  * activates from env vars alone — but required for `whoami` / `ensureProject`
@@ -64,20 +77,32 @@ interface SentryPluginOptions extends ResolveTokenInput, SentryErrorsOptions {
64
77
  org?: string;
65
78
  /** Override base URL for tests. */
66
79
  baseUrl?: string;
80
+ /** Override `fetch` for tests. */
67
81
  fetch?: typeof fetch;
68
82
  }
69
- interface PluginContext {
83
+ /** What the plugin's capabilities share: the options and two lazily built clients. */
84
+ export interface PluginContext {
85
+ /** The options the plugin was created with. */
70
86
  options: SentryPluginOptions;
87
+ /** Builds the Sentry client on first call and reuses it; the token is resolved then, not at plugin load. */
71
88
  client: () => SentryClient;
89
+ /** The client for the Comlink relay: its own token (`sentry.comlink`), the general one only as a last resort. */
90
+ relayClient: () => SentryClient;
72
91
  }
73
- declare function createContext(options: SentryPluginOptions): PluginContext;
74
- declare function errors(ctx: PluginContext): Errors;
75
- declare function createPlugin(options: SentryPluginOptions): {
92
+ /** Creates the shared context for the given options; no token is resolved until a client is first called. */
93
+ export declare function createContext(options: SentryPluginOptions): PluginContext;
94
+ /** Builds the `errors` capability from a plugin context, using the relay client for the Comlink relay. */
95
+ export declare function errors(ctx: PluginContext): Errors;
96
+ /** Creates the Sentry plugin: its probes, a `connection` probe and the `errors` capability. */
97
+ export declare function createPlugin(options: SentryPluginOptions): {
76
98
  name: string;
99
+ probes: {
100
+ connection: import("@theholocron/cli").Probe;
101
+ };
77
102
  capabilities: {
78
103
  errors: () => Errors;
79
104
  };
80
105
  };
81
- declare const AUTH_HINT: string;
82
- //#endregion
83
- 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 };
106
+ /** One-line hint shown by `holocron auth set sentry` when no token is given or the token is rejected. */
107
+ export declare const AUTH_HINT: string;
108
+ export { AuthError, type ResolveTokenInput, type SentryClient, type SentryClientOptions, type SentryErrorsOptions, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createSentryClient };
package/dist/index.mjs CHANGED
@@ -1,32 +1,303 @@
1
- import { AuthError, ProviderApiError, createResolveToken } from "@theholocron/cli";
1
+ import { AuthError, ProviderApiError, connectionProbe, createFeatureResolver, createResolveToken } from "@theholocron/cli";
2
+ import { createEnvLookup, holocronEnv } from "@theholocron/env-utils/lookup";
3
+ import { randomUUID } from "node:crypto";
2
4
  import { createSentryClient } from "@theholocron/sentry-client";
3
- //#region src/auth.ts
5
+ import { errorMessage } from "@theholocron/misc-utils";
6
+ // src/auth.ts
7
+ /** Resolves the Sentry token from `--token`, `HOLOCRON_SENTRY_TOKEN`, `SENTRY_AUTH_TOKEN` or the keyring, and throws an `AuthError` when none is set. */
4
8
  const resolveToken = createResolveToken({
5
9
  envName: "HOLOCRON_SENTRY_TOKEN",
6
10
  vendorEnvName: "SENTRY_AUTH_TOKEN",
7
11
  keyringService: "sentry",
8
12
  errorMessage: "no Sentry auth token found. Pass --token <TOKEN>, set HOLOCRON_SENTRY_TOKEN / SENTRY_AUTH_TOKEN, or run: holocron auth set sentry <TOKEN>"
9
13
  });
10
- //#endregion
11
- //#region src/capabilities/errors.ts
14
+ /**
15
+ * The token for the Comlink relay: an integration, its client secret and an alert rule need more than the general token
16
+ * (`alerts:write`, `org:write`, `event:read`), so it has its own.
17
+ */
18
+ const resolveComlinkToken = createFeatureResolver({
19
+ envName: "HOLOCRON_SENTRY_COMLINK_TOKEN",
20
+ keyringKey: "sentry.comlink",
21
+ vendor: "Sentry"
22
+ });
23
+ /**
24
+ * The token for the relay: the Comlink one when there is one, else the general Sentry token as the last resort. The
25
+ * fallback only helps if the general token happens to carry the scopes; otherwise Sentry's answer names what is missing.
26
+ */
27
+ function resolveRelayToken(input = {}) {
28
+ try {
29
+ return resolveComlinkToken(input);
30
+ } catch (err) {
31
+ if (!(err instanceof AuthError)) throw err;
32
+ return resolveToken(input);
33
+ }
34
+ }
35
+ /** Every token this plugin takes, for `holocron doctor tokens`: the general one and the Comlink relay's own. */
36
+ const tokens = [resolveToken.token, resolveComlinkToken.token];
37
+ // src/capabilities/relay.ts
38
+ /** What the integration needs to read: the alert's event. It is also why reading its secret needs the same scope. */
39
+ const INTEGRATION_SCOPES = ["event:read"];
40
+ const DEFAULT_FREQUENCY = 5;
41
+ /**
42
+ * The alert action that sends through an integration, in the shape Sentry's own page writes when "Send a notification via
43
+ * an integration" is picked: a `webhook` action named by the integration's slug. (A `sentry_app` action with the numeric
44
+ * id is accepted too, but the page shows it as an unknown integration.)
45
+ */
46
+ const integrationAction = (slug) => ({
47
+ type: "webhook",
48
+ config: {
49
+ targetType: null,
50
+ targetDisplay: null,
51
+ targetIdentifier: slug
52
+ },
53
+ data: {}
54
+ });
55
+ const sendsThrough = (action, slug) => action.type === "webhook" && action.config["targetIdentifier"] === slug;
56
+ /** The `sentry_app` form an earlier version wrote for this integration, which the page cannot name. */
57
+ const isLegacyAction = (action, appId) => action.type === "sentry_app" && String(action.config["targetIdentifier"]) === String(appId);
58
+ /** A workflow as Sentry returned it, as the body to send back (the nested ids are not part of an update). */
59
+ function toInput(wf) {
60
+ return {
61
+ name: wf.name,
62
+ enabled: wf.enabled,
63
+ environment: wf.environment,
64
+ config: wf.config,
65
+ detectorIds: wf.detectorIds,
66
+ triggers: {
67
+ logicType: wf.triggers.logicType,
68
+ conditions: wf.triggers.conditions.map((c) => ({
69
+ type: c.type,
70
+ comparison: c.comparison,
71
+ conditionResult: c.conditionResult
72
+ }))
73
+ },
74
+ actionFilters: wf.actionFilters.map((f) => ({
75
+ logicType: f.logicType,
76
+ conditions: f.conditions.map((c) => ({
77
+ type: c.type,
78
+ comparison: c.comparison,
79
+ conditionResult: c.conditionResult
80
+ })),
81
+ actions: f.actions.map((a) => ({
82
+ type: a.type,
83
+ config: a.config,
84
+ data: a.data
85
+ }))
86
+ }))
87
+ };
88
+ }
89
+ /** Sentry's own "high priority issues" rule, which is the default for a new alert. */
90
+ function newWorkflow(name, frequency, detectorIds, slug) {
91
+ return {
92
+ name,
93
+ enabled: true,
94
+ environment: null,
95
+ config: { frequency },
96
+ detectorIds,
97
+ triggers: {
98
+ logicType: "any-short",
99
+ conditions: [{
100
+ type: "new_high_priority_issue",
101
+ comparison: true,
102
+ conditionResult: true
103
+ }, {
104
+ type: "existing_high_priority_issue",
105
+ comparison: true,
106
+ conditionResult: true
107
+ }]
108
+ },
109
+ actionFilters: [{
110
+ logicType: "all",
111
+ conditions: [],
112
+ actions: [integrationAction(slug)]
113
+ }]
114
+ };
115
+ }
116
+ /** The integration: found by name, made if missing, and its webhook and alert action brought in line. */
117
+ async function ensureIntegration(client, org, input) {
118
+ const existing = (await client.sentryApps.list(org)).find((a) => a.name === input.name);
119
+ if (!existing) return {
120
+ app: await client.sentryApps.create(org, {
121
+ name: input.name,
122
+ scopes: INTEGRATION_SCOPES,
123
+ webhookUrl: input.webhookUrl,
124
+ isAlertable: true
125
+ }),
126
+ created: true,
127
+ updated: []
128
+ };
129
+ const updated = [];
130
+ if (existing.webhookUrl !== input.webhookUrl) updated.push("webhook URL");
131
+ if (!existing.isAlertable) updated.push("alert action");
132
+ const scopes = [.../* @__PURE__ */ new Set([...existing.scopes, ...INTEGRATION_SCOPES])];
133
+ if (scopes.length !== existing.scopes.length) updated.push("scopes");
134
+ if (updated.length === 0) return {
135
+ app: existing,
136
+ created: false,
137
+ updated
138
+ };
139
+ return {
140
+ app: await client.sentryApps.update(existing.slug, {
141
+ name: existing.name,
142
+ scopes,
143
+ webhookUrl: input.webhookUrl,
144
+ isAlertable: true
145
+ }),
146
+ created: false,
147
+ updated
148
+ };
149
+ }
150
+ /** The issue stream detector of each project, so a wrong project fails before anything is changed. */
151
+ async function detectorsFor(client, org, slugs) {
152
+ const [projects, detectors] = await Promise.all([client.projects.list(org), client.workflows.detectors(org)]);
153
+ return slugs.map((slug) => {
154
+ const project = projects.find((p) => p.slug === slug);
155
+ if (!project) throw new Error(`Sentry project \`${slug}\` was not found in ${org}`);
156
+ const detector = detectors.find((d) => d.projectId === project.id && d.type === "issue_stream");
157
+ if (!detector) throw new Error(`Sentry project \`${slug}\` has no issue stream detector to attach an alert to`);
158
+ return detector.id;
159
+ });
160
+ }
161
+ /** The alert rule: one workflow for every project, found by name, made if missing, reconciled if not. */
162
+ async function ensureRule(client, org, input, install, detectorIds) {
163
+ const workflows = await client.workflows.list(org);
164
+ const frequency = input.rule.frequency ?? DEFAULT_FREQUENCY;
165
+ const existing = workflows.find((w) => w.name === input.rule.name);
166
+ if (!existing) {
167
+ await client.workflows.create(org, newWorkflow(input.rule.name, frequency, detectorIds, install.slug));
168
+ return {
169
+ created: true,
170
+ updated: []
171
+ };
172
+ }
173
+ const next = toInput(existing);
174
+ const updated = [];
175
+ if (!existing.enabled) {
176
+ next.enabled = true;
177
+ updated.push("enabled");
178
+ }
179
+ if (input.rule.frequency !== void 0 && existing.config.frequency !== input.rule.frequency) {
180
+ next.config = {
181
+ ...existing.config,
182
+ frequency: input.rule.frequency
183
+ };
184
+ updated.push("frequency");
185
+ }
186
+ const missing = detectorIds.filter((id) => !existing.detectorIds.includes(id));
187
+ if (missing.length > 0) {
188
+ next.detectorIds = [...existing.detectorIds, ...missing];
189
+ updated.push("projects");
190
+ }
191
+ const sends = existing.actionFilters.some((f) => f.actions.some((a) => sendsThrough(a, install.slug)));
192
+ const legacy = existing.actionFilters.some((f) => f.actions.some((a) => isLegacyAction(a, install.appId)));
193
+ if (legacy) for (const f of next.actionFilters) f.actions = f.actions.filter((a) => !isLegacyAction(a, install.appId));
194
+ if (!sends) {
195
+ const open = next.actionFilters.find((f) => f.conditions.length === 0);
196
+ if (open) open.actions.push(integrationAction(install.slug));
197
+ else next.actionFilters.push({
198
+ logicType: "all",
199
+ conditions: [],
200
+ actions: [integrationAction(install.slug)]
201
+ });
202
+ }
203
+ if (legacy || !sends) updated.push("action");
204
+ if (updated.length === 0) return {
205
+ created: false,
206
+ updated
207
+ };
208
+ await client.workflows.update(org, existing.id, next);
209
+ return {
210
+ created: false,
211
+ updated
212
+ };
213
+ }
214
+ /** The signing secret, if the token may see it: a new integration's answer omits it, so it is read again. */
215
+ async function secretOf(client, app) {
216
+ if (app.clientSecret) return app.clientSecret;
217
+ return (await client.sentryApps.get(app.slug)).clientSecret || void 0;
218
+ }
219
+ async function ensureSentryRelay(client, org, input) {
220
+ if (input.projects.length === 0) throw new Error("relay needs at least one Sentry project to alert on");
221
+ const detectorIds = await detectorsFor(client, org, input.projects);
222
+ const integration = await ensureIntegration(client, org, input);
223
+ const install = (await client.sentryApps.installations(org)).find((i) => i.app.slug === integration.app.slug);
224
+ if (!install) throw new Error(`the integration \`${integration.app.name}\` is not installed on ${org}`);
225
+ const rule = await ensureRule(client, org, input, {
226
+ slug: install.app.slug,
227
+ appId: install.app.sentryAppId
228
+ }, detectorIds);
229
+ const clientSecret = await secretOf(client, integration.app);
230
+ return {
231
+ integration: {
232
+ created: integration.created,
233
+ updated: integration.updated
234
+ },
235
+ rule,
236
+ ...clientSecret ? { clientSecret } : {}
237
+ };
238
+ }
239
+ /**
240
+ * Read the integration and the alert rule back, changing nothing. The integration's signing secret is not read: the
241
+ * list answer is used as it is and `get`, which returns the secret, is never called.
242
+ */
243
+ async function inspectSentryRelay(client, org, input) {
244
+ const apps = await client.sentryApps.list(org);
245
+ const projects = await client.projects.list(org);
246
+ const detectors = await client.workflows.detectors(org);
247
+ const workflows = await client.workflows.list(org);
248
+ const app = apps.find((a) => a.name === input.name);
249
+ const rule = workflows.find((w) => w.name === input.rule.name);
250
+ return {
251
+ ...app ? { integration: {
252
+ webhookUrl: app.webhookUrl,
253
+ alertAction: app.isAlertable
254
+ } } : {},
255
+ rules: rule ? input.projects.flatMap((slug) => {
256
+ const project = projects.find((p) => p.slug === slug);
257
+ const detector = project && detectors.find((d) => d.projectId === project.id && d.type === "issue_stream");
258
+ if (!detector || !rule.detectorIds.includes(detector.id)) return [];
259
+ const sends = app !== void 0 && rule.actionFilters.some((f) => f.actions.some((a) => sendsThrough(a, app.slug)));
260
+ return [{
261
+ project: slug,
262
+ enabled: rule.enabled,
263
+ sends
264
+ }];
265
+ }) : []
266
+ };
267
+ }
268
+ // src/capabilities/errors.ts
269
+ /** The `errors` capability for Sentry: finds or creates a project and reports its DSN, and manages the Comlink relay. */
12
270
  var SentryErrors = class {
13
271
  client;
14
272
  opts;
273
+ relayClient;
274
+ /** The capability key, always `errors`. */
15
275
  key = "errors";
276
+ /** The provider name, `sentry`. */
16
277
  providerName = "sentry";
17
- constructor(client, opts) {
278
+ constructor(client, opts, relayClient = client) {
18
279
  this.client = client;
19
280
  this.opts = opts;
281
+ this.relayClient = relayClient;
282
+ }
283
+ async ensureRelay(input) {
284
+ return ensureSentryRelay(this.relayClient(), this.requireOrg(), input);
285
+ }
286
+ async inspectRelay(input) {
287
+ return inspectSentryRelay(this.relayClient(), this.requireOrg(), input);
20
288
  }
21
289
  async describe() {
22
290
  return {
23
291
  provider: "sentry",
24
- envKeys: ["SENTRY_DSN", "NEXT_PUBLIC_SENTRY_DSN"]
292
+ envKeys: ["SENTRY_DSN"],
293
+ frameworkEnvKeys: { next: ["NEXT_PUBLIC_SENTRY_DSN"] }
25
294
  };
26
295
  }
27
296
  async whoami() {
28
- return { org: (await this.client().auth.getOrg(this.requireOrg())).slug };
297
+ if (!this.opts.org) return null;
298
+ return { org: (await this.client().auth.getOrg(this.opts.org)).slug };
29
299
  }
300
+ /** Returns the public DSN of the project named `input.name` (matched by its slug), creating it when missing; needs `org`, and the new project uses `team` (default the org slug) and `platform` (default `node`). */
30
301
  async ensureProject(input) {
31
302
  const org = this.requireOrg();
32
303
  const slug = toSlug(input.name);
@@ -68,8 +339,244 @@ var SentryErrors = class {
68
339
  function toSlug(name) {
69
340
  return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
70
341
  }
71
- //#endregion
72
- //#region src/verify-token.ts
342
+ // src/probes/probe-deps.type.ts
343
+ function requireOrg(deps) {
344
+ if (!deps.org) throw new Error("the Sentry probes need `org` in the sentry provider's options");
345
+ return deps.org;
346
+ }
347
+ // src/probes/integrations.ts
348
+ /** Where a webhook points, without a query string that could carry a token. */
349
+ function where(url) {
350
+ if (!url) return "no webhook";
351
+ try {
352
+ const u = new URL(url);
353
+ return `${u.host}${u.pathname}`;
354
+ } catch {
355
+ return "an unreadable URL";
356
+ }
357
+ }
358
+ function integrationsProbe(deps) {
359
+ return {
360
+ summary: "List the custom integrations: scopes, alert action, webhook, and whether the client secret is visible.",
361
+ writes: false,
362
+ async run(probe) {
363
+ const apps = await deps.client().sentryApps.list(requireOrg(deps));
364
+ if (apps.length === 0) probe.say({
365
+ status: "info",
366
+ label: "no custom integrations"
367
+ });
368
+ for (const app of apps) {
369
+ probe.secret(app.clientSecret);
370
+ probe.say({
371
+ status: "ok",
372
+ label: `${app.name} (${app.slug})`,
373
+ detail: [
374
+ `scopes: ${app.scopes.join(", ") || "none"}`,
375
+ `alert action: ${app.isAlertable ? "on" : "off"}`,
376
+ `webhook: ${where(app.webhookUrl)}`,
377
+ `secret visible: ${app.clientSecret ? "yes" : "no"}`
378
+ ].join(" | ")
379
+ });
380
+ }
381
+ }
382
+ };
383
+ }
384
+ // src/probes/rule-update.ts
385
+ const FROM = 5;
386
+ const TO = 10;
387
+ /** The detector the throwaway rule hangs on: the issue stream of `HOLOCRON_SENTRY_PROBE_PROJECT`, else of any project. */
388
+ async function detectorFor(deps, org) {
389
+ const client = deps.client();
390
+ const slug = createEnvLookup(deps.env).get("HOLOCRON_SENTRY_PROBE_PROJECT");
391
+ const [detectors, projects] = await Promise.all([client.workflows.detectors(org), slug ? client.projects.list(org) : Promise.resolve([])]);
392
+ const streams = detectors.filter((d) => d.type === "issue_stream");
393
+ if (slug) {
394
+ const project = projects.find((p) => p.slug === slug);
395
+ if (!project) throw new Error(`Sentry project \`${slug}\` was not found in ${org}`);
396
+ const own = streams.find((d) => d.projectId === project.id);
397
+ if (!own) throw new Error(`Sentry project \`${slug}\` has no issue stream detector`);
398
+ return own.id;
399
+ }
400
+ const any = streams[0];
401
+ if (!any) throw new Error("no project has an issue stream detector to attach a throwaway rule to");
402
+ return any.id;
403
+ }
404
+ function ruleUpdateProbe(deps) {
405
+ return {
406
+ summary: "Make a disabled throwaway alert rule, change it the way the relay's adopt path does, read it back, delete it.",
407
+ writes: true,
408
+ async run(probe) {
409
+ const org = requireOrg(deps);
410
+ const client = deps.client();
411
+ const detectorId = await detectorFor(deps, org);
412
+ const body = {
413
+ name: `Holocron probe: throwaway rule (${(/* @__PURE__ */ new Date()).toISOString()})`,
414
+ enabled: false,
415
+ environment: null,
416
+ config: { frequency: FROM },
417
+ detectorIds: [detectorId],
418
+ triggers: {
419
+ logicType: "any-short",
420
+ conditions: [{
421
+ type: "new_high_priority_issue",
422
+ comparison: true,
423
+ conditionResult: true
424
+ }]
425
+ },
426
+ actionFilters: [{
427
+ logicType: "all",
428
+ conditions: [],
429
+ actions: []
430
+ }]
431
+ };
432
+ const created = await probe.write("create a disabled throwaway alert rule", async () => {
433
+ const wf = await client.workflows.create(org, body);
434
+ probe.cleanup(`the throwaway rule ${wf.id}`, () => client.workflows.delete(org, wf.id));
435
+ return wf;
436
+ });
437
+ if (!created) {
438
+ probe.say({
439
+ status: "info",
440
+ label: `would then change its frequency ${FROM} to ${TO} with PUT, read it back, and delete it`
441
+ });
442
+ return;
443
+ }
444
+ probe.say({
445
+ status: "ok",
446
+ label: "created",
447
+ detail: `rule ${created.id}, disabled`
448
+ });
449
+ const next = toInput(created);
450
+ next.config = {
451
+ ...created.config,
452
+ frequency: TO
453
+ };
454
+ await client.workflows.update(org, created.id, next);
455
+ probe.say({
456
+ status: "ok",
457
+ label: "PUT accepted"
458
+ });
459
+ const read = await client.workflows.get(org, created.id);
460
+ const kept = !read.enabled && read.detectorIds.includes(detectorId);
461
+ probe.say(read.config.frequency === TO && kept ? {
462
+ status: "ok",
463
+ label: "read back",
464
+ detail: `frequency ${read.config.frequency}, still disabled and attached`
465
+ } : {
466
+ status: "fail",
467
+ label: "read back differs",
468
+ detail: `frequency ${read.config.frequency} (sent ${TO}), enabled ${read.enabled}, detectors ${read.detectorIds.join(",")}`
469
+ });
470
+ }
471
+ };
472
+ }
473
+ // src/probes/rules.ts
474
+ function rulesProbe(deps) {
475
+ return {
476
+ summary: "List the alert rules: enabled, projects attached, and what each action sends to.",
477
+ writes: false,
478
+ async run(probe) {
479
+ const org = requireOrg(deps);
480
+ const client = deps.client();
481
+ const [workflows, apps] = await Promise.all([client.workflows.list(org), client.sentryApps.list(org)]);
482
+ const alertable = new Set(apps.filter((a) => a.isAlertable).map((a) => a.slug));
483
+ if (workflows.length === 0) probe.say({
484
+ status: "info",
485
+ label: "no alert rules"
486
+ });
487
+ for (const wf of workflows) {
488
+ const actions = wf.actionFilters.flatMap((f) => f.actions);
489
+ const described = actions.map((a) => {
490
+ const target = String(a.config["targetIdentifier"] ?? a.config["targetType"] ?? "");
491
+ return target ? `${a.type} ${target}` : a.type;
492
+ });
493
+ const problems = actions.flatMap((a) => {
494
+ if (a.type === "sentry_app") return [`a sentry_app action shows as an unknown integration`];
495
+ if (a.type === "webhook" && !alertable.has(String(a.config["targetIdentifier"]))) return [`webhook ${String(a.config["targetIdentifier"])} is not an alertable integration`];
496
+ return [];
497
+ });
498
+ probe.say({
499
+ status: problems.length > 0 || !wf.enabled ? "fail" : "ok",
500
+ label: wf.name,
501
+ detail: [
502
+ wf.enabled ? "enabled" : "DISABLED",
503
+ `detectors: ${wf.detectorIds.length}`,
504
+ `actions: ${described.join(", ") || "none"}`,
505
+ ...problems
506
+ ].join(" | ")
507
+ });
508
+ }
509
+ }
510
+ };
511
+ }
512
+ // src/probes/send-error.ts
513
+ /** Which DSN to send to: `HOLOCRON_SENTRY_DSN`, else `SENTRY_DSN`, else the first client key of the project named in `HOLOCRON_SENTRY_PROBE_PROJECT`. */
514
+ async function dsnFor(deps) {
515
+ const env = holocronEnv(deps.env);
516
+ const configured = env.get("SENTRY_DSN");
517
+ if (configured) return configured;
518
+ const project = env.get("HOLOCRON_SENTRY_PROBE_PROJECT");
519
+ if (!project) throw new Error("set SENTRY_DSN, or HOLOCRON_SENTRY_PROBE_PROJECT to a project slug, to say where to send the error");
520
+ const dsn = (await deps.client().projects.keys(requireOrg(deps), project))[0]?.dsn.public;
521
+ if (!dsn) throw new Error(`project \`${project}\` has no client key`);
522
+ return dsn;
523
+ }
524
+ function sendErrorProbe(deps) {
525
+ return {
526
+ summary: "Send one labelled test error to a project, to follow it through the alert rule to Discord.",
527
+ writes: true,
528
+ async run(probe) {
529
+ const dsn = new URL(await dsnFor(deps));
530
+ probe.secret(dsn.username);
531
+ const projectId = dsn.pathname.replace(/^\/+/, "");
532
+ const eventId = randomUUID().replaceAll("-", "");
533
+ const message = `Holocron probe: sent on purpose (${(/* @__PURE__ */ new Date()).toISOString()})`;
534
+ const envelope = [
535
+ JSON.stringify({
536
+ event_id: eventId,
537
+ sent_at: (/* @__PURE__ */ new Date()).toISOString()
538
+ }),
539
+ JSON.stringify({ type: "event" }),
540
+ JSON.stringify({
541
+ event_id: eventId,
542
+ level: "error",
543
+ platform: "node",
544
+ environment: "holocron-probe",
545
+ message: { formatted: message },
546
+ exception: { values: [{
547
+ type: "HolocronProbeError",
548
+ value: message
549
+ }] },
550
+ tags: { probe: "sentry.send-error" }
551
+ })
552
+ ].join("\n");
553
+ if (await probe.write("send a test error", async () => {
554
+ const res = await (deps.fetch ?? fetch)(`${dsn.protocol}//${dsn.host}/api/${projectId}/envelope/?sentry_version=7&sentry_key=${dsn.username}&sentry_client=holocron-probe/1`, {
555
+ method: "POST",
556
+ headers: { "content-type": "application/x-sentry-envelope" },
557
+ body: envelope
558
+ });
559
+ if (!res.ok) throw new Error(`Sentry answered ${res.status}`);
560
+ return true;
561
+ })) probe.say({
562
+ status: "ok",
563
+ label: "sent HolocronProbeError",
564
+ detail: "look for it in the project's issues and, through the rule, in #errors; resolve the issue by hand (a probe cannot delete it)"
565
+ });
566
+ }
567
+ };
568
+ }
569
+ // src/probes/index.ts
570
+ function sentryProbes(deps) {
571
+ return {
572
+ integrations: integrationsProbe(deps),
573
+ rules: rulesProbe(deps),
574
+ "rule-update": ruleUpdateProbe(deps),
575
+ "send-error": sendErrorProbe(deps)
576
+ };
577
+ }
578
+ // src/verify-token.ts
579
+ /** Checks a Sentry token by listing its organizations; the success subject is `org:` and the first organization's slug, the failure carries the error message. */
73
580
  async function verifyToken(token, opts = {}) {
74
581
  const client = createSentryClient({
75
582
  token,
@@ -84,36 +591,61 @@ async function verifyToken(token, opts = {}) {
84
591
  } catch (err) {
85
592
  return {
86
593
  ok: false,
87
- message: err instanceof Error ? err.message : String(err)
594
+ message: errorMessage(err)
88
595
  };
89
596
  }
90
597
  }
91
- //#endregion
92
- //#region src/index.ts
598
+ // src/index.ts
599
+ /** Creates the shared context for the given options; no token is resolved until a client is first called. */
93
600
  function createContext(options) {
94
601
  let client;
602
+ let relayClient;
95
603
  return {
96
604
  options,
97
605
  client: () => client ??= createSentryClient({
98
606
  token: resolveToken(options),
99
607
  baseUrl: options.baseUrl,
100
608
  fetch: options.fetch
609
+ }),
610
+ relayClient: () => relayClient ??= createSentryClient({
611
+ token: resolveRelayToken(options),
612
+ baseUrl: options.baseUrl,
613
+ fetch: options.fetch
101
614
  })
102
615
  };
103
616
  }
617
+ /** Builds the `errors` capability from a plugin context, using the relay client for the Comlink relay. */
104
618
  function errors(ctx) {
105
619
  return new SentryErrors(ctx.client, {
106
620
  org: ctx.options.org,
107
621
  team: ctx.options.team
108
- });
622
+ }, ctx.relayClient);
109
623
  }
624
+ /** Creates the Sentry plugin: its probes, a `connection` probe and the `errors` capability. */
110
625
  function createPlugin(options) {
111
626
  const ctx = createContext(options);
112
627
  return {
113
628
  name: "@theholocron/holocron-plugin-sentry",
629
+ probes: {
630
+ ...sentryProbes({
631
+ org: options.org,
632
+ client: ctx.relayClient,
633
+ fetch: options.fetch
634
+ }),
635
+ connection: connectionProbe({
636
+ provider: "Sentry",
637
+ url: options.baseUrl ?? "https://sentry.io",
638
+ fetch: options.fetch,
639
+ token: () => resolveToken(options),
640
+ verify: (token) => verifyToken(token, {
641
+ baseUrl: options.baseUrl,
642
+ fetch: options.fetch
643
+ })
644
+ })
645
+ },
114
646
  capabilities: { errors: () => errors(ctx) }
115
647
  };
116
648
  }
649
+ /** One-line hint shown by `holocron auth set sentry` when no token is given or the token is rejected. */
117
650
  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>";
118
- //#endregion
119
- export { AUTH_HINT, AuthError, SentryErrors, createContext, createPlugin, createSentryClient, errors, resolveToken, verifyToken };
651
+ export { AUTH_HINT, AuthError, SentryErrors, createContext, createPlugin, createSentryClient, errors, resolveComlinkToken, resolveRelayToken, resolveToken, tokens, verifyToken };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-sentry",
3
- "version": "5.0.0-alpha.42",
3
+ "version": "5.0.0-alpha.421",
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",
@@ -8,12 +8,12 @@
8
8
  "plugin",
9
9
  "sentry"
10
10
  ],
11
- "homepage": "https://github.com/theholocron/holocron/tree/main/packages/holocron-plugin-sentry#readme",
11
+ "homepage": "https://docs.theholocron.dev/holocron/plugins/sentry/",
12
12
  "bugs": "https://github.com/theholocron/holocron/issues",
13
13
  "repository": {
14
14
  "type": "git",
15
15
  "url": "git+https://github.com/theholocron/holocron.git",
16
- "directory": "packages/holocron-plugin-sentry"
16
+ "directory": "plugins/holocron-plugin-sentry"
17
17
  },
18
18
  "license": "MIT",
19
19
  "author": "Newton Koumantzelis",
@@ -29,29 +29,34 @@
29
29
  "files": [
30
30
  "dist"
31
31
  ],
32
+ "dependencies": {
33
+ "@theholocron/env-utils": "^1.17.0-alpha.4"
34
+ },
32
35
  "devDependencies": {
33
- "@theholocron/eslint-config": "^8.0.0",
34
- "@theholocron/http-client": "^1.24.0",
35
- "@theholocron/sentry-client": "^1.24.0",
36
- "@theholocron/tsconfig": "^8.0.0",
37
- "@theholocron/tsdown-config": "^8.0.0",
38
- "@theholocron/vitest-config": "^8.0.0",
39
36
  "@types/node": "^26",
40
- "@vitest/coverage-v8": "^4.1.11",
41
- "@vitest/eslint-plugin": "^1.6.27",
42
- "chalk": "^6.0.0",
43
- "eslint": "^10.8.1",
44
- "eslint-plugin-n": "^18.3.0",
45
- "globals": "^17.11.0",
46
- "tsdown": "^0.22.14",
47
- "tsx": "4.23.12",
37
+ "@vitest/coverage-v8": "^5.1.0",
38
+ "@vitest/eslint-plugin": "^1.6.28",
39
+ "chalk": "^6.0.1",
40
+ "eslint": "^10.14.0",
41
+ "eslint-plugin-n": "^18.5.0",
42
+ "globals": "^17.14.0",
43
+ "tsdown": "^0.23.5",
44
+ "tsx": "4.23.15",
48
45
  "typescript": "^5.9.3",
49
- "vitest": "^4.1.11",
50
- "@theholocron/cli": "5.0.0-alpha.42"
46
+ "vitest": "^5.1.0",
47
+ "@theholocron/cli": "5.0.0-alpha.421",
48
+ "@theholocron/eslint-config": "^8.9.0-alpha.16",
49
+ "@theholocron/http-client": "^1.58.0-alpha.28",
50
+ "@theholocron/misc-utils": "^1.17.0-alpha.4",
51
+ "@theholocron/sentry-client": "^1.58.0-alpha.28",
52
+ "@theholocron/tsconfig": "^8.9.0-alpha.16",
53
+ "@theholocron/vitest-config": "^8.9.0-alpha.16",
54
+ "@theholocron/tsdown-config": "^8.9.0-alpha.16"
51
55
  },
52
56
  "peerDependencies": {
53
- "@theholocron/sentry-client": "^1.24.0",
54
- "@theholocron/cli": "5.0.0-alpha.42"
57
+ "@theholocron/misc-utils": "^1.16.0",
58
+ "@theholocron/sentry-client": "^1.56.0",
59
+ "@theholocron/cli": "5.0.0-alpha.421"
55
60
  },
56
61
  "peerDependenciesMeta": {
57
62
  "@theholocron/sentry-client": {}
@@ -63,11 +68,11 @@
63
68
  "access": "public"
64
69
  },
65
70
  "scripts": {
66
- "delivery.build": "tsdown",
67
- "sourceQuality.staticAnalysis": "holocron run sourceQuality.staticAnalysis --",
71
+ "build": "tsdown",
72
+ "lint:code": "eslint .",
73
+ "test:unit": "vitest run --coverage",
68
74
  "test:watch": "vitest",
69
- "validate": "tsx scripts/validate.mjs",
70
- "verification.typeSafety": "holocron run verification.typeSafety --",
71
- "verification.unitTests": "holocron run verification.unitTests --"
75
+ "typecheck": "tsc --noEmit",
76
+ "validate:plugin": "tsx scripts/validate.mjs"
72
77
  }
73
78
  }