The best way to control Claude Code, Codex and more from any computer or phone

main
ts 158 lines 5.94 KB
Raw
1 import * as Axiom from "@distilled.cloud/axiom";
2 import { deepEqual, isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Redacted from "effect/Redacted";
8 import type { Providers } from "./Providers.ts";
9
10 export type ApiTokenProps = Omit<Axiom.CreateAPITokenRequest, never>;
11
12 export type ApiToken = Resource<
13 "Axiom.ApiToken",
14 ApiTokenProps,
15 Omit<Axiom.CreateAPITokenResponse, "token"> & {
16 /**
17 * The bearer token. Returned only by `create` (and `regenerate`); Axiom
18 * does not return it on subsequent reads. Persisted in resource state via
19 * `Redacted` — handle with care.
20 */
21 token: Redacted.Redacted<string>;
22 },
23 never,
24 Providers
25 >;
26
27 /**
28 * An Axiom API token — a scoped bearer token used to authenticate API
29 * requests (ingest, query, admin). Capabilities are pinned at creation time;
30 * changing any field triggers a **replacement** because Axiom does not
31 * expose an update endpoint.
32 *
33 * The raw token value is returned only by `create`. After that, Axiom
34 * never echoes it back, so it is captured into `output.token` (as a
35 * {@link Redacted}) on initial create and persisted in resource state.
36 * Treat resource state as sensitive — anyone with read access can recover
37 * the token. Pair with a secret store for downstream consumption.
38 * @see https://axiom.co/docs/reference/tokens
39 *
40 * ### Creating an API Token
41 * **Example:** Ingest-only token scoped to one dataset
42 * ```typescript
43 * const ingest = yield* Axiom.ApiToken("ingest", {
44 * name: "prod-ingest",
45 * description: "OTEL collector ingest",
46 * datasetCapabilities: {
47 * "my-app-traces": { ingest: ["create"] },
48 * },
49 * });
50 * ```
51 *
52 * **Example:** Read-only query token
53 * ```typescript
54 * yield* Axiom.ApiToken("query", {
55 * name: "grafana-reader",
56 * datasetCapabilities: {
57 * "my-app-traces": { query: ["read"] },
58 * "my-app-logs": { query: ["read"] },
59 * },
60 * });
61 * ```
62 *
63 * ### Consuming the Token
64 * **Example:** Forward the token via Cloudflare Secrets
65 * ```typescript
66 * const secret = yield* Cloudflare.SecretsStore.Secret("axiom-token", {
67 * value: ingest.token,
68 * });
69 * ```
70 *
71 * @resource
72 * @product API Token
73 */
74 export const ApiToken = Resource<ApiToken>("Axiom.ApiToken");
75
76 /** Axiom created a token but returned no bearer value. */
77 export class MissingApiTokenValue extends Data.TaggedError("MissingApiTokenValue")<{
78 readonly id: string;
79 }> {
80 override get message() {
81 return `Axiom did not return a value for the new API token ${this.id}`;
82 }
83 }
84
85 export const ApiTokenProvider = () =>
86 Provider.effect(
87 ApiToken,
88 Effect.gen(function* () {
89 const create = yield* Axiom.createAPIToken;
90 const get = yield* Axiom.getAPIToken;
91 const del = yield* Axiom.deleteAPIToken;
92 const listTokens = yield* Axiom.getAPITokens;
93
94 return {
95 stables: ["id", "token"],
96 // Enumerate every API token in the org. Axiom exposes a single
97 // account-wide `GET /v2/tokens` collection op (no pagination), so we
98 // fetch it once and hydrate each row into the exact `read` Attributes
99 // shape. The bearer secret is returned by Axiom only at creation and is
100 // never echoed back on enumeration, so — matching `read`, which sources
101 // the secret from cached state — we surface an empty Redacted token
102 // here rather than the real value.
103 list: () =>
104 Effect.gen(function* () {
105 const tokens = yield* listTokens({});
106 return tokens.map((token) => ({
107 ...token,
108 token: Redacted.make(""),
109 }));
110 }),
111 diff: Effect.fn(function* ({ olds, news, output }) {
112 if (!isResolved(news)) return undefined;
113 // First create — let the engine create normally.
114 if (output == null) return undefined;
115 // Axiom has no update endpoint for tokens, so any actual change
116 // to the inputs forces a replacement (which mints a new bearer
117 // value). If nothing changed, fall through to `noop` so we don't
118 // needlessly rotate the token on every deploy.
119 if (deepEqual(olds, news)) return undefined;
120 return { action: "replace" } as const;
121 }),
122 reconcile: Effect.fn(function* ({ news, output }) {
123 // Observe — Axiom does not expose an update endpoint for tokens,
124 // so any actual change to the inputs is forced to a replacement
125 // by `diff` above. That means by the time `reconcile` runs we
126 // are either (a) creating fresh, or (b) re-reconciling identical
127 // inputs against an existing token.
128 if (output !== undefined) {
129 // Identical inputs — Axiom does not echo the bearer back, so
130 // the cached `output` (with the persisted Redacted token) is
131 // the authoritative current state.
132 return output;
133 }
134
135 // Ensure — mint a new token. Axiom returns the bearer exactly
136 // once; capture it into Redacted state for downstream consumers.
137 const result = yield* create(news);
138 if (!result.token) {
139 return yield* Effect.die(new MissingApiTokenValue({ id: result.id }));
140 }
141 return {
142 ...result,
143 token: Redacted.isRedacted(result.token) ? result.token : Redacted.make(result.token),
144 };
145 }),
146 delete: Effect.fn(function* ({ output }) {
147 yield* del({ id: output.id }).pipe(Effect.catchTag("NotFound", () => Effect.void));
148 }),
149 read: Effect.fn(function* ({ output }) {
150 if (!output?.id) return undefined;
151 return yield* get({ id: output.id }).pipe(
152 Effect.map((current) => ({ ...current, token: output.token })),
153 Effect.catchTag("NotFound", () => Effect.undefined),
154 );
155 }),
156 };
157 }),
158 );