@theholocron/holocron-plugin-axiom 5.0.0-alpha.57 → 5.0.0-alpha.571

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
@@ -4,7 +4,7 @@
4
4
 
5
5
  Axiom plugin for [Holocron](../cli). Implements the `logs` capability
6
6
  against [Axiom's REST API](https://axiom.co/docs/restapi/introduction),
7
- plus exports `verifyToken` + `AUTH_HINT` for use by `holocron auth`.
7
+ plus exports `verifyToken` + `AUTH_HINT` for use by `holocron check token`.
8
8
 
9
9
  > This plugin does **not** ship log lines. `@theholocron/observability/logger`'s
10
10
  > Axiom transport reads `HOLOCRON_AXIOM_TOKEN` / `HOLOCRON_AXIOM_DATASET`
@@ -26,14 +26,14 @@ Token resolution order:
26
26
  2. `HOLOCRON_AXIOM_TOKEN` env var (preferred — explicit intent)
27
27
  3. `AXIOM_TOKEN` env var (Axiom-native, works in CI)
28
28
  4. Keyring `axiom.<org>` — tried first when an org is active via `--org`, `HOLOCRON_ORG`, or `org` in `holocron.config.ts`
29
- 5. Keyring `axiom` — unnamespaced fallback; set via `holocron auth set axiom <token>`
29
+ 5. Keyring `axiom` — unnamespaced fallback; set via `holocron new token axiom <token>`
30
30
  6. `AuthError` naming both env vars + the auth hint
31
31
 
32
32
  Generate an API token at **app.axiom.co/settings/api-tokens** with
33
33
  permission to read and create datasets.
34
34
 
35
35
  ```bash
36
- holocron auth set axiom.theholocron <TOKEN>
36
+ holocron new token axiom.theholocron <TOKEN>
37
37
  ```
38
38
 
39
39
  **CI**: the keyring is unavailable in headless containers — expose the
@@ -49,27 +49,28 @@ token as `HOLOCRON_AXIOM_TOKEN` (or `AXIOM_TOKEN`) in the workflow env.
49
49
  }
50
50
  ```
51
51
 
52
- No options are required. `holocron setup` provisions the `holocron-ci`
53
- and `holocron-local` datasets; `holocron doctor` checks the dataset
54
- named by `HOLOCRON_AXIOM_DATASET` / `AXIOM_DATASET`. An explicit
55
- `logs: ["axiom", { "dataset": "holocron-ci" }]` overrides the env var
56
- for `doctor`.
52
+ No options are required. `holocron setup` provisions the CLI's dataset (`holocron`)
53
+ named by `HOLOCRON_AXIOM_DATASET` / `AXIOM_DATASET`; every environment of the CLI ships to
54
+ it and is told apart by the `env` field on each line. `holocron doctor` checks
55
+ the same dataset. An explicit `logs: ["axiom", { "dataset": "my-dataset" }]`
56
+ overrides the env var for `doctor`.
57
57
 
58
- `HOLOCRON_AXIOM_DATASET` is **not a secret** — set it in your shell
59
- profile locally (`holocron-local`) or as an org CI secret
60
- (`holocron-ci`). Leave it unset locally to skip Axiom entirely.
58
+ The dataset name is **not a secret** — it is the org variable `HOLOCRON_AXIOM_DATASET`,
59
+ synced from 1Password. Leave the token unset locally to skip Axiom entirely.
61
60
 
62
61
  ## What's implemented
63
62
 
64
- | Method | Behavior |
65
- | --------------- | ------------------------------------------------------------------------------------------------ |
66
- | `describe` | Returns `{ provider: "axiom", envKeys: ["HOLOCRON_AXIOM_TOKEN", "HOLOCRON_AXIOM_DATASET"] }`. |
67
- | `whoami` | `GET /v2/datasets/{dataset}` — verifies the token and the configured dataset's reachability. |
68
- | `ensureDataset` | `GET /v2/datasets/{name}`; on 404, `POST /v2/datasets`. Returns `{ alreadyExists }`. Idempotent. |
63
+ | Method | Behavior |
64
+ | --------------- | ------------------------------------------------------------------------------------------------------------------------- |
65
+ | `describe` | Returns `{ provider: "axiom", envKeys: ["HOLOCRON_AXIOM_TOKEN", "HOLOCRON_AXIOM_DATASET"] }`. |
66
+ | `whoami` | `GET /v2/datasets/{dataset}` — verifies the token and the configured dataset's reachability. |
67
+ | `ensureDataset` | `GET /v2/datasets/{name}`; on 404, `POST /v2/datasets`. Returns `{ alreadyExists }`. Idempotent. |
68
+ | `readDataset` | `GET /v2/datasets/{name}`; a 404 is `{ exists: false }` and nothing is created. Returns `retentionDays` when Axiom does. |
69
+ | `checkToken` | `GET` of a dataset that cannot exist: a 404 means the token is accepted, a 401 means it is refused, anything else throws. |
69
70
 
70
71
  Plugin-level exports (not capability methods, per the auth-bootstrap convention):
71
72
 
72
- | Export | Purpose |
73
- | ------------- | ------------------------------------------------------------------------------------------- |
74
- | `verifyToken` | `GET /v2/user` — returns `{ ok: true, subject: "user @ …" }` or `{ ok: false, message }`. |
75
- | `AUTH_HINT` | One-line hint printed by `holocron auth set` when no token is supplied or the token is bad. |
73
+ | Export | Purpose |
74
+ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
75
+ | `verifyToken` | `GET /v2/user` — returns `{ ok: true, subject: "user @ …" }` or `{ ok: false, message }`. An API token cannot read the user (403), so it then reads the `dataset` option (`HOLOCRON_AXIOM_DATASET`), the dataset the token is scoped to: a 200 or a 404 is `API token`, a 403 or 401 there is rejected. |
76
+ | `AUTH_HINT` | One-line hint printed by `holocron new token` when no token is supplied or the token is bad. |
package/dist/index.d.mts CHANGED
@@ -1,39 +1,23 @@
1
- import { AuthError, Logs, ResolveTokenInput } from "@theholocron/cli";
2
- //#region src/auth.d.ts
3
- declare const resolveToken: (input?: ResolveTokenInput) => string;
4
- //#endregion
5
- //#region src/rest.d.ts
6
- /** Axiom dataset — the subset of fields Holocron reads. */
7
- interface AxiomDataset {
8
- id: string;
9
- name: string;
10
- description?: string;
11
- }
12
- /** Axiom user — the subset returned by `GET /v2/user`. */
13
- interface AxiomUser {
14
- id: string;
15
- name?: string;
16
- email?: string;
17
- emails?: string[];
18
- }
19
- interface AxiomClientOptions {
20
- token: string;
21
- /** Override the API base URL (default `https://api.axiom.co`). */
22
- baseUrl?: string;
23
- /** Override `fetch` for tests. */
24
- fetch?: typeof fetch;
25
- }
26
- interface AxiomRestClient {
27
- getDataset(name: string): Promise<AxiomDataset>;
28
- createDataset(input: {
29
- name: string;
30
- description?: string;
31
- }): Promise<AxiomDataset>;
32
- getCurrentUser(): Promise<AxiomUser>;
33
- }
34
- declare function createAxiomClient(opts: AxiomClientOptions): AxiomRestClient;
35
- //#endregion
36
- //#region src/capabilities/logs.d.ts
1
+ /**
2
+ * `@theholocron/holocron-plugin-axiom` — entrypoint.
3
+ *
4
+ * Implements the `logs` capability against Axiom's REST API. Also
5
+ * exports `verifyToken` + `AUTH_HINT` for `holocron check token`. See README
6
+ * for auth + config docs.
7
+ */
8
+ import { AuthError, Logs, LogsDataset, MintTokenInput, PluginToken, ResolveTokenInput, RevokeTokenInput, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess } from "@theholocron/cli";
9
+ import { AxiomClient, AxiomClientOptions, AxiomDataset, AxiomUser, CreateAxiomDatasetInput, createAxiomClient } from "@theholocron/axiom-client";
10
+ /** Resolves the Axiom token from `--token`, `HOLOCRON_AXIOM_TOKEN`, `AXIOM_TOKEN` or the keyring, and throws an `AuthError` when none is set. */
11
+ export declare const resolveToken: import("@theholocron/cli").TokenResolver;
12
+ /**
13
+ * Resolves the Axiom **personal access token** that `holocron provider axiom token` makes API tokens with, from
14
+ * `HOLOCRON_AXIOM_PERSONAL_TOKEN`, the `credentials` providers or the keyring entry `axiom.personal`. It never falls
15
+ * back to the dataset API token above, which cannot make tokens.
16
+ */
17
+ export declare const resolvePersonalToken: import("@theholocron/cli").FeatureResolver;
18
+ /** Every token this plugin takes, for `holocron doctor secrets --verify`, with what each layer's token must and must not be able to do. */
19
+ export declare const tokens: PluginToken[];
20
+ /** Options for the Axiom `logs` capability. */
37
21
  interface AxiomLogsOptions {
38
22
  /**
39
23
  * Target dataset, resolved from `HOLOCRON_AXIOM_DATASET` /
@@ -42,16 +26,19 @@ interface AxiomLogsOptions {
42
26
  */
43
27
  dataset?: string;
44
28
  }
45
- declare class AxiomLogs implements Logs {
29
+ /** The `logs` capability for Axiom: checks a dataset is reachable and creates datasets that are missing. */
30
+ export declare class AxiomLogs implements Logs {
46
31
  private readonly client;
47
32
  private readonly opts;
33
+ /** The capability key, always `logs`. */
48
34
  readonly key: "logs";
35
+ /** The provider name, `axiom`. */
49
36
  readonly providerName = "axiom";
50
37
  /**
51
38
  * `client` is a thunk — the token is resolved on first call, so
52
39
  * `describe()` (which needs no auth) works without one.
53
40
  */
54
- constructor(client: () => AxiomRestClient, opts: AxiomLogsOptions);
41
+ constructor(client: () => AxiomClient, opts: AxiomLogsOptions);
55
42
  describe(): Promise<{
56
43
  provider: string;
57
44
  envKeys: string[];
@@ -60,43 +47,41 @@ declare class AxiomLogs implements Logs {
60
47
  ok: boolean;
61
48
  dataset: string;
62
49
  }>;
50
+ readDataset(name: string): Promise<LogsDataset>;
51
+ checkToken(dataset?: string): Promise<{
52
+ ok: boolean;
53
+ reason?: string;
54
+ }>;
63
55
  ensureDataset(name: string): Promise<{
64
56
  alreadyExists: boolean;
65
57
  }>;
66
58
  }
67
- //#endregion
68
- //#region src/verify-token.d.ts
69
- /**
70
- * `verifyToken` — plugin-level export used by `holocron auth set axiom`
71
- * + `holocron auth check`. Hits `GET /v2/user` and translates the
72
- * response into the normalized `VerifyTokenResult` shape.
73
- *
74
- * Kept as a standalone function (not a capability method) so the auth
75
- * command can call it without initializing the full plugin.
76
- */
77
- interface VerifyTokenSuccess {
78
- ok: true;
79
- subject: string;
80
- }
81
- interface VerifyTokenFailure {
82
- ok: false;
83
- message: string;
84
- }
85
- type VerifyTokenResult = VerifyTokenSuccess | VerifyTokenFailure;
86
59
  interface VerifyTokenOptions {
87
60
  baseUrl?: string;
88
61
  fetch?: typeof fetch;
62
+ /**
63
+ * The dataset the token is meant to read (`HOLOCRON_AXIOM_DATASET`). An API token that cannot read the user is asked
64
+ * about this one, because a token scoped per dataset is refused (403) for any other name.
65
+ */
66
+ dataset?: string;
89
67
  }
90
- declare function verifyToken(token: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult>;
91
- //#endregion
92
- //#region src/index.d.ts
93
- interface AxiomPluginOptions extends ResolveTokenInput, AxiomLogsOptions {
68
+ /**
69
+ * Checks an Axiom token by fetching the current user; the success subject is `user @` followed by the email, name or id,
70
+ * the failure carries the error message. An API token cannot read the user (403), so then it asks for a dataset: the one
71
+ * the token is meant to read (`dataset`), else one that does not exist. A 200 or a 404 means the token is accepted and
72
+ * may read datasets, and the subject says `API token`; a 403 on the dataset it is meant to read still fails.
73
+ */
74
+ export declare function verifyToken(token: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult$1>;
75
+ /** Options for the Axiom plugin: token resolution, the target dataset and test overrides. */
76
+ export interface AxiomPluginOptions extends ResolveTokenInput, AxiomLogsOptions {
94
77
  /** Override base URL for tests. */
95
78
  baseUrl?: string;
96
79
  /** Override `fetch` for tests. */
97
80
  fetch?: typeof fetch;
98
81
  }
99
- interface PluginContext {
82
+ /** What the plugin's capabilities share: the resolved options and a lazily built client. */
83
+ export interface PluginContext {
84
+ /** The options, with `dataset` resolved from config, `HOLOCRON_AXIOM_DATASET` or `AXIOM_DATASET` (in that order). */
100
85
  options: AxiomPluginOptions & {
101
86
  dataset?: string;
102
87
  };
@@ -106,20 +91,29 @@ interface PluginContext {
106
91
  * no auth (`describe`) works without a token, and the loader never
107
92
  * aborts on a plugin whose token happens to be absent.
108
93
  */
109
- client: () => AxiomRestClient;
94
+ client: () => AxiomClient;
110
95
  }
111
- declare function createContext(options: AxiomPluginOptions): PluginContext;
112
- declare function logs(ctx: PluginContext): Logs;
113
- declare function createPlugin(options: AxiomPluginOptions): {
96
+ /** Creates the shared context for the given options; no token is resolved until `client()` is first called. */
97
+ export declare function createContext(options: AxiomPluginOptions): PluginContext;
98
+ /** Builds the `logs` capability from a plugin context. */
99
+ export declare function logs(ctx: PluginContext): Logs;
100
+ /** Creates the Axiom plugin: the `connection` and `token` probes, the `whoami` action and the `logs` capability. */
101
+ export declare function createPlugin(options: AxiomPluginOptions): {
114
102
  name: string;
103
+ probes: {
104
+ token: import("@theholocron/cli").Probe;
105
+ connection: import("@theholocron/cli").Probe;
106
+ };
107
+ whoami: import("@theholocron/cli").ProviderAction;
108
+ mintToken: (input: MintTokenInput) => Promise<import("@theholocron/cli").MintTokenResult>;
109
+ revokeToken: (input: RevokeTokenInput) => Promise<import("@theholocron/cli").RevokeTokenResult>;
115
110
  capabilities: {
116
111
  logs: () => Logs;
117
112
  };
118
113
  };
119
114
  /**
120
- * One-line hint shown by `holocron auth set axiom` when no token is
115
+ * One-line hint shown by `holocron new token axiom` when no token is
121
116
  * supplied or when the supplied token is rejected.
122
117
  */
123
- declare const AUTH_HINT: string;
124
- //#endregion
125
- export { AUTH_HINT, AuthError, type AxiomClientOptions, type AxiomDataset, AxiomLogs, type AxiomLogsOptions, AxiomPluginOptions, type AxiomRestClient, type AxiomUser, PluginContext, type ResolveTokenInput, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createAxiomClient, createContext, createPlugin, logs, resolveToken, verifyToken };
118
+ export declare const AUTH_HINT: string;
119
+ export { AuthError, type AxiomClient, type AxiomClientOptions, type AxiomDataset, type AxiomLogsOptions, type AxiomUser, type CreateAxiomDatasetInput, type ResolveTokenInput, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createAxiomClient };
package/dist/index.mjs CHANGED
@@ -1,17 +1,136 @@
1
- import { AuthError, ProviderApiError, createResolveToken, createRestClient } from "@theholocron/cli";
2
- //#region src/auth.ts
1
+ import { AuthError, ProviderApiError, connectionProbe, createFeatureResolver, createResolveToken, resolveValue, tokenExpectations, whoamiAction } from "@theholocron/cli";
2
+ import { PREFIX, createEnvLookup, firstEnv } from "@theholocron/env-utils/lookup";
3
+ import { errorMessage } from "@theholocron/misc-utils";
4
+ import { createAxiomClient } from "@theholocron/axiom-client";
5
+ // src/probes/token/expectations.ts
6
+ /**
7
+ * Datasets the logging setup retired (ADR-0019): one dataset per service now, split by the `env` field. A token that
8
+ * still reaches one is shown, so a layer pointed at the wrong dataset (`holocron-local` on a laptop) is visible.
9
+ */
10
+ const RETIRED_DATASETS = [
11
+ "holocron-local",
12
+ "holocron-ci",
13
+ "holocron-global"
14
+ ];
15
+ const RULES = {
16
+ read: "required",
17
+ ingest: "required",
18
+ query: "absent"
19
+ };
20
+ /**
21
+ * What each layer's Axiom token is meant to carry, the same as "What each Axiom token needs" in
22
+ * `docs/src/content/docs/tokens.mdx`. Every layer ships to the same dataset and only passes the environment as a field,
23
+ * so it is one token with the same permissions everywhere: it ingests (the logger) and reads the dataset (`doctor
24
+ * logs`), and does not query, because nothing in the repo reads logs back, so a leaked token cannot either. The probe
25
+ * still tries query, so a token that can is flagged. This is the plugin's `tokens` declaration, read through
26
+ * `tokenExpectations()`; change it and that table together.
27
+ */
28
+ const EXPECTED = { permissions: {
29
+ local: RULES,
30
+ dev: RULES,
31
+ ci: RULES,
32
+ prod: RULES,
33
+ agent: RULES
34
+ } };
35
+ /**
36
+ * Where the personal access token that makes API tokens (`HOLOCRON_AXIOM_PERSONAL_TOKEN`) is held: a maintainer's own
37
+ * machine (`local`) only, never `ci`. It has no permission model to declare: a personal token can do everything its
38
+ * owner can. Change it and the personal-token note in `tokens.mdx` together.
39
+ */
40
+ const PERSONAL_EXPECTED = { layers: ["local"] };
41
+ // src/verify-token.ts
42
+ /**
43
+ * `verifyToken` — plugin-level export used by `holocron new token axiom`
44
+ * + `holocron check token`. Hits `GET /v2/user` and translates the
45
+ * response into the normalized `VerifyTokenResult` shape.
46
+ *
47
+ * Kept as a standalone function (not a capability method) so the auth
48
+ * command can call it without initializing the full plugin.
49
+ */
50
+ /** Asked about when no dataset is known: one that does not exist, so a token that may read datasets answers 404. */
51
+ const PROBE_DATASET$1 = "holocron-token-check";
52
+ /**
53
+ * Checks an Axiom token by fetching the current user; the success subject is `user @` followed by the email, name or id,
54
+ * the failure carries the error message. An API token cannot read the user (403), so then it asks for a dataset: the one
55
+ * the token is meant to read (`dataset`), else one that does not exist. A 200 or a 404 means the token is accepted and
56
+ * may read datasets, and the subject says `API token`; a 403 on the dataset it is meant to read still fails.
57
+ */
58
+ async function verifyToken(token, opts = {}) {
59
+ const client = createAxiomClient({
60
+ token,
61
+ baseUrl: opts.baseUrl,
62
+ fetch: opts.fetch
63
+ });
64
+ try {
65
+ const me = await client.user.me();
66
+ return {
67
+ ok: true,
68
+ subject: `user @ ${me.email ?? me.emails?.[0] ?? me.name ?? me.id ?? "unknown"}`
69
+ };
70
+ } catch (err) {
71
+ if (err instanceof ProviderApiError && err.status === 403) return verifyApiToken(client, opts.dataset);
72
+ return {
73
+ ok: false,
74
+ message: errorMessage(err)
75
+ };
76
+ }
77
+ }
78
+ async function verifyApiToken(client, dataset) {
79
+ try {
80
+ await client.datasets.get(dataset ?? PROBE_DATASET$1);
81
+ return {
82
+ ok: true,
83
+ subject: "API token"
84
+ };
85
+ } catch (err) {
86
+ if (err instanceof ProviderApiError && err.status === 404) return {
87
+ ok: true,
88
+ subject: "API token"
89
+ };
90
+ return {
91
+ ok: false,
92
+ message: errorMessage(err)
93
+ };
94
+ }
95
+ }
96
+ // src/auth.ts
97
+ /** Resolves the Axiom token from `--token`, `HOLOCRON_AXIOM_TOKEN`, `AXIOM_TOKEN` or the keyring, and throws an `AuthError` when none is set. */
3
98
  const resolveToken = createResolveToken({
4
99
  envName: "HOLOCRON_AXIOM_TOKEN",
5
100
  vendorEnvName: "AXIOM_TOKEN",
6
101
  keyringService: "axiom",
7
- errorMessage: "no Axiom token found. Pass --token <TOKEN>, set HOLOCRON_AXIOM_TOKEN / AXIOM_TOKEN, or run: holocron auth set axiom <TOKEN>"
102
+ errorMessage: "no Axiom token found. Pass --token <TOKEN>, set HOLOCRON_AXIOM_TOKEN / AXIOM_TOKEN, or run: holocron new token axiom <TOKEN>"
8
103
  });
9
- //#endregion
10
- //#region src/capabilities/logs.ts
104
+ /**
105
+ * Resolves the Axiom **personal access token** that `holocron provider axiom token` makes API tokens with, from
106
+ * `HOLOCRON_AXIOM_PERSONAL_TOKEN`, the `credentials` providers or the keyring entry `axiom.personal`. It never falls
107
+ * back to the dataset API token above, which cannot make tokens.
108
+ */
109
+ const resolvePersonalToken = createFeatureResolver({
110
+ envName: "HOLOCRON_AXIOM_PERSONAL_TOKEN",
111
+ keyringKey: "axiom.personal",
112
+ vendor: "Axiom personal access"
113
+ });
114
+ /** Every token this plugin takes, for `holocron doctor secrets --verify`, with what each layer's token must and must not be able to do. */
115
+ const tokens = [{
116
+ ...resolveToken.token,
117
+ verify: (token) => verifyToken(token, { dataset: resolveValue(["AXIOM_DATASET"], void 0, { prefix: PREFIX }) }),
118
+ expect: EXPECTED
119
+ }, {
120
+ ...resolvePersonalToken.token,
121
+ optional: true,
122
+ expect: PERSONAL_EXPECTED
123
+ }];
124
+ // src/capabilities/logs.ts
125
+ /** The dataset asked for when the caller names none. It does not exist: asking for it tells a token Axiom accepts (404) from one it refuses (401). */
126
+ const PROBE_DATASET = "holocron-token-check";
127
+ /** The `logs` capability for Axiom: checks a dataset is reachable and creates datasets that are missing. */
11
128
  var AxiomLogs = class {
12
129
  client;
13
130
  opts;
131
+ /** The capability key, always `logs`. */
14
132
  key = "logs";
133
+ /** The provider name, `axiom`. */
15
134
  providerName = "axiom";
16
135
  /**
17
136
  * `client` is a thunk — the token is resolved on first call, so
@@ -30,76 +149,349 @@ var AxiomLogs = class {
30
149
  async whoami() {
31
150
  const dataset = this.opts.dataset;
32
151
  if (!dataset) throw new Error("@theholocron/holocron-plugin-axiom needs a dataset (HOLOCRON_AXIOM_DATASET / AXIOM_DATASET) for whoami");
33
- await this.client().getDataset(dataset);
152
+ await this.client().datasets.get(dataset);
34
153
  return {
35
154
  ok: true,
36
155
  dataset
37
156
  };
38
157
  }
158
+ async readDataset(name) {
159
+ try {
160
+ const found = await this.client().datasets.get(name);
161
+ const days = found.useRetentionPeriod === false ? void 0 : found.retentionDays;
162
+ return {
163
+ exists: true,
164
+ ...days === void 0 ? {} : { retentionDays: days }
165
+ };
166
+ } catch (err) {
167
+ if (err instanceof ProviderApiError) {
168
+ if (err.status === 404) return { exists: false };
169
+ if (err.status === 403) return {
170
+ exists: false,
171
+ forbidden: true
172
+ };
173
+ }
174
+ throw err;
175
+ }
176
+ }
177
+ async checkToken(dataset) {
178
+ try {
179
+ await this.client().datasets.get(dataset ?? PROBE_DATASET);
180
+ return { ok: true };
181
+ } catch (err) {
182
+ if (err instanceof ProviderApiError) {
183
+ if (err.status === 404) return { ok: true };
184
+ if (err.status === 401) return {
185
+ ok: false,
186
+ reason: "Axiom refused the token (401)"
187
+ };
188
+ }
189
+ throw err;
190
+ }
191
+ }
39
192
  async ensureDataset(name) {
40
193
  try {
41
- await this.client().getDataset(name);
194
+ await this.client().datasets.get(name);
42
195
  return { alreadyExists: true };
43
196
  } catch (err) {
44
197
  if (!(err instanceof ProviderApiError) || err.status !== 404) throw err;
45
198
  }
46
- await this.client().createDataset({
199
+ await this.client().datasets.create({
47
200
  name,
48
201
  description: "Managed by holocron"
49
202
  });
50
203
  return { alreadyExists: false };
51
204
  }
52
205
  };
53
- function createAxiomClient(opts) {
54
- const rest = createRestClient({
55
- baseUrl: opts.baseUrl ?? "https://api.axiom.co",
56
- token: opts.token,
57
- vendor: "Axiom",
58
- fetch: opts.fetch
206
+ // src/mint-token.ts
207
+ const DAY_MS = 864e5;
208
+ /**
209
+ * The dataset capability each declared permission grants. `read` (the dataset's own metadata, for `doctor logs`) has no
210
+ * capability Axiom documents, so it is not requested and a note says so rather than guessing a name.
211
+ */
212
+ const CAPABILITIES = {
213
+ ingest: {
214
+ name: "ingest",
215
+ capability: {
216
+ Access: "allow",
217
+ Actions: ["create"]
218
+ }
219
+ },
220
+ query: {
221
+ name: "query",
222
+ capability: {
223
+ Access: "allow",
224
+ Actions: ["read"]
225
+ }
226
+ }
227
+ };
228
+ /**
229
+ * Makes an Axiom API token for a layer through `POST /v2/tokens`, scoped to the one dataset and to the permissions the
230
+ * plugin declares `required` for that layer (`PluginToken.expect`), with an expiry from the declared rotation. It needs
231
+ * a personal access token (`HOLOCRON_AXIOM_PERSONAL_TOKEN`) and the organization id (`HOLOCRON_AXIOM_ORG`) and refuses,
232
+ * before any call, a layer with no declared permissions, no dataset, no org id or no personal token. It never grants an
233
+ * organization capability. The value is returned, never printed.
234
+ */
235
+ async function mintAxiomToken(input, options) {
236
+ const envName = resolveToken.token.envName;
237
+ const declared = tokenExpectations(tokens, {
238
+ layer: input.layer,
239
+ envName
240
+ })[0];
241
+ if (!declared || declared.required.length === 0) throw new Error(`the Axiom token declares no permissions for \`${input.layer}\`, so none can be made for it; a token with no declared scope is never made`);
242
+ const { dataset } = options;
243
+ if (!dataset) throw new Error("an Axiom dataset is required to make a token: set the plugin's dataset option or HOLOCRON_AXIOM_DATASET");
244
+ const orgId = resolveValue(["AXIOM_ORG"], options.env, { prefix: PREFIX });
245
+ if (!orgId) throw new Error("an Axiom organization id is required to make a token: set HOLOCRON_AXIOM_ORG (the `axiom-abcd` of your console URL)");
246
+ const personal = resolvePersonalToken({ env: options.env });
247
+ const granted = declared.required.flatMap((permission) => {
248
+ const entry = CAPABILITIES[permission];
249
+ return entry ? [entry] : [];
250
+ });
251
+ const unscoped = declared.required.filter((permission) => !CAPABILITIES[permission]);
252
+ const now = (input.now ?? (() => /* @__PURE__ */ new Date()))();
253
+ const days = input.expiresInDays ?? declared.rotation.maxAgeDays;
254
+ const created = await createAxiomClient({
255
+ token: personal,
256
+ orgId,
257
+ baseUrl: options.baseUrl,
258
+ fetch: options.fetch
259
+ }).tokens.create({
260
+ name: input.name,
261
+ description: `Made by holocron for the ${input.layer} layer`,
262
+ expiresAt: new Date(now.getTime() + days * DAY_MS).toISOString(),
263
+ datasetCapabilities: { [dataset]: Object.fromEntries(granted.map((g) => [g.name, g.capability])) }
59
264
  });
265
+ if (!created.token) throw new Error("Axiom made the token but returned no value");
60
266
  return {
61
- getDataset: (name) => rest.request(`/v2/datasets/${encodeURIComponent(name)}`),
62
- createDataset: (input) => rest.request("/v2/datasets", {
63
- method: "POST",
64
- body: input
65
- }),
66
- getCurrentUser: () => rest.request("/v2/user")
267
+ value: created.token,
268
+ envName,
269
+ id: created.id,
270
+ ...created.expiresAt ? { expiresAt: created.expiresAt } : {},
271
+ notes: [`the token reaches the \`${dataset}\` dataset only, with no organization capability`, ...unscoped.map((permission) => `\`${permission}\` was not requested, because Axiom documents no capability for it; run \`holocron probe axiom token --environment ${input.layer}\` to see what the token reaches`)]
67
272
  };
68
273
  }
69
- //#endregion
70
- //#region src/verify-token.ts
274
+ // src/probes/token/parse-token-args.ts
275
+ /** Reads the words after the probe name: `--layer <word>`, `--token-name <VAR>` and any number of dataset names. */
276
+ function parseTokenArgs(args) {
277
+ const datasets = [];
278
+ let layer;
279
+ let tokenName;
280
+ for (let i = 0; i < args.length; i++) {
281
+ const arg = args[i];
282
+ if (arg === "--layer") layer = args[++i];
283
+ else if (arg.startsWith("--layer=")) layer = arg.slice(8);
284
+ else if (arg === "--token-name") tokenName = args[++i];
285
+ else if (arg.startsWith("--token-name=")) tokenName = arg.slice(13);
286
+ else if (!arg.startsWith("--")) datasets.push(arg);
287
+ }
288
+ return {
289
+ ...layer ? { layer } : {},
290
+ ...tokenName ? { tokenName } : {},
291
+ datasets
292
+ };
293
+ }
294
+ // src/probes/token/token.ts
295
+ /** How many names to show before "(+N more)". */
296
+ const SHOWN = 8;
297
+ /** The time a query looks back over: a minute is enough, the query reads nothing the probe prints. */
298
+ const QUERY_WINDOW_MS = 6e4;
299
+ /** `a, b, c (+2 more)`. */
300
+ function summarise(names) {
301
+ return names.length <= SHOWN ? names.join(", ") : `${names.slice(0, SHOWN).join(", ")} (+${names.length - SHOWN} more)`;
302
+ }
71
303
  /**
72
- * `verifyToken` — plugin-level export used by `holocron auth set axiom`
73
- * + `holocron auth check`. Hits `GET /v2/user` and translates the
74
- * response into the normalized `VerifyTokenResult` shape.
75
- *
76
- * Kept as a standalone function (not a capability method) so the auth
77
- * command can call it without initializing the full plugin.
304
+ * Runs one request and says what came back. Axiom answers a token without the permission with a 401 or 403, and a
305
+ * dataset the token cannot see (or that does not exist) with a 404; all three are `none`. A request that fails for
306
+ * another reason (the network, a 5xx) is an `error`.
78
307
  */
79
- async function verifyToken(token, opts = {}) {
80
- const client = createAxiomClient({
81
- token,
82
- baseUrl: opts.baseUrl,
83
- fetch: opts.fetch
84
- });
308
+ async function reach(request) {
85
309
  try {
86
- const me = await client.getCurrentUser();
87
- return {
88
- ok: true,
89
- subject: `user @ ${me.email ?? me.emails?.[0] ?? me.name ?? me.id ?? "unknown"}`
90
- };
310
+ await request();
311
+ return { kind: "has" };
91
312
  } catch (err) {
313
+ if (err instanceof ProviderApiError && (err.status === 401 || err.status === 403)) return {
314
+ kind: "none",
315
+ detail: `no access (${err.status})`
316
+ };
317
+ if (err instanceof ProviderApiError && err.status === 404) return {
318
+ kind: "none",
319
+ detail: "no such dataset, or the token cannot see it (404)"
320
+ };
92
321
  return {
93
- ok: false,
94
- message: err instanceof Error ? err.message : String(err)
322
+ kind: "error",
323
+ detail: errorMessage(err)
95
324
  };
96
325
  }
97
326
  }
98
- //#endregion
99
- //#region src/index.ts
327
+ /** The APL query that reads one row of a dataset; the name is quoted the way APL quotes an identifier. */
328
+ function queryFor(dataset) {
329
+ return `['${dataset.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'] | take 1`;
330
+ }
331
+ /**
332
+ * One row for what was tried. With no rule it only describes (`ok` for access, `info` for none). Under a layer's rule it
333
+ * judges: a required permission the token lacks fails, and one the layer must not have fails when the token has it; a
334
+ * permission that is rightly absent is a bare `ok`.
335
+ */
336
+ function rowFor({ label, outcome }, rule) {
337
+ const detail = outcome.detail === void 0 ? {} : { detail: outcome.detail };
338
+ if (outcome.kind === "error") return {
339
+ status: "fail",
340
+ label,
341
+ ...detail
342
+ };
343
+ const has = outcome.kind === "has";
344
+ if (rule === "required") return {
345
+ status: has ? "ok" : "fail",
346
+ label,
347
+ ...detail
348
+ };
349
+ if (rule === "absent") return has ? {
350
+ status: "fail",
351
+ label,
352
+ ...detail
353
+ } : {
354
+ status: "ok",
355
+ label
356
+ };
357
+ return {
358
+ status: has ? "ok" : "info",
359
+ label,
360
+ ...detail
361
+ };
362
+ }
363
+ /**
364
+ * The `token` probe: tries each permission Holocron uses with the Axiom token on a dataset (reading it, ingesting and
365
+ * querying) and reports which ones the token has, then lists the datasets the token can see, so a token that reaches a
366
+ * retired dataset (`holocron-local`) is visible. Ingesting sends an empty list, which writes no event, and the query
367
+ * reads one row it never prints, so the probe changes nothing. The token is the one the plugin resolves, so
368
+ * `--token axiom=<token>` or `--environment <layer>` checks another one; the dataset is the plugin's own, or the names
369
+ * after the probe name.
370
+ *
371
+ * A token with no layer is only described. When the CLI passes `--layer` (because `--environment` named `ci`, `dev` or
372
+ * `local`), the results are judged against what that layer's token is meant to carry (the plugin's `tokens` declaration,
373
+ * read with `tokenExpectations()`) and shown in two groups, what it should have and what it should not, where a
374
+ * missing or extra permission fails.
375
+ */
376
+ function tokenProbe(ctx) {
377
+ return {
378
+ summary: "Try each Axiom permission Holocron uses (read, ingest, query) on a dataset with a token, and list the datasets the token can see; for a ci or dev Environment, check it against what that layer should carry. Read-only: ingest sends no event.",
379
+ writes: false,
380
+ acceptsToken: true,
381
+ async run(probe) {
382
+ const token = ctx.token();
383
+ probe.secret(token);
384
+ const client = ctx.client();
385
+ const { layer, tokenName, datasets: named } = parseTokenArgs(probe.args ?? []);
386
+ const rules = layer ? tokenExpectations(tokens, {
387
+ layer,
388
+ ...tokenName ? { envName: tokenName } : {}
389
+ })[0]?.rules : void 0;
390
+ if (layer && !rules) probe.say({
391
+ status: "info",
392
+ label: layer,
393
+ detail: "no expectations are declared for it, so the token is only described"
394
+ });
395
+ const targets = named.length > 0 ? named : ctx.options.dataset ? [ctx.options.dataset] : [];
396
+ if (targets.length === 0) probe.say({
397
+ status: rules ? "fail" : "info",
398
+ label: "dataset",
399
+ detail: "none given: name one after the probe, or set HOLOCRON_AXIOM_DATASET or the plugin's dataset option"
400
+ });
401
+ const tried = [];
402
+ for (const dataset of targets) {
403
+ const now = Date.now();
404
+ tried.push({
405
+ label: `Read (${dataset})`,
406
+ permission: "read",
407
+ outcome: await reach(() => client.datasets.get(dataset))
408
+ }, {
409
+ label: `Ingest (${dataset})`,
410
+ permission: "ingest",
411
+ outcome: await reach(() => client.datasets.ingest(dataset, []))
412
+ }, {
413
+ label: `Query (${dataset})`,
414
+ permission: "query",
415
+ outcome: await reach(() => client.datasets.query({
416
+ apl: queryFor(dataset),
417
+ startTime: (/* @__PURE__ */ new Date(now - QUERY_WINDOW_MS)).toISOString(),
418
+ endTime: new Date(now).toISOString()
419
+ }))
420
+ });
421
+ }
422
+ if (!rules) for (const t of tried) probe.say(rowFor(t, void 0));
423
+ else for (const [heading, rule] of [["Should have", "required"], ["Should not have", "absent"]]) {
424
+ const inGroup = tried.filter((t) => rules[t.permission] === rule);
425
+ if (inGroup.length === 0) continue;
426
+ probe.say({
427
+ status: "heading",
428
+ label: heading
429
+ });
430
+ for (const t of inGroup) probe.say(rowFor(t, rule));
431
+ }
432
+ probe.say({
433
+ status: "heading",
434
+ label: "Datasets this token can see"
435
+ });
436
+ try {
437
+ const names = (await client.datasets.list()).map((d) => d.name);
438
+ probe.say(names.length === 0 ? {
439
+ status: "info",
440
+ label: "datasets",
441
+ detail: "none visible"
442
+ } : {
443
+ status: "info",
444
+ label: "datasets",
445
+ detail: `${names.length}: ${summarise(names)}`
446
+ });
447
+ for (const name of names.filter((n) => RETIRED_DATASETS.includes(n))) probe.say({
448
+ status: "info",
449
+ label: name,
450
+ detail: "retired (one dataset per service now, ADR-0019): the token still reaches it"
451
+ });
452
+ } catch (err) {
453
+ const denied = err instanceof ProviderApiError && (err.status === 401 || err.status === 403);
454
+ probe.say({
455
+ status: denied ? "info" : "fail",
456
+ label: "datasets",
457
+ detail: denied ? `the token cannot list datasets (${err.status})` : errorMessage(err)
458
+ });
459
+ }
460
+ }
461
+ };
462
+ }
463
+ // src/revoke-token.ts
464
+ /**
465
+ * Deletes an Axiom API token through `DELETE /v2/tokens/{id}`. Like minting it needs a personal access token
466
+ * (`HOLOCRON_AXIOM_PERSONAL_TOKEN`) and the organization id (`HOLOCRON_AXIOM_ORG`) and refuses, before any call, when
467
+ * either is missing. The call is made with the personal token, which is never an API token the plugin minted, so no
468
+ * id can be the token in use. A token Axiom does not have (404) is `revoked: false`; any other refusal throws.
469
+ */
470
+ async function revokeAxiomToken(input, options) {
471
+ const orgId = resolveValue(["AXIOM_ORG"], options.env, { prefix: PREFIX });
472
+ if (!orgId) throw new Error("an Axiom organization id is required to revoke a token: set HOLOCRON_AXIOM_ORG (the `axiom-abcd` of your console URL)");
473
+ const personal = resolvePersonalToken({ env: options.env });
474
+ return await createAxiomClient({
475
+ token: personal,
476
+ orgId,
477
+ baseUrl: options.baseUrl,
478
+ fetch: options.fetch
479
+ }).tokens.delete(input.id).then(() => true, (err) => {
480
+ if (err instanceof ProviderApiError && err.status === 404) return false;
481
+ throw err;
482
+ }) ? {
483
+ revoked: true,
484
+ notes: ["anything that still ingests or queries with this token stops working: replace it where it is used (`holocron sync secrets`)"]
485
+ } : {
486
+ revoked: false,
487
+ notes: [`Axiom has no token \`${input.id}\` (already deleted or expired)`]
488
+ };
489
+ }
490
+ // src/index.ts
491
+ /** Creates the shared context for the given options; no token is resolved until `client()` is first called. */
100
492
  function createContext(options) {
101
- const env = options.env ?? process.env;
102
- const dataset = options.dataset ?? env.HOLOCRON_AXIOM_DATASET ?? env.AXIOM_DATASET;
493
+ const env = createEnvLookup(options.env);
494
+ const dataset = options.dataset ?? firstEnv(env, ["HOLOCRON_AXIOM_DATASET", "AXIOM_DATASET"]);
103
495
  let client;
104
496
  return {
105
497
  options: {
@@ -113,20 +505,60 @@ function createContext(options) {
113
505
  })
114
506
  };
115
507
  }
508
+ /** Builds the `logs` capability from a plugin context. */
116
509
  function logs(ctx) {
117
510
  return new AxiomLogs(ctx.client, { dataset: ctx.options.dataset });
118
511
  }
512
+ /** Creates the Axiom plugin: the `connection` and `token` probes, the `whoami` action and the `logs` capability. */
119
513
  function createPlugin(options) {
120
514
  const ctx = createContext(options);
121
515
  return {
122
516
  name: "@theholocron/holocron-plugin-axiom",
517
+ probes: {
518
+ token: tokenProbe({
519
+ options: ctx.options,
520
+ client: ctx.client,
521
+ token: () => resolveToken(options)
522
+ }),
523
+ connection: connectionProbe({
524
+ provider: "Axiom",
525
+ url: options.baseUrl ?? "https://api.axiom.co",
526
+ fetch: options.fetch,
527
+ token: () => resolveToken(options),
528
+ verify: (token) => verifyToken(token, {
529
+ baseUrl: options.baseUrl,
530
+ fetch: options.fetch,
531
+ dataset: ctx.options.dataset
532
+ })
533
+ })
534
+ },
535
+ whoami: whoamiAction({
536
+ provider: "axiom",
537
+ token: () => resolveToken(options),
538
+ verify: (token) => verifyToken(token, {
539
+ baseUrl: options.baseUrl,
540
+ fetch: options.fetch,
541
+ dataset: ctx.options.dataset
542
+ }),
543
+ tokens
544
+ }),
545
+ mintToken: (input) => mintAxiomToken(input, {
546
+ dataset: ctx.options.dataset,
547
+ env: options.env,
548
+ baseUrl: options.baseUrl,
549
+ fetch: options.fetch
550
+ }),
551
+ revokeToken: (input) => revokeAxiomToken(input, {
552
+ env: options.env,
553
+ baseUrl: options.baseUrl,
554
+ fetch: options.fetch
555
+ }),
123
556
  capabilities: { logs: () => logs(ctx) }
124
557
  };
125
558
  }
126
559
  /**
127
- * One-line hint shown by `holocron auth set axiom` when no token is
560
+ * One-line hint shown by `holocron new token axiom` when no token is
128
561
  * supplied or when the supplied token is rejected.
129
562
  */
130
- const AUTH_HINT = "generate an Axiom API token at https://app.axiom.co/settings/api-tokens with dataset read + create permissions, then run: holocron auth set axiom <TOKEN>";
131
- //#endregion
132
- export { AUTH_HINT, AuthError, AxiomLogs, createAxiomClient, createContext, createPlugin, logs, resolveToken, verifyToken };
563
+ const AUTH_HINT = "generate an Axiom API token at https://app.axiom.co/settings/api-tokens with dataset read + create permissions, then run: holocron new token axiom <TOKEN>";
564
+ export { AUTH_HINT, AuthError, AxiomLogs, createAxiomClient, createContext, createPlugin, logs, resolvePersonalToken, resolveToken, tokens, verifyToken };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-axiom",
3
- "version": "5.0.0-alpha.57",
3
+ "version": "5.0.0-alpha.571",
4
4
  "description": "Holocron plugin for Axiom. Implements the logs capability against Axiom's REST API — dataset provisioning and connectivity checks, plus verifyToken + AUTH_HINT for `holocron auth`.",
5
5
  "keywords": [
6
6
  "axiom",
@@ -8,12 +8,12 @@
8
8
  "logs",
9
9
  "plugin"
10
10
  ],
11
- "homepage": "https://github.com/theholocron/holocron/tree/main/packages/holocron-plugin-axiom#readme",
11
+ "homepage": "https://docs.theholocron.dev/holocron/plugins/axiom/",
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-axiom"
16
+ "directory": "plugins/holocron-plugin-axiom"
17
17
  },
18
18
  "license": "MIT",
19
19
  "author": "Newton Koumantzelis",
@@ -29,26 +29,33 @@
29
29
  "files": [
30
30
  "dist"
31
31
  ],
32
+ "dependencies": {
33
+ "@theholocron/env-utils": "^1.17.0-alpha.9"
34
+ },
32
35
  "devDependencies": {
33
- "@theholocron/eslint-config": "^8.4.5",
34
- "@theholocron/http-client": "^1.25.0",
35
- "@theholocron/tsconfig": "^8.4.5",
36
- "@theholocron/tsdown-config": "^8.4.5",
37
- "@theholocron/vitest-config": "^8.4.5",
38
36
  "@types/node": "^26",
39
- "@vitest/coverage-v8": "^4.1.11",
40
- "@vitest/eslint-plugin": "^1.6.27",
41
- "eslint": "^10.8.1",
42
- "eslint-plugin-n": "^18.3.0",
43
- "globals": "^17.11.0",
44
- "tsdown": "^0.22.14",
45
- "tsx": "4.23.12",
46
- "typescript": "^5.9.3",
47
- "vitest": "^4.1.11",
48
- "@theholocron/cli": "5.0.0-alpha.57"
37
+ "@vitest/coverage-v8": "^5.1.1",
38
+ "@vitest/eslint-plugin": "^1.6.28",
39
+ "eslint": "^10.15.0",
40
+ "eslint-plugin-n": "^18.5.0",
41
+ "globals": "^17.14.0",
42
+ "tsdown": "^0.23.7",
43
+ "tsx": "4.23.15",
44
+ "typescript": "^6.0.3",
45
+ "vitest": "^5.1.1",
46
+ "@theholocron/axiom-client": "^1.58.0-alpha.66",
47
+ "@theholocron/cli": "5.0.0-alpha.571",
48
+ "@theholocron/eslint-config": "^8.9.0-alpha.24",
49
+ "@theholocron/http-client": "^1.58.0-alpha.66",
50
+ "@theholocron/tsconfig": "^8.9.0-alpha.24",
51
+ "@theholocron/misc-utils": "^1.17.0-alpha.9",
52
+ "@theholocron/tsdown-config": "^8.9.0-alpha.24",
53
+ "@theholocron/vitest-config": "^8.9.0-alpha.24"
49
54
  },
50
55
  "peerDependencies": {
51
- "@theholocron/cli": "5.0.0-alpha.57"
56
+ "@theholocron/axiom-client": "^1.58.0",
57
+ "@theholocron/misc-utils": "^1.16.0",
58
+ "@theholocron/cli": "5.0.0-alpha.571"
52
59
  },
53
60
  "engines": {
54
61
  "node": ">=22"
@@ -57,11 +64,11 @@
57
64
  "access": "public"
58
65
  },
59
66
  "scripts": {
60
- "delivery.build": "tsdown",
61
- "sourceQuality.staticAnalysis": "holocron run sourceQuality.staticAnalysis --",
67
+ "build": "tsdown",
68
+ "lint:code": "eslint .",
69
+ "test:unit": "vitest run --coverage",
62
70
  "test:watch": "vitest",
63
- "validate": "tsx scripts/validate.mjs",
64
- "verification.typeSafety": "holocron run verification.typeSafety --",
65
- "verification.unitTests": "holocron run verification.unitTests --"
71
+ "typecheck": "tsc --noEmit",
72
+ "validate:plugin": "tsx scripts/validate.mjs"
66
73
  }
67
74
  }