Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 133 lines 5.95 KB
Raw
1 import { Config, Console, Effect, Option, Redacted, Schema } from 'effect';
2 import { FetchHttpClient, HttpClient, HttpClientRequest } from 'effect/http';
3 import { NPM_REGISTRY } from './lanes';
4 import { RELEASE_PUBLISHER } from './provenance';
5 import { isSuccess } from './registry-wait';
6 import { fail } from './runtime';
7
8 /** The runbook section on npm trusted publishers, linked from every npm login failure. */
9 export const NPM_TRUSTED_PUBLISHING_RUNBOOK = 'ts/docs/internal/release.md#npm-trusted-publishing';
10
11 /** Where an owner changes a package's trusted publisher; the npm CLI cannot change it. */
12 export const npmTrustedPublisherSettings = (name: string) =>
13 `npmjs.com → ${name} → Settings → Trusted publishing`;
14
15 const REQUEST_TIMEOUT = '30 seconds';
16
17 /** The audience npm requests the GitHub ID token for, as npm CLI 11.21.0 does. */
18 const AUDIENCE = `npm:${new URL(NPM_REGISTRY).hostname}`;
19
20 /** npm's per-package exchange endpoint; npm escapes only the scope's slash, as `%2f`. */
21 const exchangeUrl = (name: string) =>
22 `${NPM_REGISTRY}/-/npm/v1/oidc/token/exchange/package/${name.replaceAll('/', '%2f')}`;
23
24 const present = <A>(value: Option.Option<A>, text: (value: A) => string) =>
25 Option.filter(value, item => text(item) !== '');
26
27 const IdTokenRequest = Config.all({
28 url: Config.option(Config.String('ACTIONS_ID_TOKEN_REQUEST_URL')),
29 token: Config.option(Config.Redacted('ACTIONS_ID_TOKEN_REQUEST_TOKEN')),
30 });
31
32 const IdToken = Schema.fromJsonString(Schema.Struct({ value: Schema.NonEmptyString }));
33 const ExchangedToken = Schema.fromJsonString(Schema.Struct({ token: Schema.NonEmptyString }));
34 const NpmErrorBody = Schema.fromJsonString(Schema.Struct({ message: Schema.String }));
35
36 /**
37 * Sends one request and returns its status and body. Transport failures become a fixed message,
38 * so a request's credentials can never surface in an error.
39 */
40 const send = (request: HttpClientRequest.HttpClientRequest, failure: string) =>
41 Effect.gen(function* () {
42 const client = yield* HttpClient.HttpClient;
43 const response = yield* client.execute(request);
44 return { status: response.status, text: yield* response.text };
45 }).pipe(
46 Effect.provideService(FetchHttpClient.RequestInit, { redirect: 'error' }),
47 Effect.timeout(REQUEST_TIMEOUT),
48 Effect.catch(() => fail(failure))
49 );
50
51 /** Requests the GitHub ID token for npm, as npm does before trusted publishing. */
52 const githubIdToken = Effect.gen(function* () {
53 const env = yield* IdTokenRequest;
54 const url = present(env.url, value => value);
55 const token = present(env.token, Redacted.value);
56 if (Option.isNone(url) || Option.isNone(token))
57 return yield* fail(
58 'GitHub id-token permission missing: ACTIONS_ID_TOKEN_REQUEST_URL and ACTIONS_ID_TOKEN_REQUEST_TOKEN are unset, so npm trusted publishing cannot log in. The publish-npm job needs `permissions: id-token: write`.'
59 );
60 const target = new URL(url.value);
61 target.searchParams.append('audience', AUDIENCE);
62 const response = yield* send(
63 HttpClientRequest.get(target.href, {
64 headers: {
65 accept: 'application/json',
66 authorization: `Bearer ${Redacted.value(token.value)}`,
67 },
68 }),
69 'The GitHub OIDC ID token request did not answer'
70 );
71 const body = Schema.decodeUnknownOption(IdToken)(response.text);
72 if (!isSuccess(response.status) || Option.isNone(body))
73 return yield* fail(`GitHub did not issue an OIDC ID token for npm (${response.status})`);
74 return Redacted.make(body.value.value);
75 });
76
77 /** npm's reason for refusing an exchange: its `message`, else the body as it came. */
78 const npmReason = (text: string) =>
79 Option.match(Schema.decodeUnknownOption(NpmErrorBody)(text), {
80 onNone: () => text.trim() || 'empty response',
81 onSome: body => body.message,
82 });
83
84 /** One package's exchange; the exchanged token is checked for presence and then dropped. */
85 const exchange = (name: string, idToken: Redacted.Redacted<string>) =>
86 Effect.gen(function* () {
87 const response = yield* send(
88 HttpClientRequest.post(exchangeUrl(name), {
89 headers: { accept: 'application/json', authorization: `Bearer ${Redacted.value(idToken)}` },
90 }),
91 `The npm trusted-publishing exchange for ${name} did not answer`
92 );
93 if (
94 isSuccess(response.status) &&
95 Option.isSome(Schema.decodeUnknownOption(ExchangedToken)(response.text))
96 )
97 return Option.none<string>();
98 return Option.some(
99 isSuccess(response.status)
100 ? `${name} (${response.status}): npm answered without a token`
101 : `${name} (${response.status}): ${npmReason(response.text)}`
102 );
103 });
104
105 /**
106 * Logs in to npm through trusted publishing for every package, the way `npm publish` and
107 * `npm dist-tag` will, and prints npm's answer for each. Fails before anything is uploaded when
108 * npm refuses any of them, naming each package and npm's reason. Every planned package is
109 * checked, not only the ones still missing, because moving a dist-tag needs the same login.
110 */
111 export const checkNpmLogin = (names: ReadonlyArray<string>) =>
112 Effect.gen(function* () {
113 const idToken = yield* githubIdToken;
114 const refusals: string[] = [];
115 for (const name of names) {
116 const refusal = yield* exchange(name, idToken);
117 yield* Console.log(
118 Option.match(refusal, {
119 onNone: () => `npm trusted publishing accepted ${name}`,
120 onSome: reason => `npm trusted publishing refused ${reason}`,
121 })
122 );
123 if (Option.isSome(refusal)) refusals.push(refusal.value);
124 }
125 if (refusals.length > 0)
126 return yield* fail(
127 [
128 `npm refused the trusted-publishing login for ${refusals.length} of ${names.length} packages, so nothing was uploaded:`,
129 ...refusals.map(reason => ` ${reason}`),
130 `Check each package's trusted publisher (${npmTrustedPublisherSettings('<package>')}): repository ${RELEASE_PUBLISHER.repository}, workflow ${RELEASE_PUBLISHER.workflow}, environment npm-release. See ${NPM_TRUSTED_PUBLISHING_RUNBOOK}.`,
131 ].join('\n')
132 );
133 });