@effected/github-actions 0.24.0 → 0.26.0

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.
@@ -1,3 +1,4 @@
1
+ import { decodeJson } from "./internal/json.js";
1
2
  import { Context, Effect, FileSystem, Layer, Option, Schema } from "effect";
2
3
 
3
4
  // src/ActionEnvironment.ts
@@ -176,14 +177,11 @@ const make = (base) => Effect.gen(function* () {
176
177
  name: "GITHUB_EVENT_PATH",
177
178
  detail: `could not read "${path}": ${String(cause)}`
178
179
  })));
179
- return yield* Effect.try({
180
- try: () => JSON.parse(raw),
181
- catch: (cause) => new ActionEnvironmentError({
182
- reason: "malformed",
183
- name: "GITHUB_EVENT_PATH",
184
- detail: `not valid JSON: ${String(cause)}`
185
- })
186
- });
180
+ return yield* decodeJson(raw).pipe(Effect.mapError((cause) => new ActionEnvironmentError({
181
+ reason: "malformed",
182
+ name: "GITHUB_EVENT_PATH",
183
+ detail: `not valid JSON: ${cause.message}`
184
+ })));
187
185
  }),
188
186
  withEnv: (overrides, effect) => Effect.flatMap(EnvOverrides, (current) => Effect.provideService(effect, EnvOverrides, {
189
187
  ...current,
package/ActionInput.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { decodeJson } from "./internal/json.js";
1
2
  import { Config, ConfigProvider, Context, Effect, Schema, SchemaIssue } from "effect";
2
3
 
3
4
  // src/ActionInput.ts
@@ -29,7 +30,17 @@ const inputVariable = (name) => `INPUT_${name.replaceAll(" ", "_").toUpperCase()
29
30
  * mutations the author meant to rehearse. `actual` carries the offending value
30
31
  * so the rendered error names it.
31
32
  */
32
- const configError = (message, actual) => new Config.ConfigError(new Schema.SchemaError(new SchemaIssue.InvalidValue({ message }, actual)));
33
+ /**
34
+ * A `ConfigError` carrying `message` as its first issue and, when a decode
35
+ * failed, that decode's own issue beside it, so the cause is structured
36
+ * rather than flattened into the message.
37
+ */
38
+ const configError = (message, actual, cause) => {
39
+ const stated = new SchemaIssue.InvalidValue({ message }, actual);
40
+ return new Config.ConfigError(new Schema.SchemaError(cause === void 0 ? stated : new SchemaIssue.Composite(Schema.Unknown.ast, [stated, cause.issue], actual)));
41
+ };
42
+ /** The JSON-array form of {@link ActionInput.list}. */
43
+ const decodeStringArray = Schema.decodeUnknownEffect(Schema.Array(Schema.String));
33
44
  /** YAML 1.2 core-schema booleans, which is what the runner documents. */
34
45
  const TRUE = /* @__PURE__ */ new Set([
35
46
  "true",
@@ -267,13 +278,7 @@ var ActionInput = class ActionInput {
267
278
  return Config.String(inputVariable(name)).pipe(Config.mapEffect((raw) => {
268
279
  const trimmed = raw.trim();
269
280
  if (trimmed === "") return Effect.succeed([]);
270
- if (trimmed.startsWith("[")) try {
271
- const parsed = JSON.parse(trimmed);
272
- if (Array.isArray(parsed) && parsed.every((item) => typeof item === "string")) return Effect.succeed(parsed);
273
- return Effect.fail(configError(`Input "${name}" is a JSON array but not an array of strings`, raw));
274
- } catch {
275
- return Effect.fail(configError(`Input "${name}" looks like JSON but could not be parsed`, raw));
276
- }
281
+ if (trimmed.startsWith("[")) return decodeJson(trimmed).pipe(Effect.mapError((cause) => configError(`Input "${name}" looks like JSON but could not be parsed`, raw, cause)), Effect.flatMap((parsed) => decodeStringArray(parsed).pipe(Effect.mapError((cause) => configError(`Input "${name}" is a JSON array but not an array of strings`, raw, cause)))));
277
282
  const entries = trimmed.split(/[\n,]/).map((item) => item.trim()).filter((item) => !item.startsWith("#")).map((item) => item.startsWith("- ") || item.startsWith("* ") ? item.slice(2).trim() : item).filter((item) => item !== "");
278
283
  return Effect.succeed(entries);
279
284
  }));
@@ -332,15 +337,7 @@ var ActionInput = class ActionInput {
332
337
  * which is exactly the missing-versus-malformed split above.
333
338
  */
334
339
  static schema(name, schema) {
335
- return Config.String(inputVariable(name)).pipe(Config.mapEffect((raw) => {
336
- let parsed;
337
- try {
338
- parsed = JSON.parse(raw);
339
- } catch {
340
- return Effect.fail(configError(`Input "${name}" is not valid JSON`, raw));
341
- }
342
- return Schema.decodeUnknownEffect(schema)(parsed).pipe(Effect.mapError(() => configError(`Input "${name}" did not satisfy its schema`, parsed)));
343
- }));
340
+ return Config.String(inputVariable(name)).pipe(Config.mapEffect((raw) => decodeJson(raw).pipe(Effect.mapError((cause) => configError(`Input "${name}" is not valid JSON`, raw, cause)), Effect.flatMap((parsed) => Schema.decodeUnknownEffect(schema)(parsed).pipe(Effect.mapError((cause) => configError(`Input "${name}" did not satisfy its schema`, parsed, cause)))))));
344
341
  }
345
342
  /**
346
343
  * A `ConfigProvider` over a record of runner variables **or input names**.
package/ActionLogger.js CHANGED
@@ -97,6 +97,30 @@ const commandLogger = Logger.withConsoleLog(renderLogger);
97
97
  * @internal
98
98
  */
99
99
  const ActiveBuffer = Context.Reference("@effected/github-actions/ActiveBuffer", { defaultValue: () => null });
100
+ /**
101
+ * How many {@link ActionLoggerShape.group} calls the current fiber is inside.
102
+ *
103
+ * @remarks
104
+ * The runner does not nest groups: a second `::group::` implicitly ends the
105
+ * first, leaving an empty outer header and a stray `::endgroup::`. So only
106
+ * depth 0 writes the group commands, and a nested call writes a plain header
107
+ * line instead. Fiber-scoped for the same reason as {@link ActiveBuffer}: a
108
+ * `Context.Reference` is provided around the body, so it unwinds on every
109
+ * exit path with nothing to restore.
110
+ *
111
+ * @internal
112
+ */
113
+ const GroupDepth = Context.Reference("@effected/github-actions/GroupDepth", { defaultValue: () => 0 });
114
+ /**
115
+ * The line a nested group writes in place of a second `::group::`.
116
+ *
117
+ * @remarks
118
+ * Line breaks collapse to spaces so the header stays one line — the
119
+ * top-level form escapes them into one command — and the result is
120
+ * neutralized, because a group name is caller text and a `::` or `##[` in it
121
+ * would otherwise be a command.
122
+ */
123
+ const nestedHeader = (name) => CommandNeutralizer.text(`▸ ${name.replace(/\r\n|\r|\n/g, " ")}`);
100
124
  /** Drop a transcript without writing it, so a green step stays quiet. */
101
125
  const discard = (state) => Effect.sync(() => {
102
126
  state.entries.length = 0;
@@ -132,7 +156,10 @@ const make = Effect.gen(function* () {
132
156
  return yield* effect.pipe(Effect.provideService(References.MinimumLogLevel, "All"), Effect.provideService(Logger.CurrentLoggers, /* @__PURE__ */ new Set([buffering])), Effect.provideService(ActiveBuffer, state), Effect.onExit((exit) => Exit.isSuccess(exit) && options?.onSuccess === "discard" ? discard(state) : flush(state)));
133
157
  });
134
158
  return {
135
- group: (name, effect) => Effect.acquireUseRelease(Console.log(WorkflowCommand.group(name)), () => Effect.tapCause(effect, () => flushActive), () => Console.log(WorkflowCommand.endGroup())),
159
+ group: (name, effect) => Effect.flatMap(GroupDepth, (depth) => {
160
+ const body = Effect.tapCause(Effect.provideService(effect, GroupDepth, depth + 1), () => flushActive);
161
+ return depth === 0 ? Effect.acquireUseRelease(Console.log(WorkflowCommand.group(name)), () => body, () => Console.log(WorkflowCommand.endGroup())) : Effect.andThen(Console.log(nestedHeader(name)), body);
162
+ }),
136
163
  withBuffer,
137
164
  withStep: (name, effect, options) => withBuffer(name, Effect.tapCause(effect, () => Console.log(CommandNeutralizer.text(`❌ ${name}`))), { onSuccess: "discard" }).pipe(Effect.tap(() => Effect.logInfo(options?.summary ?? `✅ ${name}`))),
138
165
  notice: (message, properties = {}) => Console.log(WorkflowCommand.notice(message, properties)),
@@ -200,7 +227,8 @@ var ActionLogger = class ActionLogger extends Context.Service()("@effected/githu
200
227
  * {@link ActionEnvironment.makeTest}. A logger that dies when a suite logs
201
228
  * would make every double unusable, and silence is the honest default for a
202
229
  * service whose whole job is output. Group and buffer wrappers pass their
203
- * effect through unchanged.
230
+ * effect through unchanged, so the double does not model group nesting:
231
+ * a test of nested-group output needs the live {@link ActionLogger.layer}.
204
232
  */
205
233
  static makeTest = (overrides = {}) => ({
206
234
  group: (_name, effect) => effect,
@@ -1,16 +1,16 @@
1
1
  import { OidcTokenIssuer } from "./OidcTokenIssuer.js";
2
2
  import { Effect, Layer } from "effect";
3
- import { IdentityToken, IdentityTokenError } from "@effected/sbom";
3
+ import { IdentityToken, IdentityTokenError } from "@effected/oidc";
4
4
 
5
5
  // src/ActionsIdentityToken.ts
6
6
  /**
7
- * Serves `@effected/sbom`'s `IdentityToken` contract from the runner's own OIDC
7
+ * Serves `@effected/oidc`'s `IdentityToken` contract from the runner's own OIDC
8
8
  * token service, so signing an SBOM inside a workflow needs no further wiring.
9
9
  *
10
10
  * @remarks
11
- * `@effected/sbom` declares `IdentityToken` — one method, one audience,
12
- * one redacted token — precisely so that signing does not drag the Actions
13
- * runtime into every consumer that only wants to emit an SBOM. This is the
11
+ * `@effected/oidc` declares `IdentityToken` — one method, one audience,
12
+ * one redacted token — precisely so that a consumer of a token, such as
13
+ * `@effected/sbom`'s signer, does not drag the Actions runtime in. This is the
14
14
  * layer that closes the inversion from the other side: it serves that contract
15
15
  * from the runner's own OIDC token service ({@link OidcTokenIssuer}), the same
16
16
  * arrangement as `@effected/workspaces` implementing `@effected/commands`'
@@ -20,12 +20,14 @@ const DEFAULT_SERVER_URL = "https://github.com";
20
20
  *
21
21
  * @remarks
22
22
  * `SlsaProvenance.forGitHubWorkflow` is total and does the real work, but it
23
- * takes a camelCase input record — and the only input anyone inside a workflow
24
- * actually holds is the runner's own OIDC claims, spelled in GitHub's
25
- * snake_case claim names. The rename between the two is eleven all-string
26
- * fields, so transposing `repository_id` and `repository_owner_id` compiles,
27
- * passes every type check, and produces a validly signed attestation asserting
28
- * the **wrong** provenance. This module owns that rename once, on the same
23
+ * takes an all-string input record — and the only input anyone inside a
24
+ * workflow actually holds is the runner's own OIDC claims, decoded as
25
+ * `@effected/github`'s `ActionsOidcClaims` with integer ids. The projection
26
+ * between the two is eleven close-cousin fields, so transposing `repositoryId`
27
+ * and `repositoryOwnerId` compiles, passes every type check, and produces a
28
+ * validly signed attestation asserting the **wrong** provenance. This module
29
+ * owns that projection once, rendering the ids back to the decimal strings the
30
+ * token carried, on the same
29
31
  * `github-actions` ↔ `sbom` seam as {@link ActionsIdentityToken}: `sbom` must
30
32
  * not depend on the Actions runtime, so the adapter lives here, beside the
31
33
  * services it reads.
@@ -55,7 +57,7 @@ var ActionsProvenance = class {
55
57
  *
56
58
  * @remarks
57
59
  * Every field `GitHubWorkflowProvenance` declares is populated from
58
- * {@link OidcClaims}, except `serverUrl`, which is read from
60
+ * the runner's `ActionsOidcClaims`, except `serverUrl`, which is read from
59
61
  * `GITHUB_SERVER_URL` through {@link ActionEnvironment}'s `getOptional`
60
62
  * with `https://github.com` as the default — **not** through the
61
63
  * `GitHubContext` projection. The projection fails typed when a `GITHUB_*`
@@ -88,14 +90,14 @@ var ActionsProvenance = class {
88
90
  repository: claims.repository,
89
91
  ref: claims.ref,
90
92
  sha: claims.sha,
91
- eventName: claims.event_name,
92
- workflowRef: claims.workflow_ref,
93
- jobWorkflowRef: claims.job_workflow_ref,
94
- repositoryId: claims.repository_id,
95
- repositoryOwnerId: claims.repository_owner_id,
96
- runnerEnvironment: claims.runner_environment,
97
- runId: claims.run_id,
98
- runAttempt: claims.run_attempt
93
+ eventName: claims.eventName,
94
+ workflowRef: claims.workflowRef,
95
+ jobWorkflowRef: claims.jobWorkflowRef,
96
+ repositoryId: String(claims.repositoryId),
97
+ repositoryOwnerId: String(claims.repositoryOwnerId),
98
+ runnerEnvironment: claims.runnerEnvironment,
99
+ runId: String(claims.runId),
100
+ runAttempt: String(claims.runAttempt)
99
101
  });
100
102
  });
101
103
  };
@@ -0,0 +1,81 @@
1
+ import { OidcTokenIssuer } from "./OidcTokenIssuer.js";
2
+ import { Secret } from "./Secret.js";
3
+ import { Effect } from "effect";
4
+ import { workloadCredential } from "@effected/npm";
5
+
6
+ // src/ActionsRegistryCredential.ts
7
+ /**
8
+ * Registry credentials minted from the runner's own workload identity.
9
+ *
10
+ * @remarks
11
+ * The GitHub Actions half of `@effected/npm`'s workload credential. npm owns
12
+ * the credential's shape and the npmrc write and takes no Actions edge, so it
13
+ * cannot mint or mask; this class does both, so a consumer never holds the
14
+ * identity token or the prefixed value as plaintext and never reaches for
15
+ * `Secret.forSigning` to build one.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * import { ActionsRegistryCredential } from "@effected/github-actions";
20
+ * import { PackagePublish } from "@effected/npm";
21
+ * import { Effect } from "effect";
22
+ *
23
+ * const program = Effect.gen(function* () {
24
+ * const credential = yield* ActionsRegistryCredential.workload({
25
+ * audience: "https://registry.example",
26
+ * prefix: "example_workload_",
27
+ * });
28
+ * const publish = yield* PackagePublish;
29
+ * yield* publish.setupAuth({
30
+ * registry: "https://registry.example/npm",
31
+ * credential,
32
+ * npmrcPath: "/home/runner/.npmrc",
33
+ * });
34
+ * });
35
+ * ```
36
+ *
37
+ * @public
38
+ */
39
+ var ActionsRegistryCredential = class {
40
+ constructor() {}
41
+ /**
42
+ * Mint a workload identity token for `audience`, mask it and its prefixed
43
+ * form, and return `@effected/npm`'s `WorkloadCredential`.
44
+ *
45
+ * @remarks
46
+ * In order: the runner's {@link OidcTokenIssuer} mints a token for
47
+ * `audience` (verbatim — it is the registry's own audience, and a token
48
+ * minted for another is refused); the bare token is masked; npm's
49
+ * `workloadCredential` prefixes it; the prefixed value is masked too,
50
+ * because the runner's log filter matches whole registered values and the
51
+ * prefixed form is a new one. Both masks are emitted before the credential
52
+ * is returned, so no later step — the npm subprocess included — can print
53
+ * either value in clear.
54
+ *
55
+ * A mint failure stays an {@link OidcTokenError}, distinct from a later
56
+ * `PublishError` of kind `"auth"` from `setupAuth`, so a caller can tell
57
+ * "the runner refused an identity token" from "the npmrc could not be
58
+ * written". On an issuer failure nothing is masked and nothing is built.
59
+ *
60
+ * **In a detached worker the masks are a leak**, exactly as for
61
+ * {@link Secret.mask}: mint in the parent, where the runner parses stdout.
62
+ *
63
+ * @param options - `audience` for the identity token; `prefix` is the
64
+ * registry's token prefix, an open string because the vocabulary belongs
65
+ * to the registry, not to this kit.
66
+ */
67
+ static workload = Effect.fn("ActionsRegistryCredential.workload")(function* (options) {
68
+ yield* Effect.annotateCurrentSpan({ audience: options.audience });
69
+ const identityToken = yield* (yield* OidcTokenIssuer).token(options.audience);
70
+ yield* Secret.mask(identityToken);
71
+ const credential = workloadCredential({
72
+ audience: options.audience,
73
+ prefix: options.prefix,
74
+ identityToken
75
+ });
76
+ yield* Secret.mask(credential.token);
77
+ return credential;
78
+ });
79
+ };
80
+
81
+ export { ActionsRegistryCredential };
package/Artifact.js CHANGED
@@ -7,7 +7,7 @@ import { digestFileHex } from "./internal/digest.js";
7
7
  import { isWindowsRunner } from "./internal/runner.js";
8
8
  import { spawnOnce } from "./internal/spawn.js";
9
9
  import { unzipCommand, zipCommand, zipManifest } from "./internal/archiveCommands.js";
10
- import { Context, Effect, FileSystem, Layer, Option, Path, Result, Schema } from "effect";
10
+ import { Context, DateTime, Duration, Effect, FileSystem, Layer, Option, Path, Result, Schema } from "effect";
11
11
  import { HttpClient } from "effect/http";
12
12
  import { BlobClient, BlockBlobClient } from "@azure/storage-blob";
13
13
  import { ChildProcessSpawner } from "effect/process";
@@ -263,11 +263,12 @@ const make = (transfer) => Effect.gen(function* () {
263
263
  cause
264
264
  })));
265
265
  const digest = yield* digestOf(packed, name);
266
+ const expiresAt = options?.retentionDays === void 0 ? void 0 : DateTime.formatIso(DateTime.addDuration(yield* DateTime.now, Duration.days(options.retentionDays)));
266
267
  const finalized = yield* call("FinalizeArtifact", () => ({
267
268
  name,
268
269
  size: String(size.size),
269
270
  hash: `sha256:${digest}`,
270
- ...options?.retentionDays === void 0 ? {} : { expiresAt: new Date(Date.now() + options.retentionDays * 864e5).toISOString() }
271
+ ...expiresAt === void 0 ? {} : { expiresAt }
271
272
  }), name);
272
273
  if (finalized === CONFLICT || !isOk(finalized)) return yield* Effect.fail(new ArtifactError({
273
274
  reason: "refused",
package/BlobStore.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { unstubbed } from "./internal/unstubbed.js";
2
- import { BlobEnvelope } from "./BlobEnvelope.js";
3
- import { sign } from "./internal/sigv4.js";
4
2
  import { Secret } from "./Secret.js";
5
- import { Context, Effect, Layer, Option, Schema } from "effect";
3
+ import { BlobEnvelope } from "./BlobEnvelope.js";
4
+ import { Context, Crypto, DateTime, Effect, Layer, Option, Schema } from "effect";
6
5
  import { HttpClient, HttpClientRequest } from "effect/http";
6
+ import { SigV4 } from "@effected/crypto";
7
7
 
8
8
  // src/BlobStore.ts
9
9
  /**
@@ -15,12 +15,17 @@ var BlobStoreError = class extends Schema.TaggedError()("BlobStoreError", {
15
15
  /**
16
16
  * `unreachable` — the store could not be contacted. `refused` — it answered,
17
17
  * unhappily; `status` says how. `misconfigured` — the layer was built with
18
- * settings the store cannot use.
18
+ * settings the store cannot use, or a request could not be signed with them
19
+ * (no WebCrypto in the runtime, or key material it refuses). `invalidKey` —
20
+ * the caller's key cannot be stored at all, whatever the settings: on S3, a
21
+ * key with a `.` or `..` path segment, which no URL carries as signed.
22
+ * Nothing is sent.
19
23
  */
20
24
  reason: Schema.Literals([
21
25
  "unreachable",
22
26
  "refused",
23
- "misconfigured"
27
+ "misconfigured",
28
+ "invalidKey"
24
29
  ]),
25
30
  /** The key involved. A stable identifier, never a value. */
26
31
  key: Schema.optionalKey(Schema.String),
@@ -35,6 +40,7 @@ var BlobStoreError = class extends Schema.TaggedError()("BlobStoreError", {
35
40
  switch (this.reason) {
36
41
  case "unreachable": return `The blob store could not be reached${this.key === void 0 ? "" : ` for "${this.key}"`}`;
37
42
  case "refused": return `The blob store refused "${this.key}"${this.status === void 0 ? "" : ` with status ${this.status}`}${this.detail === void 0 ? "" : `: ${this.detail}`}`;
43
+ case "invalidKey": return `The blob store cannot hold the key "${this.key}"${this.detail === void 0 ? "" : `: ${this.detail}`}`;
38
44
  default: return `The blob store is misconfigured${this.detail === void 0 ? "" : `: ${this.detail}`}`;
39
45
  }
40
46
  }
@@ -75,10 +81,17 @@ var BlobStore = class BlobStore extends Context.Service()("@effected/github-acti
75
81
  * An S3-compatible backend, signed with SigV4.
76
82
  *
77
83
  * @remarks
78
- * No `@aws-sdk/*` dependency: signing is a specified algorithm over strings
79
- * and HMACs, and this package already has `node:crypto`. The SDK's weight is
80
- * in credential management, retries and a service catalogue none of which
81
- * this needs.
84
+ * No `@aws-sdk/*` dependency: signing is `@effected/crypto`'s `SigV4`, a
85
+ * specified algorithm over strings and HMACs. The SDK's weight is in
86
+ * credential management, retries and a service catalogue none of which this
87
+ * needs.
88
+ *
89
+ * Requires core `Crypto` for the SHA-256 digests signing takes, resolved
90
+ * once when the layer is built; `NodeServices.layer` supplies it. A request
91
+ * that cannot be signed fails as {@link BlobStoreError} `misconfigured`. A
92
+ * key with a `.` or `..` path segment fails as `invalidKey` before anything
93
+ * is signed or sent: every URL parser collapses such a segment, so the store
94
+ * would receive another path than the one signed.
82
95
  *
83
96
  * A parameterized layer factory mints a fresh layer per call and layers
84
97
  * memoize by reference — bind it to a `const` rather than calling it at each
@@ -119,43 +132,60 @@ var BlobStore = class BlobStore extends Context.Service()("@effected/github-acti
119
132
  };
120
133
  const dies = unstubbed("BlobStore.makeTest");
121
134
  const makeS3 = (config) => Effect.gen(function* () {
122
- const http = yield* HttpClient.HttpClient;
135
+ const http = HttpClient.transform(yield* HttpClient.HttpClient, (effect) => Effect.provideService(effect, HttpClient.TracerPropagationEnabled, false));
136
+ const crypto = yield* Crypto.Crypto;
123
137
  let endpoint = config.endpoint ?? `https://s3.${config.region}.amazonaws.com`;
124
138
  while (endpoint.endsWith("/")) endpoint = endpoint.slice(0, -1);
125
139
  const host = new URL(endpoint).host;
126
- const secretAccessKey = yield* Secret.forSigning(config.secretAccessKey);
127
- const sessionToken = config.sessionToken === void 0 ? void 0 : yield* Secret.forSigning(config.sessionToken);
140
+ yield* Secret.mask(config.secretAccessKey);
141
+ if (config.sessionToken !== void 0) yield* Secret.mask(config.sessionToken);
142
+ const credentials = {
143
+ accessKeyId: config.accessKeyId,
144
+ secretAccessKey: config.secretAccessKey,
145
+ ...config.sessionToken === void 0 ? {} : { sessionToken: config.sessionToken },
146
+ region: config.region,
147
+ service: "s3"
148
+ };
128
149
  const objectPath = (key) => [
129
150
  config.bucket,
130
151
  ...config.prefix === void 0 ? [] : [config.prefix],
131
152
  key
132
153
  ].join("/").replaceAll(/\/{2,}/g, "/");
133
- const request = (method, key, body) => {
154
+ const unsignable = (key, cause) => new BlobStoreError({
155
+ reason: "misconfigured",
156
+ key,
157
+ detail: "the request could not be signed",
158
+ cause
159
+ });
160
+ const request = (method, key, body) => Effect.gen(function* () {
134
161
  const path = objectPath(key);
135
- const headers = sign({
162
+ const now = yield* DateTime.now;
163
+ const signed = yield* SigV4.sign({
136
164
  method,
137
165
  path,
138
166
  host,
139
- headers: {},
140
167
  body,
141
- now: /* @__PURE__ */ new Date()
142
- }, {
143
- accessKeyId: config.accessKeyId,
144
- secretAccessKey,
145
- ...sessionToken === void 0 ? {} : { sessionToken },
146
- region: config.region,
147
- service: "s3"
148
- });
168
+ now
169
+ }, credentials).pipe(Effect.provideService(Crypto.Crypto, crypto), Effect.catchTags({
170
+ SigV4PathError: (cause) => Effect.fail(new BlobStoreError({
171
+ reason: "invalidKey",
172
+ key,
173
+ detail: `the path has a "${cause.segment}" segment, which a URL collapses, so it cannot be sent as signed`,
174
+ cause
175
+ })),
176
+ CryptoError: (cause) => Effect.fail(unsignable(key, cause)),
177
+ PlatformError: (cause) => Effect.fail(unsignable(key, cause))
178
+ }));
149
179
  return {
150
- url: `${endpoint}/${path}`,
151
- headers
180
+ url: `${endpoint}${signed.path}${signed.query === "" ? "" : `?${signed.query}`}`,
181
+ headers: signed.headers
152
182
  };
153
- };
154
- const send = (method, key, body) => Effect.suspend(() => {
155
- const { url, headers } = request(method, key, body);
183
+ });
184
+ const send = (method, key, body) => Effect.gen(function* () {
185
+ const { url, headers } = yield* request(method, key, body);
156
186
  const base = HttpClientRequest.make(method)(url, { headers });
157
187
  const built = body.length === 0 ? base : HttpClientRequest.bodyUint8Array(base, body);
158
- return http.execute(built).pipe(Effect.mapError((cause) => new BlobStoreError({
188
+ return yield* http.execute(built).pipe(Effect.mapError((cause) => new BlobStoreError({
159
189
  reason: "unreachable",
160
190
  key,
161
191
  cause
@@ -1,8 +1,10 @@
1
1
  import { ActionEnvironment } from "./ActionEnvironment.js";
2
2
  import { unstubbed } from "./internal/unstubbed.js";
3
- import { payloadOf, unsignedJwt } from "./internal/jwt.js";
4
3
  import { Context, Effect, Layer, Redacted, Schema } from "effect";
5
4
  import { HttpClient, HttpClientRequest } from "effect/http";
5
+ import { Oidc } from "@effected/oidc";
6
+ import { ActionsOidcClaimsFromWire } from "@effected/github";
7
+ import * as Base64Url from "effect/encoding/Base64Url";
6
8
  import * as HttpClientResponse from "effect/http/HttpClientResponse";
7
9
 
8
10
  // src/OidcTokenIssuer.ts
@@ -45,44 +47,6 @@ var OidcTokenError = class extends Schema.TaggedError()("OidcTokenError", {
45
47
  }
46
48
  }
47
49
  };
48
- /**
49
- * The claims a GitHub Actions OIDC token carries about the workflow that ran.
50
- *
51
- * @remarks
52
- * The field names are GitHub's own JWT claim names, kept verbatim rather than
53
- * translated to the kit's casing. They are an **external vocabulary** — the
54
- * same strings that appear in a SLSA provenance predicate and in every
55
- * published example of an Actions OIDC policy — and renaming them would put a
56
- * translation layer between a consumer and the specification they are reading.
57
- *
58
- * @public
59
- */
60
- var OidcClaims = class extends Schema.Class("OidcClaims")({
61
- /** The issuer, e.g. `https://token.actions.githubusercontent.com`. */
62
- iss: Schema.String,
63
- /** The full ref the workflow ran on. */
64
- ref: Schema.String,
65
- /** The commit. */
66
- sha: Schema.String,
67
- /** `owner/repo`. */
68
- repository: Schema.String,
69
- /** The event that triggered the run. */
70
- event_name: Schema.String,
71
- /** The reusable-workflow ref, which is what a verifier pins against. */
72
- job_workflow_ref: Schema.String,
73
- /** The calling workflow's ref. */
74
- workflow_ref: Schema.String,
75
- /** The numeric repository id, as a string. */
76
- repository_id: Schema.String,
77
- /** The numeric owner id, as a string. */
78
- repository_owner_id: Schema.String,
79
- /** `github-hosted` or `self-hosted`. */
80
- runner_environment: Schema.String,
81
- /** The run id, as a string. */
82
- run_id: Schema.String,
83
- /** The run attempt, as a string. */
84
- run_attempt: Schema.String
85
- }) {};
86
50
  /** The token envelope the runner's token service answers with. */
87
51
  const TokenEnvelope = Schema.Struct({
88
52
  value: Schema.String,
@@ -97,16 +61,23 @@ const REQUEST_URL = "ACTIONS_ID_TOKEN_REQUEST_URL";
97
61
  * The absence of verification is deliberate and is documented on
98
62
  * {@link OidcTokenIssuerShape.claims}; do not "fix" it here.
99
63
  */
100
- const readClaims = (token) => Effect.gen(function* () {
101
- const decoded = yield* Effect.fromResult(payloadOf(token)).pipe(Effect.mapError((failure) => new OidcTokenError({
102
- reason: "malformedToken",
103
- ...failure
104
- })));
105
- return yield* Schema.decodeUnknownEffect(OidcClaims)(decoded).pipe(Effect.mapError((cause) => new OidcTokenError({
106
- reason: "missingClaims",
107
- cause
108
- })));
109
- });
64
+ const readClaims = (token) => Oidc.decodeUnverified(token, ActionsOidcClaimsFromWire).pipe(Effect.mapError((error) => error.reason === "claims" ? new OidcTokenError({
65
+ reason: "missingClaims",
66
+ cause: error.cause ?? error
67
+ }) : new OidcTokenError({
68
+ reason: "malformedToken",
69
+ detail: error.detail,
70
+ cause: error
71
+ })));
72
+ /**
73
+ * An **unsigned** JWT: `header.payload.unsigned`, each JSON segment
74
+ * base64url-encoded. For test doubles only; the signature segment is a
75
+ * placeholder, so the token fails any verifier.
76
+ */
77
+ const unsignedJwt = (header, payload) => {
78
+ const segment = (value) => Base64Url.encode(JSON.stringify(value));
79
+ return `${segment(header)}.${segment(payload)}.unsigned`;
80
+ };
110
81
  const make = Effect.gen(function* () {
111
82
  const env = yield* ActionEnvironment;
112
83
  const http = yield* HttpClient.HttpClient;
@@ -166,7 +137,7 @@ const dies = unstubbed("OidcTokenIssuer.makeTest");
166
137
  * const program = Effect.gen(function* () {
167
138
  * const issuer = yield* OidcTokenIssuer;
168
139
  * const claims = yield* issuer.claims("sigstore");
169
- * return claims.job_workflow_ref;
140
+ * return claims.jobWorkflowRef;
170
141
  * });
171
142
  * ```
172
143
  *
@@ -193,7 +164,7 @@ var OidcTokenIssuer = class OidcTokenIssuer extends Context.Service()("@effected
193
164
  static unsignedTokenFor = (claims) => Redacted.make(unsignedJwt({
194
165
  alg: "RS256",
195
166
  typ: "JWT"
196
- }, Schema.encodeUnknownSync(OidcClaims)(claims)));
167
+ }, Schema.encodeSync(ActionsOidcClaimsFromWire)(claims)));
197
168
  /** A test double. Unstubbed members die rather than answering with a non-token. */
198
169
  static makeTest = (overrides = {}) => ({
199
170
  token: () => dies("token"),
@@ -216,6 +187,51 @@ var OidcTokenIssuer = class OidcTokenIssuer extends Context.Service()("@effected
216
187
  token: () => Effect.succeed(OidcTokenIssuer.unsignedTokenFor(claims)),
217
188
  claims: () => Effect.succeed(claims)
218
189
  });
190
+ /**
191
+ * A {@link OidcTokenIssuer.layerFor} double that also records the audience
192
+ * every call asked for.
193
+ *
194
+ * @remarks
195
+ * A sibling of `layerTest` rather than a recording `layerTest`, following
196
+ * `ActionOutputs.recording`: the doubles here are override-and-die, and a
197
+ * recorder is a different contract. The audience is the one input a token
198
+ * request carries, and a token minted for the wrong audience is refused by
199
+ * the party it was meant for — so "which audience did this ask for" is
200
+ * worth an assertion rather than an assumption.
201
+ *
202
+ * Each call returns a fresh journal and a fresh layer: bind the result to a
203
+ * `const` and provide its `layer` once.
204
+ *
205
+ * @example
206
+ * ```ts
207
+ * import type { ActionsOidcClaims } from "@effected/github";
208
+ * import { OidcTokenIssuer } from "@effected/github-actions";
209
+ * import { Effect } from "effect";
210
+ *
211
+ * declare const claims: ActionsOidcClaims;
212
+ * const recorder = OidcTokenIssuer.recording(claims);
213
+ * const program = Effect.gen(function* () {
214
+ * const issuer = yield* OidcTokenIssuer;
215
+ * yield* issuer.token("https://registry.example");
216
+ * return recorder.audiences();
217
+ * });
218
+ * Effect.runPromise(Effect.provide(program, recorder.layer)).then(console.log);
219
+ * // => ["https://registry.example"]
220
+ * ```
221
+ */
222
+ static recording = (claims) => {
223
+ const audiences = [];
224
+ const record = (audience) => Effect.sync(() => {
225
+ audiences.push(audience);
226
+ });
227
+ return {
228
+ layer: Layer.succeed(OidcTokenIssuer, {
229
+ token: (audience) => Effect.as(record(audience), OidcTokenIssuer.unsignedTokenFor(claims)),
230
+ claims: (audience) => Effect.as(record(audience), claims)
231
+ }),
232
+ audiences: () => audiences.slice()
233
+ };
234
+ };
219
235
  };
220
236
 
221
- export { OidcClaims, OidcTokenError, OidcTokenIssuer };
237
+ export { OidcTokenError, OidcTokenIssuer };