@foldrun/core 9.2.1 → 9.4.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.
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/src/oauth-discovery.d.ts +90 -0
- package/dist/src/oauth-discovery.js +168 -0
- package/dist/src/oauth-token.d.ts +51 -0
- package/dist/src/oauth-token.js +169 -0
- package/dist/src/secrets.d.ts +58 -0
- package/dist/src/secrets.js +139 -7
- package/dist/src/untrusted-fetch.d.ts +4 -0
- package/dist/src/untrusted-fetch.js +1 -1
- package/index.ts +2 -0
- package/package.json +1 -1
- package/src/oauth-discovery.ts +208 -0
- package/src/oauth-token.ts +180 -0
- package/src/secrets.ts +153 -13
- package/src/untrusted-fetch.ts +5 -1
package/dist/src/secrets.js
CHANGED
|
@@ -23,6 +23,8 @@ import path from "node:path";
|
|
|
23
23
|
import { dataRoot } from "./paths.js";
|
|
24
24
|
import { platform } from "./platform.js";
|
|
25
25
|
import { fetchUntrusted } from "./untrusted-fetch.js";
|
|
26
|
+
import { oauthTokenRequest, readTokenResponse, tokenAuthProblem } from "./oauth-token.js";
|
|
27
|
+
import { isSecureUrl } from "./oauth-discovery.js";
|
|
26
28
|
/**
|
|
27
29
|
* GCM's auth tag, pinned to its full 16 bytes at every cipher call. Without
|
|
28
30
|
* `authTagLength`, Node accepts whatever length `setAuthTag` is handed — 4, 8,
|
|
@@ -821,9 +823,15 @@ export function setOAuth2Secret(tenant, name, config, workspace, limit = {}) {
|
|
|
821
823
|
if (config.grant_type !== "client_credentials" && !config.refresh_token?.trim()) {
|
|
822
824
|
throw new Error("oauth2 secret needs refresh_token (or grant_type: client_credentials)");
|
|
823
825
|
}
|
|
826
|
+
if (config.revocation_url !== undefined && (typeof config.revocation_url !== "string" || !isSecureUrl(config.revocation_url))) {
|
|
827
|
+
throw new Error("revocation_url must be https");
|
|
828
|
+
}
|
|
829
|
+
const authProblem = tokenAuthProblem(config);
|
|
830
|
+
if (authProblem)
|
|
831
|
+
throw new Error(`oauth2 secret: ${authProblem}`);
|
|
824
832
|
// Loopback is exempt: a token endpoint on this same machine (tests, a
|
|
825
833
|
// local mock, a sidecar) crosses no wire for http to leak on.
|
|
826
|
-
if (
|
|
834
|
+
if (!isSecureUrl(config.token_url)) {
|
|
827
835
|
throw new Error("token_url must be https — a refresh token over http is a leaked one");
|
|
828
836
|
}
|
|
829
837
|
setSecret(tenant, name, OAUTH2_PREFIX + JSON.stringify(config), workspace, "oauth2", limit);
|
|
@@ -898,11 +906,11 @@ async function exchange(config, cacheKey) {
|
|
|
898
906
|
if (pending)
|
|
899
907
|
return pending;
|
|
900
908
|
const flight = (async () => {
|
|
901
|
-
|
|
909
|
+
// One builder for every token request (oauth-token.ts): the client's
|
|
910
|
+
// identity goes where its token_auth says, and an `extra` cannot set it.
|
|
911
|
+
const request = oauthTokenRequest(config, {
|
|
902
912
|
grant_type: config.grant_type ?? "refresh_token",
|
|
903
913
|
...(config.grant_type === "client_credentials" ? {} : { refresh_token: config.refresh_token }),
|
|
904
|
-
client_id: config.client_id,
|
|
905
|
-
...(config.client_secret ? { client_secret: config.client_secret } : {}),
|
|
906
914
|
...(config.extra ?? {}),
|
|
907
915
|
});
|
|
908
916
|
// A network blip is retried; a provider's answer is not. "fetch failed"
|
|
@@ -918,8 +926,8 @@ async function exchange(config, cacheKey) {
|
|
|
918
926
|
try {
|
|
919
927
|
res = await fetchUntrusted(config.token_url, {
|
|
920
928
|
method: "POST",
|
|
921
|
-
headers:
|
|
922
|
-
body: body
|
|
929
|
+
headers: request.headers,
|
|
930
|
+
body: request.body,
|
|
923
931
|
signal: AbortSignal.timeout(15_000),
|
|
924
932
|
}, { sameOrigin: true });
|
|
925
933
|
}
|
|
@@ -934,7 +942,8 @@ async function exchange(config, cacheKey) {
|
|
|
934
942
|
}
|
|
935
943
|
if (!res)
|
|
936
944
|
throw lastNetwork instanceof Error ? lastNetwork : new Error(String(lastNetwork));
|
|
937
|
-
|
|
945
|
+
// JSON or form-encoded, Slack's nested user token, expires_in as a string.
|
|
946
|
+
const payload = readTokenResponse(await res.text().catch(() => ""), res.headers.get("content-type") ?? "");
|
|
938
947
|
if (!res.ok || !payload.access_token) {
|
|
939
948
|
throw new Error(`token refresh failed (${res.status}): ${payload.error_description ?? payload.error ?? "no access_token in the reply"}`);
|
|
940
949
|
}
|
|
@@ -956,6 +965,129 @@ async function exchange(config, cacheKey) {
|
|
|
956
965
|
oauthFlight.delete(cacheKey);
|
|
957
966
|
}
|
|
958
967
|
}
|
|
968
|
+
// ---------------------------------------------------------------- revocation
|
|
969
|
+
/** The oauth2 recipe stored at exactly this scope — never the account copy a
|
|
970
|
+
* workspace would fall back to: revoking is about the copy being removed. */
|
|
971
|
+
export function oauth2ValueAt(tenant, name, workspace) {
|
|
972
|
+
const v = openRecord(tenant, workspace, name, read(tenant, workspace)[name]);
|
|
973
|
+
return v !== null && isOAuth2Value(v) ? v : null;
|
|
974
|
+
}
|
|
975
|
+
/** The workspaces with a vault file of their own (current and legacy layout). */
|
|
976
|
+
function workspacesWithSecrets(tenant) {
|
|
977
|
+
const out = new Set();
|
|
978
|
+
for (const dir of ["workspaces", "projects"]) {
|
|
979
|
+
const base = path.join(dataRoot(), tenant, dir);
|
|
980
|
+
let names = [];
|
|
981
|
+
try {
|
|
982
|
+
names = fs.readdirSync(base);
|
|
983
|
+
}
|
|
984
|
+
catch {
|
|
985
|
+
continue;
|
|
986
|
+
}
|
|
987
|
+
for (const n of names)
|
|
988
|
+
if (fs.existsSync(path.join(base, n, "secrets.json")))
|
|
989
|
+
out.add(n);
|
|
990
|
+
}
|
|
991
|
+
return [...out];
|
|
992
|
+
}
|
|
993
|
+
/**
|
|
994
|
+
* Another stored secret of this account holds a grant revoking this one could
|
|
995
|
+
* end: the same refresh token (a copy made by hand, or one rotation reached),
|
|
996
|
+
* or any grant from the same app (token URL and client id). Providers such as
|
|
997
|
+
* Google revoke every token of a user's grant to an app together, so deleting
|
|
998
|
+
* the Ads connection would take down the Search Console one made with the
|
|
999
|
+
* same app (Codex review, 1 Nov 2026). Such a grant is left alone.
|
|
1000
|
+
*/
|
|
1001
|
+
export function oauthGrantSharedElsewhere(tenant, name, workspace, refreshToken, app) {
|
|
1002
|
+
for (const scope of [undefined, ...workspacesWithSecrets(tenant)]) {
|
|
1003
|
+
for (const [other, rec] of Object.entries(read(tenant, scope))) {
|
|
1004
|
+
if (other === name && scope === workspace)
|
|
1005
|
+
continue;
|
|
1006
|
+
// By the value, not the optional kind tag: a recipe copied with a
|
|
1007
|
+
// plain setSecret is still one materializeSecrets refreshes.
|
|
1008
|
+
const v = openRecord(tenant, scope, other, rec);
|
|
1009
|
+
if (!v || !isOAuth2Value(v))
|
|
1010
|
+
continue;
|
|
1011
|
+
try {
|
|
1012
|
+
const other = JSON.parse(v.slice(OAUTH2_PREFIX.length));
|
|
1013
|
+
if (other.refresh_token === refreshToken)
|
|
1014
|
+
return true;
|
|
1015
|
+
if (app && other.grant_type !== "client_credentials" && other.token_url === app.token_url && other.client_id === app.client_id)
|
|
1016
|
+
return true;
|
|
1017
|
+
}
|
|
1018
|
+
catch {
|
|
1019
|
+
continue;
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
return false;
|
|
1024
|
+
}
|
|
1025
|
+
/**
|
|
1026
|
+
* Revoke what an oauth2 recipe holds at its provider (RFC 7009): the refresh
|
|
1027
|
+
* token, then the access token this process has cached for it. The client
|
|
1028
|
+
* authenticates as at the token URL (its token_auth). A 200 is success —
|
|
1029
|
+
* the RFC answers 200 for a token already invalid too; anything else is
|
|
1030
|
+
* reported in `error`, and the next token is still tried. `replacement`: the
|
|
1031
|
+
* recipe taking this one's place; one from the same app (token URL and client
|
|
1032
|
+
* id) means nothing is revoked, since a provider that revokes per app would
|
|
1033
|
+
* end the new grant with the old.
|
|
1034
|
+
*/
|
|
1035
|
+
export async function revokeOAuth2Value(value, opts = {}) {
|
|
1036
|
+
let config;
|
|
1037
|
+
try {
|
|
1038
|
+
config = JSON.parse(value.slice(OAUTH2_PREFIX.length));
|
|
1039
|
+
}
|
|
1040
|
+
catch {
|
|
1041
|
+
return { skipped: "unreadable", revoked: [] };
|
|
1042
|
+
}
|
|
1043
|
+
if (!config.revocation_url)
|
|
1044
|
+
return { skipped: "no-revocation-url", revoked: [] };
|
|
1045
|
+
if (opts.replacement && opts.replacement.token_url === config.token_url && opts.replacement.client_id === config.client_id) {
|
|
1046
|
+
return { skipped: "same-app", revoked: [] };
|
|
1047
|
+
}
|
|
1048
|
+
if (config.grant_type !== "client_credentials" && opts.tenant && opts.name
|
|
1049
|
+
&& oauthGrantSharedElsewhere(opts.tenant, opts.name, opts.workspace, config.refresh_token ?? "", { token_url: config.token_url, client_id: config.client_id })) {
|
|
1050
|
+
return { skipped: "shared-grant", revoked: [] };
|
|
1051
|
+
}
|
|
1052
|
+
// No redirect is followed: a 3xx is not ok, so a revocation endpoint that
|
|
1053
|
+
// sends us to a login page is reported, never counted as revoked.
|
|
1054
|
+
const fetcher = opts.fetcher ?? ((url, init) => fetchUntrusted(url, init, { sameOrigin: true, noRedirects: true }));
|
|
1055
|
+
const key = tokenCacheKey("oauth2", value, opts.tenant);
|
|
1056
|
+
const access = oauthCache.get(key)?.token;
|
|
1057
|
+
const tokens = [];
|
|
1058
|
+
if (config.grant_type !== "client_credentials" && config.refresh_token)
|
|
1059
|
+
tokens.push(["refresh_token", config.refresh_token]);
|
|
1060
|
+
if (access)
|
|
1061
|
+
tokens.push(["access_token", access]);
|
|
1062
|
+
const out = { revoked: [] };
|
|
1063
|
+
for (const [hint, token] of tokens) {
|
|
1064
|
+
try {
|
|
1065
|
+
const request = oauthTokenRequest(config, { token, token_type_hint: hint });
|
|
1066
|
+
const res = await fetcher(config.revocation_url, { method: "POST", headers: request.headers, body: request.body, redirect: "error", signal: AbortSignal.timeout(10_000) });
|
|
1067
|
+
if (res.ok) {
|
|
1068
|
+
await res.body?.cancel().catch(() => { });
|
|
1069
|
+
out.revoked.push(hint);
|
|
1070
|
+
}
|
|
1071
|
+
else {
|
|
1072
|
+
// Reported, and the next token is still tried: a provider that will
|
|
1073
|
+
// not revoke refresh tokens may still revoke the access token.
|
|
1074
|
+
const why = readTokenResponse(await res.text().catch(() => ""), res.headers.get("content-type") ?? "");
|
|
1075
|
+
out.error ??= `the provider refused to revoke the ${hint.replace("_", " ")} (${res.status}${why.error ? `: ${why.error_description ?? why.error}` : ""})`;
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
catch (err) {
|
|
1079
|
+
out.error ??= `revoking the ${hint.replace("_", " ")} failed: ${err instanceof Error ? err.message : String(err)}`;
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
// Every entry serving that access token goes: after a rotation the same
|
|
1083
|
+
// token is cached under the recipe before and after it (Codex review).
|
|
1084
|
+
oauthCache.delete(key);
|
|
1085
|
+
if (access)
|
|
1086
|
+
for (const [k, v] of oauthCache)
|
|
1087
|
+
if (v.token === access)
|
|
1088
|
+
oauthCache.delete(k);
|
|
1089
|
+
return out;
|
|
1090
|
+
}
|
|
959
1091
|
/**
|
|
960
1092
|
* Swap every oauth2 recipe in an env map for a live access token. The one
|
|
961
1093
|
* async moment in secret resolution, kept out of the sync paths: callers
|
|
@@ -24,4 +24,8 @@ export declare function fetchUntrusted(url: string, init?: RequestInit, opts?: {
|
|
|
24
24
|
sameOrigin?: boolean;
|
|
25
25
|
/** The most the answer may be, read; MAX_BYTES unless said. */
|
|
26
26
|
maxBytes?: number;
|
|
27
|
+
/** Follow no redirect at all: a 3xx comes back as the answer, for the
|
|
28
|
+
* caller to treat as the failure it is (a revocation that redirects to
|
|
29
|
+
* a login page did not revoke anything). */
|
|
30
|
+
noRedirects?: boolean;
|
|
27
31
|
}): Promise<Response>;
|
|
@@ -93,7 +93,7 @@ export async function fetchUntrusted(url, init = {}, opts = {}) {
|
|
|
93
93
|
for (let hop = 0;; hop++) {
|
|
94
94
|
const res = await platform.fetchUntrusted(current, { ...req, redirect: "manual" }, { maxBytes });
|
|
95
95
|
const location = REDIRECT.has(res.status) ? res.headers.get("location") : null;
|
|
96
|
-
if (!location)
|
|
96
|
+
if (!location || opts.noRedirects)
|
|
97
97
|
return capBody(res, maxBytes, current);
|
|
98
98
|
// The body of a redirect is never read; free the socket.
|
|
99
99
|
await res.body?.cancel().catch(() => { });
|
package/index.ts
CHANGED
|
@@ -42,6 +42,8 @@ export * from "./src/package.ts";
|
|
|
42
42
|
export * from "./src/storage.ts";
|
|
43
43
|
export * from "./src/secrets.ts";
|
|
44
44
|
export * from "./src/oauth-presets.ts";
|
|
45
|
+
export * from "./src/oauth-token.ts";
|
|
46
|
+
export * from "./src/oauth-discovery.ts";
|
|
45
47
|
export * from "./src/secret-files.ts";
|
|
46
48
|
export * from "./src/notify.ts";
|
|
47
49
|
export * from "./src/webhook.ts";
|
package/package.json
CHANGED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// Discovery from an issuer: give foldrun the provider's issuer URL and it
|
|
2
|
+
// reads the authorization server's own metadata (RFC 8414, OpenID Connect
|
|
3
|
+
// Discovery 1.0) instead of a person typing the authorize, token and
|
|
4
|
+
// revocation URLs by hand — where a typo costs a consent, and an endpoint
|
|
5
|
+
// on the wrong host is a mix-up attack waiting to happen.
|
|
6
|
+
//
|
|
7
|
+
// Where the metadata lives, in the order tried (RFC 8414 §3.1 and §5):
|
|
8
|
+
// https://host/.well-known/oauth-authorization-server{/path}
|
|
9
|
+
// https://host/.well-known/openid-configuration{/path}
|
|
10
|
+
// https://host{/path}/.well-known/openid-configuration (OIDC's own spelling)
|
|
11
|
+
// The document's `issuer` must equal the issuer asked for, exactly (RFC 8414
|
|
12
|
+
// §3.3) — a document that names another issuer is refused, not trusted.
|
|
13
|
+
|
|
14
|
+
import type { TokenAuth } from "./oauth-token.ts";
|
|
15
|
+
|
|
16
|
+
/** What foldrun reads from a metadata document. */
|
|
17
|
+
export interface OAuthServerMetadata {
|
|
18
|
+
issuer: string;
|
|
19
|
+
authorization_endpoint?: string;
|
|
20
|
+
token_endpoint?: string;
|
|
21
|
+
revocation_endpoint?: string;
|
|
22
|
+
device_authorization_endpoint?: string;
|
|
23
|
+
pushed_authorization_request_endpoint?: string;
|
|
24
|
+
require_pushed_authorization_requests?: boolean;
|
|
25
|
+
token_endpoint_auth_methods_supported?: string[];
|
|
26
|
+
code_challenge_methods_supported?: string[];
|
|
27
|
+
authorization_response_iss_parameter_supported?: boolean;
|
|
28
|
+
dpop_signing_alg_values_supported?: string[];
|
|
29
|
+
scopes_supported?: string[];
|
|
30
|
+
jwks_uri?: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A discovered server, as the fields a saved app and an oauth2 secret take. */
|
|
34
|
+
export interface DiscoveredClientConfig {
|
|
35
|
+
issuer: string;
|
|
36
|
+
authorize_url?: string;
|
|
37
|
+
token_url: string;
|
|
38
|
+
revocation_url?: string;
|
|
39
|
+
device_url?: string;
|
|
40
|
+
par_url?: string;
|
|
41
|
+
/** The server requires PAR: an authorize URL without a request_uri fails. */
|
|
42
|
+
par_required?: boolean;
|
|
43
|
+
/** Whether the server sends `iss` with every authorization response
|
|
44
|
+
* (RFC 9207): when true, one that comes back without it is refused. */
|
|
45
|
+
iss_parameter: boolean;
|
|
46
|
+
/** How the client should authenticate at the token URL, given whether it
|
|
47
|
+
* has a secret and what the server supports; absent is the form body. */
|
|
48
|
+
token_auth?: TokenAuth;
|
|
49
|
+
/** Where the metadata was read from. */
|
|
50
|
+
metadata_url: string;
|
|
51
|
+
metadata: OAuthServerMetadata;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Loopback is exempt: a server on this machine (tests, a local Keycloak)
|
|
55
|
+
* crosses no wire for http to leak on. Judged on the parsed URL, never on
|
|
56
|
+
* how it starts: `http://localhost:80@evil.example` is evil.example
|
|
57
|
+
* (Codex review, 1 Nov 2026). */
|
|
58
|
+
export function isSecureUrl(url: string): boolean {
|
|
59
|
+
let u: URL;
|
|
60
|
+
try {
|
|
61
|
+
u = new URL(url);
|
|
62
|
+
} catch {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
if (u.username || u.password) return false;
|
|
66
|
+
if (u.protocol === "https:") return true;
|
|
67
|
+
return u.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(u.hostname);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Every URL the metadata may be at, in the order to try. */
|
|
71
|
+
export function metadataUrls(issuer: string): string[] {
|
|
72
|
+
const u = new URL(issuer);
|
|
73
|
+
const pathPart = u.pathname.replace(/\/+$/, "");
|
|
74
|
+
const origin = u.origin;
|
|
75
|
+
const urls = [
|
|
76
|
+
`${origin}/.well-known/oauth-authorization-server${pathPart}`,
|
|
77
|
+
`${origin}/.well-known/openid-configuration${pathPart}`,
|
|
78
|
+
];
|
|
79
|
+
if (pathPart) urls.push(`${origin}${pathPart}/.well-known/openid-configuration`);
|
|
80
|
+
return [...new Set(urls)];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Why an issuer cannot be discovered from, or null. */
|
|
84
|
+
export function issuerProblem(issuer: string): string | null {
|
|
85
|
+
let u: URL;
|
|
86
|
+
try {
|
|
87
|
+
u = new URL(issuer);
|
|
88
|
+
} catch {
|
|
89
|
+
return "issuer must be a URL, like https://login.example.com";
|
|
90
|
+
}
|
|
91
|
+
if (!isSecureUrl(issuer)) return "issuer must be https";
|
|
92
|
+
if (u.search || u.hash) return "issuer has no query or fragment (RFC 8414 §2)";
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
type Fetcher = (url: string, init?: RequestInit) => Promise<Response>;
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Read the authorization server's metadata. `fetcher` is how the caller
|
|
100
|
+
* reaches the network (the platform's SSRF-guarded fetchPublic, the CLI's
|
|
101
|
+
* fetch). Throws with every place tried when none answers.
|
|
102
|
+
*/
|
|
103
|
+
export async function fetchOAuthMetadata(issuer: string, fetcher: Fetcher): Promise<{ url: string; metadata: OAuthServerMetadata }> {
|
|
104
|
+
const problem = issuerProblem(issuer);
|
|
105
|
+
if (problem) throw new Error(problem);
|
|
106
|
+
const tried: string[] = [];
|
|
107
|
+
for (const url of metadataUrls(issuer)) {
|
|
108
|
+
let res: Response;
|
|
109
|
+
try {
|
|
110
|
+
res = await fetcher(url, { headers: { accept: "application/json" }, redirect: "error", signal: AbortSignal.timeout(10_000) });
|
|
111
|
+
} catch (err) {
|
|
112
|
+
tried.push(`${url} (${err instanceof Error ? err.message : String(err)})`);
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (!res.ok) {
|
|
116
|
+
await res.body?.cancel().catch(() => {});
|
|
117
|
+
tried.push(`${url} (${res.status})`);
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
let doc: unknown;
|
|
121
|
+
try {
|
|
122
|
+
doc = await res.json();
|
|
123
|
+
} catch {
|
|
124
|
+
tried.push(`${url} (not JSON)`);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (!doc || typeof doc !== "object" || Array.isArray(doc)) {
|
|
128
|
+
tried.push(`${url} (not a metadata document)`);
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
const metadata = doc as OAuthServerMetadata;
|
|
132
|
+
// RFC 8414 §3.3: the issuer in the document is the one asked for, or
|
|
133
|
+
// the document is not used. Trailing-slash differences are not forgiven.
|
|
134
|
+
if (metadata.issuer !== issuer) {
|
|
135
|
+
throw new Error(`the metadata at ${url} names the issuer ${JSON.stringify(metadata.issuer ?? null)}, not ${issuer} — refused (RFC 8414 §3.3)`);
|
|
136
|
+
}
|
|
137
|
+
return { url, metadata };
|
|
138
|
+
}
|
|
139
|
+
throw new Error(`no OAuth metadata for ${issuer} — tried ${tried.join(", ")}`);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const ENDPOINTS = [
|
|
143
|
+
"authorization_endpoint", "token_endpoint", "revocation_endpoint",
|
|
144
|
+
"device_authorization_endpoint", "pushed_authorization_request_endpoint", "jwks_uri",
|
|
145
|
+
] as const;
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* What a client config should say for this server. `hasSecret`: the app
|
|
149
|
+
* has a client secret; `pkce`: false when the caller turned PKCE off;
|
|
150
|
+
* `tokenAuth`: one the caller chose, which wins over the server's list.
|
|
151
|
+
*/
|
|
152
|
+
export function clientConfigFromMetadata(
|
|
153
|
+
found: { url: string; metadata: OAuthServerMetadata },
|
|
154
|
+
opts: { hasSecret: boolean; pkce?: boolean; tokenAuth?: TokenAuth; needsAuthorize?: boolean } = { hasSecret: true },
|
|
155
|
+
): DiscoveredClientConfig {
|
|
156
|
+
const m = found.metadata;
|
|
157
|
+
for (const k of ENDPOINTS) {
|
|
158
|
+
const v = m[k];
|
|
159
|
+
if (v !== undefined && (typeof v !== "string" || !isSecureUrl(v))) throw new Error(`the server's ${k} is not an https URL: ${String(v)}`);
|
|
160
|
+
}
|
|
161
|
+
if (!m.token_endpoint) throw new Error(`${m.issuer} publishes no token_endpoint`);
|
|
162
|
+
if ((opts.needsAuthorize ?? true) && !m.authorization_endpoint) throw new Error(`${m.issuer} publishes no authorization_endpoint — it does not do browser sign-in`);
|
|
163
|
+
// PKCE S256 is required of every connection (RFC 9700 §2.1.1). A server
|
|
164
|
+
// that lists its methods and leaves S256 out would ignore our challenge.
|
|
165
|
+
if (opts.pkce !== false && Array.isArray(m.code_challenge_methods_supported) && !m.code_challenge_methods_supported.includes("S256")) {
|
|
166
|
+
throw new Error(`${m.issuer} does not support PKCE S256 (it lists ${m.code_challenge_methods_supported.join(", ") || "none"}) — refused; turn PKCE off only if you are sure (--no-pkce)`);
|
|
167
|
+
}
|
|
168
|
+
return {
|
|
169
|
+
issuer: m.issuer,
|
|
170
|
+
...(m.authorization_endpoint ? { authorize_url: m.authorization_endpoint } : {}),
|
|
171
|
+
token_url: m.token_endpoint,
|
|
172
|
+
...(m.revocation_endpoint ? { revocation_url: m.revocation_endpoint } : {}),
|
|
173
|
+
...(m.device_authorization_endpoint ? { device_url: m.device_authorization_endpoint } : {}),
|
|
174
|
+
...(m.pushed_authorization_request_endpoint ? { par_url: m.pushed_authorization_request_endpoint } : {}),
|
|
175
|
+
...(m.require_pushed_authorization_requests === true ? { par_required: true } : {}),
|
|
176
|
+
iss_parameter: m.authorization_response_iss_parameter_supported === true,
|
|
177
|
+
...pickTokenAuth(m.token_endpoint_auth_methods_supported, opts),
|
|
178
|
+
metadata_url: found.url,
|
|
179
|
+
metadata: m,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* The token_auth to use. A choice the caller made is kept. Otherwise, with a
|
|
185
|
+
* secret: the form body when the server lists it (what every secret did
|
|
186
|
+
* before), else Basic — which is also the RFC 8414 default when the server
|
|
187
|
+
* lists nothing. Without a secret: none (a public client).
|
|
188
|
+
*/
|
|
189
|
+
export function pickTokenAuth(supported: unknown, opts: { hasSecret: boolean; tokenAuth?: TokenAuth }): { token_auth?: TokenAuth } {
|
|
190
|
+
if (opts.tokenAuth) return { token_auth: opts.tokenAuth };
|
|
191
|
+
const list = Array.isArray(supported) ? supported.filter((s): s is string => typeof s === "string") : null;
|
|
192
|
+
// A public client sends no secret. Not refused when the list leaves out
|
|
193
|
+
// `none`: Keycloak takes public clients and lists only secret methods,
|
|
194
|
+
// so the list is not the last word on it (found by the conformance suite).
|
|
195
|
+
if (!opts.hasSecret) return {};
|
|
196
|
+
if (list && list.includes("client_secret_post")) return {};
|
|
197
|
+
if (!list || list.includes("client_secret_basic")) return { token_auth: "client_secret_basic" };
|
|
198
|
+
throw new Error(`the server takes none of the ways foldrun signs in at its token URL (it lists ${list.join(", ") || "nothing"}; foldrun sends the secret in the form body or as HTTP Basic)`);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Discover and turn into a client config in one call. */
|
|
202
|
+
export async function discoverOAuth(
|
|
203
|
+
issuer: string,
|
|
204
|
+
fetcher: Fetcher,
|
|
205
|
+
opts: { hasSecret: boolean; pkce?: boolean; tokenAuth?: TokenAuth; needsAuthorize?: boolean },
|
|
206
|
+
): Promise<DiscoveredClientConfig> {
|
|
207
|
+
return clientConfigFromMetadata(await fetchOAuthMetadata(issuer, fetcher), opts);
|
|
208
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// Every request to an OAuth token endpoint, and every answer read from one,
|
|
2
|
+
// goes through here: core's refresh (refresh_token, client_credentials), the
|
|
3
|
+
// platform's code exchange after a consent, and the CLI's own loopback
|
|
4
|
+
// connect. Three hand-written bodies had already drifted — none could send
|
|
5
|
+
// the client secret any way but in the form body, which is the one way RFC
|
|
6
|
+
// 6749 §2.3.1 lets a server refuse (Notion, Spotify, Reddit, Zoom do).
|
|
7
|
+
//
|
|
8
|
+
// How the client proves itself at the token endpoint (`token_auth`):
|
|
9
|
+
// client_secret_post id and secret in the form body (the default — what
|
|
10
|
+
// every stored secret did before 1 Nov 2026)
|
|
11
|
+
// client_secret_basic HTTP Basic, the id and secret each form-urlencoded
|
|
12
|
+
// first (RFC 6749 §2.3.1, Appendix B) — not plain
|
|
13
|
+
// base64 of the raw pair, which breaks on a secret
|
|
14
|
+
// holding ':' or '%'
|
|
15
|
+
// none a public client: client_id in the body, no secret
|
|
16
|
+
//
|
|
17
|
+
// Absent means the old behaviour: the body, with the secret if there is one.
|
|
18
|
+
|
|
19
|
+
export const TOKEN_AUTH_METHODS = ["client_secret_post", "client_secret_basic", "none"] as const;
|
|
20
|
+
export type TokenAuth = (typeof TOKEN_AUTH_METHODS)[number];
|
|
21
|
+
|
|
22
|
+
/** The short spellings a person types (`--token-auth basic`), to the RFC names. */
|
|
23
|
+
export function parseTokenAuth(value: string): TokenAuth | null {
|
|
24
|
+
const v = value.trim().toLowerCase();
|
|
25
|
+
if ((TOKEN_AUTH_METHODS as readonly string[]).includes(v)) return v as TokenAuth;
|
|
26
|
+
if (v === "post" || v === "body") return "client_secret_post";
|
|
27
|
+
if (v === "basic") return "client_secret_basic";
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface TokenClient {
|
|
32
|
+
client_id: string;
|
|
33
|
+
client_secret?: string;
|
|
34
|
+
token_auth?: TokenAuth;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Why a client's token_auth cannot work, or null. */
|
|
38
|
+
export function tokenAuthProblem(client: { client_secret?: string; token_auth?: unknown }): string | null {
|
|
39
|
+
const auth = client.token_auth;
|
|
40
|
+
if (auth === undefined) return null;
|
|
41
|
+
if (typeof auth !== "string" || !(TOKEN_AUTH_METHODS as readonly string[]).includes(auth)) {
|
|
42
|
+
return `token_auth must be one of ${TOKEN_AUTH_METHODS.join(", ")}`;
|
|
43
|
+
}
|
|
44
|
+
const hasSecret = !!client.client_secret?.trim();
|
|
45
|
+
if (auth === "client_secret_basic" && !hasSecret) return "token_auth client_secret_basic needs a client_secret";
|
|
46
|
+
if (auth === "client_secret_post" && !hasSecret) return "token_auth client_secret_post needs a client_secret — a public app is token_auth none";
|
|
47
|
+
if (auth === "none" && hasSecret) return "token_auth none is a public client — it sends no client_secret; leave the secret empty or pick client_secret_post or client_secret_basic";
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The form-urlencoding RFC 6749 Appendix B asks for: space as '+'. */
|
|
52
|
+
const formEncode = (s: string) => new URLSearchParams({ x: s }).toString().slice(2);
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The headers and body of one token request. `params` is the grant's own
|
|
56
|
+
* fields (grant_type, code, refresh_token, …); the client's identity is
|
|
57
|
+
* added here, by its token_auth. Fields in `params` named client_id or
|
|
58
|
+
* client_secret are dropped — the method decides those, never an `extra`.
|
|
59
|
+
* `clientIdInBody`: client_id goes in the form whatever the method — a
|
|
60
|
+
* pushed authorization request carries it as a parameter of the request it
|
|
61
|
+
* describes even when the client authenticates with Basic (RFC 9126 §2.1).
|
|
62
|
+
*/
|
|
63
|
+
export function oauthTokenRequest(client: TokenClient, params: Record<string, string>, opts: { clientIdInBody?: boolean } = {}): { headers: Record<string, string>; body: string } {
|
|
64
|
+
const problem = tokenAuthProblem(client);
|
|
65
|
+
if (problem) throw new Error(problem);
|
|
66
|
+
const form = new URLSearchParams();
|
|
67
|
+
for (const [k, v] of Object.entries(params)) {
|
|
68
|
+
if (k === "client_id" || k === "client_secret") continue;
|
|
69
|
+
form.set(k, v);
|
|
70
|
+
}
|
|
71
|
+
const headers: Record<string, string> = {
|
|
72
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
73
|
+
// GitHub answers form-encoded unless asked; every server may answer JSON.
|
|
74
|
+
accept: "application/json",
|
|
75
|
+
};
|
|
76
|
+
const auth = client.token_auth ?? (client.client_secret ? "client_secret_post" : "none");
|
|
77
|
+
if (auth === "client_secret_basic") {
|
|
78
|
+
// One method per request (RFC 6749 §2.3): the id travels in the header,
|
|
79
|
+
// not the body as well.
|
|
80
|
+
const pair = `${formEncode(client.client_id)}:${formEncode(client.client_secret!)}`;
|
|
81
|
+
headers.authorization = `Basic ${Buffer.from(pair, "utf8").toString("base64")}`;
|
|
82
|
+
if (opts.clientIdInBody) form.set("client_id", client.client_id);
|
|
83
|
+
} else {
|
|
84
|
+
form.set("client_id", client.client_id);
|
|
85
|
+
if (auth === "client_secret_post") form.set("client_secret", client.client_secret!);
|
|
86
|
+
}
|
|
87
|
+
return { headers, body: form.toString() };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** A token endpoint's answer, read the ways providers actually write it. */
|
|
91
|
+
export interface TokenResponse {
|
|
92
|
+
access_token?: string;
|
|
93
|
+
refresh_token?: string;
|
|
94
|
+
/** Seconds; a string "3600" (some providers) is read as the number. */
|
|
95
|
+
expires_in?: number;
|
|
96
|
+
refresh_token_expires_in?: number;
|
|
97
|
+
token_type?: string;
|
|
98
|
+
scope?: string;
|
|
99
|
+
error?: string;
|
|
100
|
+
error_description?: string;
|
|
101
|
+
/** The other plain fields beside the token — Salesforce's instance_url,
|
|
102
|
+
* Slack's team — kept for the caller; never a token. */
|
|
103
|
+
fields: Record<string, string>;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Fields that are credentials or are read into their own slot above. */
|
|
107
|
+
const NOT_FIELDS = new Set([
|
|
108
|
+
"access_token", "refresh_token", "id_token", "expires_in", "refresh_token_expires_in",
|
|
109
|
+
"error", "error_description", "error_uri", "authed_user", "ok",
|
|
110
|
+
]);
|
|
111
|
+
|
|
112
|
+
function seconds(v: unknown): number | undefined {
|
|
113
|
+
const n = typeof v === "number" ? v : typeof v === "string" && v.trim() !== "" ? Number(v) : NaN;
|
|
114
|
+
return Number.isFinite(n) && n >= 0 ? n : undefined;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function str(v: unknown): string | undefined {
|
|
118
|
+
return typeof v === "string" && v !== "" ? v : undefined;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Read a token endpoint's body: JSON, or form-encoded (GitHub without an
|
|
123
|
+
* Accept header, some older servers), whatever the content type claims.
|
|
124
|
+
* Slack's user-token install nests the token under `authed_user` and says
|
|
125
|
+
* `ok: false` with a 200 when it refuses; both are read here.
|
|
126
|
+
*/
|
|
127
|
+
export function readTokenResponse(text: string, contentType = ""): TokenResponse {
|
|
128
|
+
let raw: Record<string, unknown> = {};
|
|
129
|
+
const trimmed = text.trim();
|
|
130
|
+
if (trimmed.startsWith("{")) {
|
|
131
|
+
try {
|
|
132
|
+
const parsed = JSON.parse(trimmed) as unknown;
|
|
133
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) raw = parsed as Record<string, unknown>;
|
|
134
|
+
} catch {
|
|
135
|
+
raw = {};
|
|
136
|
+
}
|
|
137
|
+
} else if (trimmed && (/x-www-form-urlencoded|text\/plain/i.test(contentType) || /^[\w.-]+=/.test(trimmed))) {
|
|
138
|
+
raw = Object.fromEntries(new URLSearchParams(trimmed));
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Slack: a user token alone comes back under authed_user, with its own
|
|
142
|
+
// refresh token and expiry when rotation is on. The top-level token (a bot
|
|
143
|
+
// token) wins when there is one.
|
|
144
|
+
let source: Record<string, unknown> = raw;
|
|
145
|
+
const nested = raw.authed_user;
|
|
146
|
+
if (!str(raw.access_token) && nested && typeof nested === "object" && str((nested as Record<string, unknown>).access_token)) {
|
|
147
|
+
source = nested as Record<string, unknown>;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const fields: Record<string, string> = {};
|
|
151
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
152
|
+
if (NOT_FIELDS.has(k)) continue;
|
|
153
|
+
if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") fields[k] = String(v);
|
|
154
|
+
}
|
|
155
|
+
// From the nested object: its scope and type describe the token we took.
|
|
156
|
+
const scope = str(source.scope) ?? str(raw.scope);
|
|
157
|
+
const tokenType = str(source.token_type) ?? str(raw.token_type);
|
|
158
|
+
|
|
159
|
+
const out: TokenResponse = { fields };
|
|
160
|
+
const access = str(source.access_token);
|
|
161
|
+
const refresh = str(source.refresh_token);
|
|
162
|
+
const expires = seconds(source.expires_in);
|
|
163
|
+
const refreshExpires = seconds(source.refresh_token_expires_in);
|
|
164
|
+
if (access) out.access_token = access;
|
|
165
|
+
if (refresh) out.refresh_token = refresh;
|
|
166
|
+
if (expires !== undefined) out.expires_in = expires;
|
|
167
|
+
if (refreshExpires !== undefined) out.refresh_token_expires_in = refreshExpires;
|
|
168
|
+
if (tokenType) out.token_type = tokenType;
|
|
169
|
+
if (scope) out.scope = scope;
|
|
170
|
+
const error = str(raw.error) ?? (raw.ok === false ? "refused" : undefined);
|
|
171
|
+
if (error) {
|
|
172
|
+
out.error = error;
|
|
173
|
+
// A refusal carries no token, whatever else the body held.
|
|
174
|
+
delete out.access_token;
|
|
175
|
+
delete out.refresh_token;
|
|
176
|
+
}
|
|
177
|
+
const description = str(raw.error_description);
|
|
178
|
+
if (description) out.error_description = description;
|
|
179
|
+
return out;
|
|
180
|
+
}
|