pi-lean-host 0.4.0 → 0.6.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/README.md +194 -557
- package/core/api-guide-types.ts +250 -47
- package/core/api-toggle.ts +244 -39
- package/core/auth.ts +997 -76
- package/core/delete-command.ts +1 -1
- package/core/fs-0600.ts +39 -0
- package/core/guide-catalog.ts +349 -0
- package/core/guide-picker.ts +76 -61
- package/core/guide-store.ts +2 -2
- package/core/helpers.ts +532 -151
- package/core/local-helpers.ts +7 -0
- package/core/oauth-command.ts +913 -0
- package/core/oauth-flow.ts +392 -0
- package/core/oauth-store.ts +306 -0
- package/core/parse-api-guide.ts +1125 -596
- package/core/path-template.ts +101 -0
- package/core/portal-projection.ts +3 -4
- package/core/resolve-op.ts +113 -67
- package/core/response-spill.ts +10 -7
- package/core/secrets-command.ts +18 -13
- package/core/secrets-store.ts +11 -44
- package/core/select-picker.ts +171 -0
- package/core/staging.ts +29 -0
- package/core/transport.ts +322 -35
- package/core/verify-command.ts +93 -65
- package/docs/migration-v1.md +56 -0
- package/index.ts +12 -10
- package/package.json +16 -6
- package/tools/api-fetch.ts +45 -18
- package/tools/api-guide.ts +37 -67
- package/tools/api-learn.ts +148 -103
- package/tools/api-probe.ts +458 -294
- package/tools/api-scaffold.ts +34 -63
- package/tools/api-store.ts +381 -0
- package/tools/oauth-mint.ts +338 -0
- package/tools/utils.ts +70 -1
- package/core/verify-ship-manifest.ts +0 -118
- package/tools/index.ts +0 -8
package/core/auth.ts
CHANGED
|
@@ -1,14 +1,41 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Auth — store-backed secret resolution + OAuth2 token resolution + the
|
|
3
|
+
* metadata-only auth footer.
|
|
3
4
|
*
|
|
4
|
-
*
|
|
5
|
-
* footers
|
|
6
|
-
* only — secret values never leave
|
|
5
|
+
* Shared by `api-fetch` (injection + fail-closed), `api-guide`/`api-fetch`
|
|
6
|
+
* footers, and `/api oauth`. Reads the secrets store and the OAuth2 token
|
|
7
|
+
* store; exposes names only — secret values never leave the resolved header
|
|
7
8
|
* map (which only the fetch pipeline consumes, never agent context).
|
|
9
|
+
*
|
|
10
|
+
* Import direction: this module imports `oauth-store.ts` (the footer and
|
|
11
|
+
* token resolution must read the token store); `oauth-store.ts` imports
|
|
12
|
+
* nothing from here, so the edge stays one-way and no cycle can form.
|
|
8
13
|
*/
|
|
9
14
|
|
|
10
|
-
import type {
|
|
11
|
-
|
|
15
|
+
import type {
|
|
16
|
+
ApiGuide,
|
|
17
|
+
AuthConfig,
|
|
18
|
+
OAuth2Auth,
|
|
19
|
+
OAuth2Grant,
|
|
20
|
+
OAuth2TokenEndpointAuthMethod,
|
|
21
|
+
StaticKeyAuth,
|
|
22
|
+
} from "./api-guide-types.js";
|
|
23
|
+
import {
|
|
24
|
+
isOAuth2Grant,
|
|
25
|
+
isOAuth2TokenEndpointAuthMethod,
|
|
26
|
+
oauth2GrantIssue,
|
|
27
|
+
OAUTH2_GRANTS,
|
|
28
|
+
OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS,
|
|
29
|
+
type OAuth2GrantIssue,
|
|
30
|
+
} from "./api-guide-types.js";
|
|
31
|
+
import {
|
|
32
|
+
listDomains,
|
|
33
|
+
listNames,
|
|
34
|
+
readSecret,
|
|
35
|
+
provisionedDomainsSuffix,
|
|
36
|
+
} from "./secrets-store.js";
|
|
37
|
+
import { readToken, writeToken, deleteToken, slotKey } from "./oauth-store.js";
|
|
38
|
+
import type { OAuthToken } from "./oauth-store.js";
|
|
12
39
|
|
|
13
40
|
/**
|
|
14
41
|
* The canonical secret-store key for a guide: its primary browsable domain.
|
|
@@ -31,29 +58,28 @@ export interface SecretResolution {
|
|
|
31
58
|
* audit — a server may echo the bare token, not just the prefixed form.
|
|
32
59
|
*/
|
|
33
60
|
rawHeaderValues: string[];
|
|
34
|
-
/** secret names referenced by
|
|
61
|
+
/** secret names referenced by required refs that are absent from the store. */
|
|
35
62
|
absentRequired: string[];
|
|
36
|
-
/** secret names referenced by
|
|
63
|
+
/** secret names referenced by optional refs that are absent from the store. */
|
|
37
64
|
absentOptional: string[];
|
|
38
65
|
}
|
|
39
66
|
|
|
40
|
-
/** Resolve store-secret headers for a `static-key` guide
|
|
67
|
+
/** Resolve store-secret headers for a `static-key` guide. */
|
|
41
68
|
export function resolveSecretHeaders(
|
|
42
|
-
auth:
|
|
69
|
+
auth: StaticKeyAuth,
|
|
43
70
|
domain: string,
|
|
44
71
|
): SecretResolution {
|
|
45
72
|
const headers: Record<string, string> = {};
|
|
46
73
|
const rawHeaderValues: string[] = [];
|
|
47
74
|
const absentRequired: string[] = [];
|
|
48
75
|
const absentOptional: string[] = [];
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
const value = readSecret(domain, secretName);
|
|
76
|
+
for (const [headerName, ref] of Object.entries(auth.secretRefs ?? {})) {
|
|
77
|
+
const value = readSecret(domain, ref.secret);
|
|
52
78
|
if (value === null) {
|
|
53
|
-
if (
|
|
54
|
-
else
|
|
79
|
+
if (ref.optional) absentOptional.push(ref.secret);
|
|
80
|
+
else absentRequired.push(ref.secret);
|
|
55
81
|
} else {
|
|
56
|
-
headers[headerName] = (
|
|
82
|
+
headers[headerName] = (ref.prefix ?? "") + value;
|
|
57
83
|
rawHeaderValues.push(value);
|
|
58
84
|
}
|
|
59
85
|
}
|
|
@@ -64,33 +90,30 @@ export function resolveSecretHeaders(
|
|
|
64
90
|
export interface QuerySecretResolution {
|
|
65
91
|
/** paramName → resolved value, injected below the agent params map. */
|
|
66
92
|
queryParams: Record<string, string>;
|
|
67
|
-
/** secret names referenced by
|
|
93
|
+
/** secret names referenced by required refs that are absent from the store. */
|
|
68
94
|
absentRequired: string[];
|
|
69
|
-
/** secret names referenced by
|
|
95
|
+
/** secret names referenced by optional refs that are absent from the store. */
|
|
70
96
|
absentOptional: string[];
|
|
71
97
|
}
|
|
72
98
|
|
|
73
99
|
/**
|
|
74
100
|
* Resolve store-secret query params for a `static-key` guide. Mirrors
|
|
75
|
-
* `resolveSecretHeaders`: reads the store, splits absents by
|
|
76
|
-
*
|
|
77
|
-
*
|
|
101
|
+
* `resolveSecretHeaders`: reads the store, splits absents by ref.optional.
|
|
102
|
+
* The values are injected below the agent-supplied params map by the fetch
|
|
103
|
+
* pipeline and never enter agent context.
|
|
78
104
|
*/
|
|
79
105
|
export function resolveSecretQueryParams(
|
|
80
|
-
auth:
|
|
106
|
+
auth: StaticKeyAuth,
|
|
81
107
|
domain: string,
|
|
82
108
|
): QuerySecretResolution {
|
|
83
109
|
const queryParams: Record<string, string> = {};
|
|
84
110
|
const absentRequired: string[] = [];
|
|
85
111
|
const absentOptional: string[] = [];
|
|
86
|
-
const
|
|
87
|
-
|
|
88
|
-
auth.secretQueryRefs ?? {},
|
|
89
|
-
)) {
|
|
90
|
-
const value = readSecret(domain, secretName);
|
|
112
|
+
for (const [paramName, ref] of Object.entries(auth.secretQueryRefs ?? {})) {
|
|
113
|
+
const value = readSecret(domain, ref.secret);
|
|
91
114
|
if (value === null) {
|
|
92
|
-
if (
|
|
93
|
-
else
|
|
115
|
+
if (ref.optional) absentOptional.push(ref.secret);
|
|
116
|
+
else absentRequired.push(ref.secret);
|
|
94
117
|
} else {
|
|
95
118
|
queryParams[paramName] = value;
|
|
96
119
|
}
|
|
@@ -98,62 +121,183 @@ export function resolveSecretQueryParams(
|
|
|
98
121
|
return { queryParams, absentRequired, absentOptional };
|
|
99
122
|
}
|
|
100
123
|
|
|
124
|
+
/**
|
|
125
|
+
* Resolve store-secret path tokens for a `static-key` guide. Mirrors
|
|
126
|
+
* `resolveSecretQueryParams` minus the optional arm: `secretPathRefs` are
|
|
127
|
+
* required-only (parse rejects `optional` — a path-keyed API has no
|
|
128
|
+
* unauthenticated state), so any store miss joins a single `missing` list
|
|
129
|
+
* and the caller fails closed. Values are the RAW secret (no prefix — path
|
|
130
|
+
* injection is verbatim; parse rejects `prefix` on path refs) and never
|
|
131
|
+
* enter agent context — they fill `{name}` in the op path at fetch time.
|
|
132
|
+
*/
|
|
133
|
+
export interface PathSecretResolution {
|
|
134
|
+
/** pathTokenName → resolved raw value, injected below the agent params map. */
|
|
135
|
+
values: Record<string, string>;
|
|
136
|
+
/** secret names referenced by path refs that are absent from the store. */
|
|
137
|
+
missing: string[];
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function resolveSecretPathParams(
|
|
141
|
+
auth: StaticKeyAuth,
|
|
142
|
+
domain: string,
|
|
143
|
+
): PathSecretResolution {
|
|
144
|
+
const values: Record<string, string> = {};
|
|
145
|
+
const missing: string[] = [];
|
|
146
|
+
for (const [tokenName, ref] of Object.entries(auth.secretPathRefs ?? {})) {
|
|
147
|
+
const value = readSecret(domain, ref.secret);
|
|
148
|
+
if (value === null) missing.push(ref.secret);
|
|
149
|
+
else values[tokenName] = value;
|
|
150
|
+
}
|
|
151
|
+
return { values, missing };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Fold the three resolver results into one deduped list of missing required
|
|
156
|
+
* secret names (a secret may be referenced by more than one ref map). One
|
|
157
|
+
* derivation shared by resolve-op, the /api verify precheck, and the auth
|
|
158
|
+
* status footer.
|
|
159
|
+
*/
|
|
160
|
+
export function missingRequiredSecrets(
|
|
161
|
+
headerRes: SecretResolution,
|
|
162
|
+
queryRes: QuerySecretResolution,
|
|
163
|
+
pathRes: PathSecretResolution,
|
|
164
|
+
): string[] {
|
|
165
|
+
return [
|
|
166
|
+
...new Set([
|
|
167
|
+
...headerRes.absentRequired,
|
|
168
|
+
...queryRes.absentRequired,
|
|
169
|
+
...pathRes.missing,
|
|
170
|
+
]),
|
|
171
|
+
];
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Path-token names owned by `secretPathRefs` — store-filled, never
|
|
176
|
+
* caller-supplied, so never unsatisfiable (see `unsatisfiable`).
|
|
177
|
+
*/
|
|
178
|
+
export function secretPathTokenNames(auth: AuthConfig): ReadonlySet<string> {
|
|
179
|
+
return auth.kind === "static-key"
|
|
180
|
+
? new Set(Object.keys(auth.secretPathRefs ?? {}))
|
|
181
|
+
: new Set<string>();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Secret store-names a guide's auth block declares, from `auth.secretRefs`,
|
|
186
|
+
* and `auth.secretQueryRefs` (ref.secret values). For oauth2 the clientId/
|
|
187
|
+
* clientSecret refs are declared too — their store names are resolved
|
|
188
|
+
* per-user, so assisted provisioning should prompt for them. Empty for
|
|
189
|
+
* guides without keyed/oauth auth. Single source of truth for both the
|
|
190
|
+
* `/api secrets` assisted-entry and the `api-store` declared/gap report.
|
|
191
|
+
*/
|
|
192
|
+
export function declaredSecretRefNames(guide: ApiGuide): string[] {
|
|
193
|
+
const names = new Set<string>();
|
|
194
|
+
switch (guide.auth.kind) {
|
|
195
|
+
case "static-key":
|
|
196
|
+
for (const ref of Object.values(guide.auth.secretRefs ?? {}))
|
|
197
|
+
names.add(ref.secret);
|
|
198
|
+
for (const ref of Object.values(guide.auth.secretQueryRefs ?? {}))
|
|
199
|
+
names.add(ref.secret);
|
|
200
|
+
for (const ref of Object.values(guide.auth.secretPathRefs ?? {}))
|
|
201
|
+
names.add(ref.secret);
|
|
202
|
+
break;
|
|
203
|
+
case "oauth2":
|
|
204
|
+
// clientId/clientSecret are SecretRefs resolved per-user — declare
|
|
205
|
+
// their store names so assisted provisioning prompts for them.
|
|
206
|
+
for (const ref of [guide.auth.clientId, guide.auth.clientSecret])
|
|
207
|
+
if (ref) names.add(ref.secret);
|
|
208
|
+
for (const ref of Object.values(guide.auth.secretRefs ?? {}))
|
|
209
|
+
names.add(ref.secret);
|
|
210
|
+
break;
|
|
211
|
+
case "none":
|
|
212
|
+
break;
|
|
213
|
+
default: {
|
|
214
|
+
const _exhaustive: never = guide.auth;
|
|
215
|
+
throw new Error(`Unhandled auth kind: ${_exhaustive}`);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return [...names].sort((a, b) => a.localeCompare(b));
|
|
219
|
+
}
|
|
220
|
+
|
|
101
221
|
/**
|
|
102
222
|
* Metadata-only auth status footer line, shared by `api-guide` and `api-fetch`.
|
|
103
|
-
* Five states
|
|
104
|
-
* ok-optional
|
|
105
|
-
*
|
|
106
|
-
*
|
|
223
|
+
* Five static-key states (no-auth → undefined / ok / nudge-provision /
|
|
224
|
+
* ok-optional / optional-not-provisioned) plus the oauth2 states (ok /
|
|
225
|
+
* expired-but-refreshable / missing → nudge /api oauth). Never renders a
|
|
226
|
+
* secret value — names only.
|
|
107
227
|
*/
|
|
108
228
|
export function authStatusLine(
|
|
109
229
|
auth: AuthConfig,
|
|
110
230
|
domain: string,
|
|
111
231
|
): string | undefined {
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
232
|
+
switch (auth.kind) {
|
|
233
|
+
case "none":
|
|
234
|
+
return undefined;
|
|
235
|
+
case "static-key": {
|
|
236
|
+
// Nothing to report when no ref map has an entry (empty maps are
|
|
237
|
+
// valid = no injection). A path-secret-only guide must render as
|
|
238
|
+
// keyed auth, not "no auth".
|
|
239
|
+
if (
|
|
240
|
+
Object.keys(auth.secretRefs ?? {}).length === 0 &&
|
|
241
|
+
Object.keys(auth.secretQueryRefs ?? {}).length === 0 &&
|
|
242
|
+
Object.keys(auth.secretPathRefs ?? {}).length === 0
|
|
243
|
+
)
|
|
244
|
+
return undefined;
|
|
245
|
+
const headerRes = resolveSecretHeaders(auth, domain);
|
|
246
|
+
const queryRes = resolveSecretQueryParams(auth, domain);
|
|
247
|
+
const pathRes = resolveSecretPathParams(auth, domain);
|
|
248
|
+
const absentRequired = missingRequiredSecrets(headerRes, queryRes, pathRes);
|
|
249
|
+
if (absentRequired.length > 0) {
|
|
250
|
+
return (
|
|
251
|
+
`🔑 auth: requires ${absentRequired.join(", ")} — not provisioned. ` +
|
|
252
|
+
`Run /api secrets ${domain}.` +
|
|
253
|
+
provisionedDomainsSuffix(domain)
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
// The optional dimension only exists for refs actually marked
|
|
257
|
+
// optional (a ref with optional: true). Path refs are required-only
|
|
258
|
+
// (parse rejects `optional`), so they never contribute here — the
|
|
259
|
+
// spread is for hand-built auth symmetry only.
|
|
260
|
+
const referencedOptional = [
|
|
261
|
+
...Object.entries(auth.secretRefs ?? {}),
|
|
262
|
+
...Object.entries(auth.secretQueryRefs ?? {}),
|
|
263
|
+
...Object.entries(auth.secretPathRefs ?? {}),
|
|
264
|
+
]
|
|
265
|
+
.filter(([, r]) => r.optional)
|
|
266
|
+
.map(([, r]) => r.secret);
|
|
267
|
+
if (referencedOptional.length > 0) {
|
|
268
|
+
const absentOptional = [
|
|
269
|
+
...new Set([...headerRes.absentOptional, ...queryRes.absentOptional]),
|
|
270
|
+
];
|
|
271
|
+
if (absentOptional.length > 0) {
|
|
272
|
+
return (
|
|
273
|
+
`🔑 auth: ok (optional ${absentOptional.join(", ")} not ` +
|
|
274
|
+
`provisioned — unauthenticated; provision with /api secrets ${domain} for higher limits)`
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
return "🔑 auth: ok (optional provisioned)";
|
|
278
|
+
}
|
|
279
|
+
return "🔑 auth: ok";
|
|
280
|
+
}
|
|
281
|
+
case "oauth2": {
|
|
282
|
+
const token = readToken(domain, auth.grant, auth.tokenUrl);
|
|
283
|
+
if (!token) {
|
|
284
|
+
return `🔑 auth: oauth2 — no token. Run /api oauth ${domain}.`;
|
|
285
|
+
}
|
|
286
|
+
if (isTokenExpired(token)) {
|
|
287
|
+
return (
|
|
288
|
+
`🔑 auth: oauth2 — token expired` +
|
|
289
|
+
(token.refreshToken
|
|
290
|
+
? `, refreshable. Run /api oauth ${domain} --refresh.`
|
|
291
|
+
: `. Run /api oauth ${domain} to re-mint.`)
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
return "🔑 auth: ok (oauth2)";
|
|
295
|
+
}
|
|
296
|
+
default: {
|
|
297
|
+
const _exhaustive: never = auth;
|
|
298
|
+
throw new Error(`Unhandled auth kind: ${_exhaustive}`);
|
|
153
299
|
}
|
|
154
|
-
return "🔑 auth: ok (optional provisioned)";
|
|
155
300
|
}
|
|
156
|
-
return "🔑 auth: ok";
|
|
157
301
|
}
|
|
158
302
|
|
|
159
303
|
/**
|
|
@@ -184,3 +328,780 @@ export function scrubSecretValues(
|
|
|
184
328
|
}
|
|
185
329
|
return text;
|
|
186
330
|
}
|
|
331
|
+
|
|
332
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
333
|
+
// OAuth2 token resolution (client_credentials + lazy refresh)
|
|
334
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Thrown when an OAuth2 token can't be produced without human action (no
|
|
338
|
+
* cached token, no client_secret to mint, or an auth-code guide with no
|
|
339
|
+
* interactive flow). Callers fail closed and nudge `/api oauth <domain>`.
|
|
340
|
+
*/
|
|
341
|
+
export class OAuthTokenMissingError extends Error {
|
|
342
|
+
constructor(message: string) {
|
|
343
|
+
super(message);
|
|
344
|
+
this.name = "OAuthTokenMissingError";
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** Resolved OAuth2 token injection, shaped to drop straight into AuthOpts. */
|
|
349
|
+
export interface AccessTokenResult {
|
|
350
|
+
authHeaders?: Record<string, string>;
|
|
351
|
+
secretHeaderNames?: Set<string>;
|
|
352
|
+
secretQueryParams?: Record<string, string>;
|
|
353
|
+
secretQueryParamNames?: Set<string>;
|
|
354
|
+
secretValues: string[];
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Granted scopes for a minted token: what the provider echoed at mint;
|
|
358
|
+
* absent → the requested scopes with `assumed: true` (RFC 6749 §5.1 —
|
|
359
|
+
* granted = requested). Empty when neither is on record. */
|
|
360
|
+
export function grantedScopes(
|
|
361
|
+
scope: string | undefined,
|
|
362
|
+
requested: string[],
|
|
363
|
+
): { scopes: string[]; assumed: boolean } {
|
|
364
|
+
const echo = scope?.split(/\s+/).filter(Boolean) ?? [];
|
|
365
|
+
if (echo.length > 0) return { scopes: echo, assumed: false };
|
|
366
|
+
return { scopes: requested, assumed: requested.length > 0 };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Refresh the access token one round trip before real expiry. */
|
|
370
|
+
const EXPIRY_SKEW_MS = 60_000;
|
|
371
|
+
|
|
372
|
+
/** True when a cached token should be refreshed/re-minted (skewed early). */
|
|
373
|
+
export function isTokenExpired(
|
|
374
|
+
token: OAuthToken,
|
|
375
|
+
now: number = Date.now(),
|
|
376
|
+
): boolean {
|
|
377
|
+
if (token.expiresAt === undefined) {
|
|
378
|
+
// ponytail: no expires_in → treat as fresh; a provider that omits it
|
|
379
|
+
// will 401 and the next call re-mints. Add a TTL heuristic if a real
|
|
380
|
+
// recipe's short TTL makes this hurt.
|
|
381
|
+
return false;
|
|
382
|
+
}
|
|
383
|
+
return now >= token.expiresAt - EXPIRY_SKEW_MS;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Per-slot in-process lock keyed by `(storeDomain, slot)` — the same slot
|
|
388
|
+
* derivation the token store uses (two derivations that can diverge would be
|
|
389
|
+
* a second clobber), so concurrent `api-fetch` calls for the same slot
|
|
390
|
+
* serialize on one read-check-refresh-write sequence. Without it, two
|
|
391
|
+
* parallel calls that both see an expired token could race a refresh and
|
|
392
|
+
* double-spend a rotated refresh token. Cross-slot calls don't serialize —
|
|
393
|
+
* they touch different records; the store's synchronous read-modify-write
|
|
394
|
+
* keeps them atomic wrt the event loop.
|
|
395
|
+
*/
|
|
396
|
+
const tokenLocks = new Map<string, Promise<unknown>>();
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Run `fn` while holding the per-slot lock — serializes any read-check-refresh-write
|
|
400
|
+
* sequence for `(storeDomain, slot)`, so `--refresh`/mint paths can't race an
|
|
401
|
+
* agent's `resolveAccessToken` into double-spending a rotated refresh token.
|
|
402
|
+
*/
|
|
403
|
+
async function withSlotLock<T>(
|
|
404
|
+
auth: OAuth2Auth,
|
|
405
|
+
domain: string,
|
|
406
|
+
fn: () => Promise<T>,
|
|
407
|
+
): Promise<T> {
|
|
408
|
+
const lockKey = `${domain}:${slotKey(auth.grant, auth.tokenUrl)}`;
|
|
409
|
+
// Chain onto the current holder instead of wait-then-run: everyone who
|
|
410
|
+
// awaited the same in-flight promise would otherwise resume as a herd and
|
|
411
|
+
// run fn() concurrently (double-spending a rotated refresh token).
|
|
412
|
+
const prev = tokenLocks.get(lockKey) ?? Promise.resolve();
|
|
413
|
+
const next = prev.catch(() => {}).then(fn);
|
|
414
|
+
tokenLocks.set(lockKey, next);
|
|
415
|
+
try {
|
|
416
|
+
return await next;
|
|
417
|
+
} finally {
|
|
418
|
+
if (tokenLocks.get(lockKey) === next) tokenLocks.delete(lockKey);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Resolve an access token for an oauth2 auth (guide-backed or synthetic):
|
|
424
|
+
* cached → lazy refresh → client-credentials mint. Reads the token store
|
|
425
|
+
* fresh on every call (no closure cache) so a refresh on op N is visible to
|
|
426
|
+
* op N+1 during a long `/api verify` run. Fail-closed: throws `OAuthTokenMissingError` when no
|
|
427
|
+
* token exists and none can be minted.
|
|
428
|
+
*/
|
|
429
|
+
export async function resolveAccessToken(
|
|
430
|
+
auth: OAuth2Auth,
|
|
431
|
+
domain: string,
|
|
432
|
+
): Promise<AccessTokenResult> {
|
|
433
|
+
return withSlotLock(auth, domain, () => resolveTokenUnlocked(auth, domain));
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
async function resolveTokenUnlocked(
|
|
437
|
+
auth: OAuth2Auth,
|
|
438
|
+
domain: string,
|
|
439
|
+
): Promise<AccessTokenResult> {
|
|
440
|
+
let token = readToken(domain, auth.grant, auth.tokenUrl);
|
|
441
|
+
if (token && !isTokenExpired(token))
|
|
442
|
+
return toAccessTokenResult(auth, token, domain);
|
|
443
|
+
if (token?.refreshToken) {
|
|
444
|
+
try {
|
|
445
|
+
token = await refreshAccessToken(auth, domain, token.refreshToken);
|
|
446
|
+
writeToken(domain, auth.grant, auth.tokenUrl, token);
|
|
447
|
+
return toAccessTokenResult(auth, token, domain);
|
|
448
|
+
} catch {
|
|
449
|
+
// Refresh failed (rotated/revoked refresh token, endpoint down) —
|
|
450
|
+
// fall through to re-mint; the mint surfaces the real failure.
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
if (auth.grant === "client_credentials") {
|
|
454
|
+
token = await mintClientCredentialsToken(auth, domain);
|
|
455
|
+
writeToken(domain, auth.grant, auth.tokenUrl, token);
|
|
456
|
+
return toAccessTokenResult(auth, token, domain);
|
|
457
|
+
}
|
|
458
|
+
// authorization_code: no interactive mint here — fail closed with
|
|
459
|
+
// a nudge to /api oauth.
|
|
460
|
+
throw new OAuthTokenMissingError(
|
|
461
|
+
`No usable OAuth2 token for '${domain}' (grant: authorization_code). ` +
|
|
462
|
+
`Run /api oauth ${domain} to start the interactive flow.`,
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Loud misconfiguration guard: a static `Authorization` header (from
|
|
468
|
+
* secretRefs) collides with the oauth2 bearer injection — fetch merges
|
|
469
|
+
* same-named headers case-insensitively, so both would ride one garbled
|
|
470
|
+
* `Authorization: Bearer x, Bearer y` header. Fail loudly instead.
|
|
471
|
+
*/
|
|
472
|
+
export function assertNoBearerCollision(
|
|
473
|
+
headers: Record<string, string>,
|
|
474
|
+
source: string,
|
|
475
|
+
): void {
|
|
476
|
+
const clash = Object.keys(headers).find(
|
|
477
|
+
(k) => k.toLowerCase() === "authorization",
|
|
478
|
+
);
|
|
479
|
+
if (clash !== undefined) {
|
|
480
|
+
throw new Error(
|
|
481
|
+
`oauth2 bearer injection collides with the static '${clash}' header declared via ${source} — ` +
|
|
482
|
+
`declare the secret under a different header (e.g. Client-Id) or set paramStyle: query.`,
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/** Map a token set onto the AuthOpts shape (bearer-header or query style). */
|
|
488
|
+
function toAccessTokenResult(
|
|
489
|
+
auth: OAuth2Auth,
|
|
490
|
+
token: OAuthToken,
|
|
491
|
+
domain: string,
|
|
492
|
+
): AccessTokenResult {
|
|
493
|
+
// secretRefs (e.g. Twitch's Client-Id) merge onto the same header map —
|
|
494
|
+
// SAME semantics as static-key: resolved from the secrets store,
|
|
495
|
+
// fail-closed when a required one is missing.
|
|
496
|
+
const resolvedHeaders: Record<string, string> = {};
|
|
497
|
+
const resolvedValues: string[] = [];
|
|
498
|
+
for (const [headerName, ref] of Object.entries(auth.secretRefs ?? {})) {
|
|
499
|
+
const value = readSecret(domain, ref.secret);
|
|
500
|
+
if (value === null) {
|
|
501
|
+
if (ref.optional) continue;
|
|
502
|
+
throw new OAuthTokenMissingError(
|
|
503
|
+
`OAuth2 request header '${headerName}' needs the secret '${ref.secret}' provisioned ` +
|
|
504
|
+
`for '${domain}'. Run /api secrets ${domain} then /api oauth ${domain}.`,
|
|
505
|
+
);
|
|
506
|
+
}
|
|
507
|
+
resolvedHeaders[headerName] = (ref.prefix ?? "") + value;
|
|
508
|
+
resolvedValues.push(value);
|
|
509
|
+
}
|
|
510
|
+
const style = auth.paramStyle ?? "bearer-header";
|
|
511
|
+
if (style === "query") {
|
|
512
|
+
// RFC 6750 §2.3 — the query-injected param name is `access_token`.
|
|
513
|
+
return {
|
|
514
|
+
...(Object.keys(resolvedHeaders).length > 0
|
|
515
|
+
? {
|
|
516
|
+
authHeaders: resolvedHeaders,
|
|
517
|
+
// Strip them on cross-domain redirect hops, same as bearer style.
|
|
518
|
+
secretHeaderNames: new Set(
|
|
519
|
+
Object.keys(resolvedHeaders).map((h) => h.toLowerCase()),
|
|
520
|
+
),
|
|
521
|
+
}
|
|
522
|
+
: {}),
|
|
523
|
+
secretQueryParams: { access_token: token.accessToken },
|
|
524
|
+
secretQueryParamNames: new Set(["access_token"]),
|
|
525
|
+
secretValues: [token.accessToken, ...resolvedValues],
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
assertNoBearerCollision(resolvedHeaders, "secretRefs");
|
|
529
|
+
return {
|
|
530
|
+
authHeaders: {
|
|
531
|
+
authorization: `Bearer ${token.accessToken}`,
|
|
532
|
+
...resolvedHeaders,
|
|
533
|
+
},
|
|
534
|
+
secretHeaderNames: new Set([
|
|
535
|
+
"authorization",
|
|
536
|
+
...Object.keys(resolvedHeaders).map((h) => h.toLowerCase()),
|
|
537
|
+
]),
|
|
538
|
+
secretValues: [token.accessToken, ...resolvedValues],
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* The client credentials for an oauth2 guide: resolved from the secrets
|
|
544
|
+
* store via the guide's named `clientId` / `clientSecret` SecretRefs
|
|
545
|
+
* (store-resolved values appear ONLY as `SecretRef.secret` — a shippable
|
|
546
|
+
* guide bakes in no per-user registration). Null secret when the guide
|
|
547
|
+
* declares no `clientSecret` (PKCE auth-code apps) or the store lacks it.
|
|
548
|
+
* Throws `OAuthTokenMissingError` when the client id's store name is absent —
|
|
549
|
+
* the token endpoint cannot be called without it — or when a declared,
|
|
550
|
+
* non-optional `clientSecret` is unprovisioned (fail closed with a naming
|
|
551
|
+
* nudge rather than silently degrading to an unauthenticated public client
|
|
552
|
+
* and a bare provider `invalid_client` at exchange time).
|
|
553
|
+
*/
|
|
554
|
+
export function resolveClientCredentials(
|
|
555
|
+
auth: OAuth2Auth,
|
|
556
|
+
domain: string,
|
|
557
|
+
): {
|
|
558
|
+
clientId: string;
|
|
559
|
+
clientSecret: { secret: string; refName: string } | null;
|
|
560
|
+
} {
|
|
561
|
+
const clientId = readSecret(domain, auth.clientId.secret);
|
|
562
|
+
if (clientId === null) {
|
|
563
|
+
throw new OAuthTokenMissingError(
|
|
564
|
+
`OAuth2 needs the client id '${auth.clientId.secret}' provisioned ` +
|
|
565
|
+
`for '${domain}'. Run /api secrets ${domain} then /api oauth ${domain}.`,
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
const ref = auth.clientSecret;
|
|
569
|
+
const clientSecret = ref ? readSecret(domain, ref.secret) : null;
|
|
570
|
+
if (ref && clientSecret === null && !ref.optional) {
|
|
571
|
+
throw new OAuthTokenMissingError(
|
|
572
|
+
`OAuth2 client secret '${ref.secret}' is declared but not provisioned ` +
|
|
573
|
+
`for '${domain}'. Run /api secrets ${domain} ${ref.secret}, or mark ` +
|
|
574
|
+
`the ref optional to proceed as a PKCE public client.`,
|
|
575
|
+
);
|
|
576
|
+
}
|
|
577
|
+
return {
|
|
578
|
+
clientId,
|
|
579
|
+
...(clientSecret !== null && ref
|
|
580
|
+
? { clientSecret: { secret: clientSecret, refName: ref.secret } }
|
|
581
|
+
: { clientSecret: null }),
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* Which of the given secrets-store NAMES are not provisioned for `domain`.
|
|
587
|
+
* Shared by oauth-mint and /api oauth init — both mint paths key credentials
|
|
588
|
+
* on store NAMEs (values never enter the transcript), so both precheck the
|
|
589
|
+
* same store before touching any prompt or endpoint.
|
|
590
|
+
*/
|
|
591
|
+
export function missingCredentialNames(
|
|
592
|
+
domain: string,
|
|
593
|
+
names: string[],
|
|
594
|
+
): string[] {
|
|
595
|
+
const provisioned = listNames(domain);
|
|
596
|
+
return names.filter((n) => !provisioned.includes(n));
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* Shared store-name precheck for both mint paths (oauth-mint tool +
|
|
601
|
+
* `/api oauth init`): returns the user-facing gap message, or null when all
|
|
602
|
+
* credential NAMES are provisioned. Keeps the security prose
|
|
603
|
+
* ("values never enter the transcript") in exactly one place.
|
|
604
|
+
* Caller decides delivery: notify (command) vs throw (tool).
|
|
605
|
+
*/
|
|
606
|
+
export function credentialNameGap(
|
|
607
|
+
storeDomain: string,
|
|
608
|
+
clientId: string,
|
|
609
|
+
clientSecret?: string,
|
|
610
|
+
): string | null {
|
|
611
|
+
const missing = missingCredentialNames(storeDomain, [
|
|
612
|
+
clientId,
|
|
613
|
+
...(clientSecret === undefined ? [] : [clientSecret]),
|
|
614
|
+
]);
|
|
615
|
+
if (missing.length === 0) return null;
|
|
616
|
+
return (
|
|
617
|
+
`OAuth2 client credentials must be provisioned store NAMEs, but ${missing.map((n) => `'${n}'`).join(", ")} ` +
|
|
618
|
+
`are not in the secrets store for '${storeDomain}'. ` +
|
|
619
|
+
`Provision them first: /api secrets ${storeDomain} <name> (values never enter the transcript).`
|
|
620
|
+
);
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* Mint-time overwrite warning: slots are keyed (domain, grant, tokenUrl), so
|
|
625
|
+
* a same-grant re-mint with different scopes/issuer silently replaces the
|
|
626
|
+
* previous token — the documented mitigation for the reserved slot-key seam
|
|
627
|
+
* (scopes/clientId are deliberately excluded from the key). Returns the
|
|
628
|
+
* warning text when a token already occupies the slot, else null; callers
|
|
629
|
+
* render via ctx.ui.notify (this module stays ui-free).
|
|
630
|
+
*/
|
|
631
|
+
export function slotOverwriteWarning(
|
|
632
|
+
auth: OAuth2Auth,
|
|
633
|
+
domain: string,
|
|
634
|
+
): string | null {
|
|
635
|
+
const existing = readToken(domain, auth.grant, auth.tokenUrl);
|
|
636
|
+
if (!existing) return null;
|
|
637
|
+
return `⚠ Overwriting an existing token for this slot (${auth.grant}) — previous scope: ${existing.scope ?? "(none)"}.`;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* Fresh client_credentials mint: drop the slot's cached token, then mint.
|
|
642
|
+
* Shared by `/api oauth init` and oauth-mint — bootstrap paths that always
|
|
643
|
+
* want a fresh mint, never a cached token. Both must slot-scope the delete
|
|
644
|
+
* (a bare domain delete would leave a stale prior-grant/prior-issuer slot
|
|
645
|
+
* surviving the re-mint). NOTE: the plain command's `--refresh` arm stays
|
|
646
|
+
* inline — its delete is conditional on the flag; resolving the cached
|
|
647
|
+
* token is the default there.
|
|
648
|
+
*/
|
|
649
|
+
export async function mintFreshClientCredentials(
|
|
650
|
+
auth: OAuth2Auth,
|
|
651
|
+
domain: string,
|
|
652
|
+
): Promise<void> {
|
|
653
|
+
deleteToken(domain, auth.grant, auth.tokenUrl);
|
|
654
|
+
await resolveAccessToken(auth, domain);
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* True when a token can be produced without human interaction: a cached
|
|
659
|
+
* fresh token, a refreshable one, or (client_credentials) a provisioned
|
|
660
|
+
* client secret to mint from. Used by the `/api verify` precheck to
|
|
661
|
+
* fail-fast instead of surfacing N identical token-missing failures.
|
|
662
|
+
*/
|
|
663
|
+
export function hasUsableTokenPath(auth: OAuth2Auth, domain: string): boolean {
|
|
664
|
+
const token = readToken(domain, auth.grant, auth.tokenUrl);
|
|
665
|
+
if (token && !isTokenExpired(token)) return true;
|
|
666
|
+
if (token?.refreshToken) return true;
|
|
667
|
+
if (auth.grant === "client_credentials") {
|
|
668
|
+
return (
|
|
669
|
+
readSecret(domain, auth.clientId.secret) !== null &&
|
|
670
|
+
auth.clientSecret !== undefined &&
|
|
671
|
+
readSecret(domain, auth.clientSecret.secret) !== null
|
|
672
|
+
);
|
|
673
|
+
}
|
|
674
|
+
return false;
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
/**
|
|
678
|
+
* Attach client authentication to a token-endpoint request (RFC 6749 §2.3):
|
|
679
|
+
* `client_secret_basic` → Basic Authorization header, `client_secret_post`
|
|
680
|
+
* (the default) → `client_secret` form field. Mutates `form` / `headers`.
|
|
681
|
+
* No-op without a client secret (PKCE public clients). Returns extra values
|
|
682
|
+
* callers must add to their `secretValues` scrub set — the Basic credential
|
|
683
|
+
* (`base64(clientId:secret)`, and its full header form) is a secret a
|
|
684
|
+
* token-endpoint error body can echo, just like the raw secret.
|
|
685
|
+
*/
|
|
686
|
+
function applyClientAuth(
|
|
687
|
+
auth: OAuth2Auth,
|
|
688
|
+
clientId: string,
|
|
689
|
+
clientSecret: { secret: string } | null,
|
|
690
|
+
form: Record<string, string>,
|
|
691
|
+
headers: Record<string, string>,
|
|
692
|
+
): string[] {
|
|
693
|
+
if (!clientSecret) return [];
|
|
694
|
+
const method = auth.tokenEndpointAuthMethod ?? "client_secret_post";
|
|
695
|
+
if (method === "client_secret_basic") {
|
|
696
|
+
const cred = Buffer.from(`${clientId}:${clientSecret.secret}`).toString(
|
|
697
|
+
"base64",
|
|
698
|
+
);
|
|
699
|
+
headers["authorization"] = "Basic " + cred;
|
|
700
|
+
return [cred, `Basic ${cred}`];
|
|
701
|
+
}
|
|
702
|
+
if (method === "client_secret_post") {
|
|
703
|
+
form["client_secret"] = clientSecret.secret;
|
|
704
|
+
}
|
|
705
|
+
return [];
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* Exchange an authorization code for a token set (PKCE verifier in the
|
|
710
|
+
* body). `redirectUri` must be the SAME URI sent in the authorize step.
|
|
711
|
+
* The client secret (when the guide declares one) rides per
|
|
712
|
+
* `tokenEndpointAuthMethod`; PKCE public clients send none.
|
|
713
|
+
*/
|
|
714
|
+
export async function exchangeAuthCode(
|
|
715
|
+
auth: OAuth2Auth,
|
|
716
|
+
domain: string,
|
|
717
|
+
code: string,
|
|
718
|
+
redirectUri: string,
|
|
719
|
+
verifier: string,
|
|
720
|
+
): Promise<OAuthToken> {
|
|
721
|
+
const { clientId, clientSecret } = resolveClientCredentials(auth, domain);
|
|
722
|
+
const form: Record<string, string> = {
|
|
723
|
+
grant_type: "authorization_code",
|
|
724
|
+
code,
|
|
725
|
+
redirect_uri: redirectUri,
|
|
726
|
+
client_id: clientId,
|
|
727
|
+
code_verifier: verifier,
|
|
728
|
+
};
|
|
729
|
+
const headers: Record<string, string> = {};
|
|
730
|
+
const clientAuthValues = applyClientAuth(
|
|
731
|
+
auth,
|
|
732
|
+
clientId,
|
|
733
|
+
clientSecret,
|
|
734
|
+
form,
|
|
735
|
+
headers,
|
|
736
|
+
);
|
|
737
|
+
const data = await oauthPost(auth.tokenUrl, form, headers, [
|
|
738
|
+
code,
|
|
739
|
+
...(clientSecret ? [clientSecret.secret] : []),
|
|
740
|
+
...clientAuthValues,
|
|
741
|
+
]);
|
|
742
|
+
return tokenFromResponse(data);
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/**
|
|
746
|
+
* Force a fresh token for an auth-code guide by refreshing via the stored
|
|
747
|
+
* refresh token (no re-consent). Throws `OAuthTokenMissingError` when there
|
|
748
|
+
* is no refresh token — the caller falls back to the interactive flow.
|
|
749
|
+
*/
|
|
750
|
+
export async function forceRefreshToken(
|
|
751
|
+
auth: OAuth2Auth,
|
|
752
|
+
domain: string,
|
|
753
|
+
): Promise<OAuthToken> {
|
|
754
|
+
return withSlotLock(auth, domain, () =>
|
|
755
|
+
forceRefreshTokenUnlocked(auth, domain),
|
|
756
|
+
);
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
async function forceRefreshTokenUnlocked(
|
|
760
|
+
auth: OAuth2Auth,
|
|
761
|
+
domain: string,
|
|
762
|
+
): Promise<OAuthToken> {
|
|
763
|
+
const token = readToken(domain, auth.grant, auth.tokenUrl);
|
|
764
|
+
if (!token?.refreshToken) {
|
|
765
|
+
throw new OAuthTokenMissingError(
|
|
766
|
+
`No refresh token for '${domain}' — run /api oauth ${domain} to start the interactive flow.`,
|
|
767
|
+
);
|
|
768
|
+
}
|
|
769
|
+
const fresh = await refreshAccessToken(auth, domain, token.refreshToken);
|
|
770
|
+
writeToken(domain, auth.grant, auth.tokenUrl, fresh);
|
|
771
|
+
return fresh;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/**
|
|
775
|
+
* One POST to an OAuth2 endpoint (token/refresh/revoke) — the first non-GET
|
|
776
|
+
* requests host makes, kept OUT of `transport.ts` (GET-only by contract) in
|
|
777
|
+
* a small separate helper. `secretValues` are scrubbed from any error body
|
|
778
|
+
* so a server echoing a credential can't leak it into agent context.
|
|
779
|
+
*
|
|
780
|
+
* Returns the parsed JSON body, or `{}` for an empty/non-JSON body (valid
|
|
781
|
+
* for RFC 7009 revocation, which returns 200 OK with no body). Callers that
|
|
782
|
+
* need a token validate `access_token` themselves via `tokenFromResponse`.
|
|
783
|
+
*/
|
|
784
|
+
async function oauthPost(
|
|
785
|
+
url: string,
|
|
786
|
+
form: Record<string, string>,
|
|
787
|
+
headers: Record<string, string>,
|
|
788
|
+
secretValues: string[],
|
|
789
|
+
): Promise<Record<string, unknown>> {
|
|
790
|
+
// ponytail: fixed 30s matching transport's DEFAULT_TIMEOUT — configurable
|
|
791
|
+
// only if a provider ever needs more. Without this, a hung token endpoint
|
|
792
|
+
// holds the per-slot lock (and the user's command) until undici's 300s
|
|
793
|
+
// headersTimeout finally gives up.
|
|
794
|
+
const ac = new AbortController();
|
|
795
|
+
const timer = setTimeout(
|
|
796
|
+
() => ac.abort(new Error("OAuth2 endpoint timeout (30s)")),
|
|
797
|
+
30_000,
|
|
798
|
+
);
|
|
799
|
+
try {
|
|
800
|
+
// The timer spans headers AND the body read — a server that sends
|
|
801
|
+
// headers then stalls mid-body is hung just as hard as one that never
|
|
802
|
+
// answers (mirrors singleGet's abort scope in transport.ts).
|
|
803
|
+
const res = await fetch(url, {
|
|
804
|
+
method: "POST",
|
|
805
|
+
redirect: "error", // token endpoints never redirect; a 3xx must not forward secret-bearing bodies
|
|
806
|
+
headers: {
|
|
807
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
808
|
+
...headers,
|
|
809
|
+
},
|
|
810
|
+
body: new URLSearchParams(form).toString(),
|
|
811
|
+
signal: ac.signal,
|
|
812
|
+
});
|
|
813
|
+
const text = await res.text();
|
|
814
|
+
if (!res.ok) {
|
|
815
|
+
// Scrub before slicing — a secret straddling the cut would otherwise
|
|
816
|
+
// leave its prefix unredacted.
|
|
817
|
+
throw new Error(
|
|
818
|
+
`OAuth2 endpoint ${res.status}: ${scrubSecretValues(text, secretValues).slice(0, 300)}`,
|
|
819
|
+
);
|
|
820
|
+
}
|
|
821
|
+
try {
|
|
822
|
+
const data = JSON.parse(text);
|
|
823
|
+
if (data && typeof data === "object" && !Array.isArray(data)) {
|
|
824
|
+
return data as Record<string, unknown>;
|
|
825
|
+
}
|
|
826
|
+
} catch {
|
|
827
|
+
// empty / non-JSON body — valid for revocation (RFC 7009)
|
|
828
|
+
}
|
|
829
|
+
return {};
|
|
830
|
+
} finally {
|
|
831
|
+
clearTimeout(timer);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
function tokenFromResponse(data: Record<string, unknown>): OAuthToken {
|
|
836
|
+
const at = data["access_token"];
|
|
837
|
+
if (typeof at !== "string") {
|
|
838
|
+
throw new Error("OAuth2 token endpoint returned no access_token");
|
|
839
|
+
}
|
|
840
|
+
const token: OAuthToken = {
|
|
841
|
+
accessToken: at,
|
|
842
|
+
};
|
|
843
|
+
if (typeof data["refresh_token"] === "string") {
|
|
844
|
+
token.refreshToken = data["refresh_token"];
|
|
845
|
+
}
|
|
846
|
+
// Some providers return a string despite RFC 6749 §5.1 — coerce or the
|
|
847
|
+
// token is cached as eternal (isTokenExpired treats missing expiresAt as fresh).
|
|
848
|
+
const raw = data["expires_in"];
|
|
849
|
+
const expiresIn = typeof raw === "string" ? Number(raw) : raw;
|
|
850
|
+
if (typeof expiresIn === "number" && Number.isFinite(expiresIn)) {
|
|
851
|
+
token.expiresAt = Date.now() + expiresIn * 1000;
|
|
852
|
+
}
|
|
853
|
+
if (typeof data["scope"] === "string") token.scope = data["scope"];
|
|
854
|
+
return token;
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
/** Client-credentials mint: POST grant_type=client_credentials → token. */
|
|
858
|
+
async function mintClientCredentialsToken(
|
|
859
|
+
auth: OAuth2Auth,
|
|
860
|
+
domain: string,
|
|
861
|
+
): Promise<OAuthToken> {
|
|
862
|
+
const { clientId, clientSecret } = resolveClientCredentials(auth, domain);
|
|
863
|
+
if (!clientSecret) {
|
|
864
|
+
const refName = auth.clientSecret?.secret ?? "client_secret";
|
|
865
|
+
throw new OAuthTokenMissingError(
|
|
866
|
+
`OAuth2 client_credentials needs the client secret '${refName}' provisioned ` +
|
|
867
|
+
`for '${domain}'. Run /api secrets ${domain} then /api oauth ${domain}.`,
|
|
868
|
+
);
|
|
869
|
+
}
|
|
870
|
+
const form: Record<string, string> = {
|
|
871
|
+
grant_type: "client_credentials",
|
|
872
|
+
client_id: clientId,
|
|
873
|
+
};
|
|
874
|
+
const headers: Record<string, string> = {};
|
|
875
|
+
const clientAuthValues = applyClientAuth(
|
|
876
|
+
auth,
|
|
877
|
+
clientId,
|
|
878
|
+
clientSecret,
|
|
879
|
+
form,
|
|
880
|
+
headers,
|
|
881
|
+
);
|
|
882
|
+
if (auth.scopes && auth.scopes.length > 0) {
|
|
883
|
+
form["scope"] = auth.scopes.join(" ");
|
|
884
|
+
}
|
|
885
|
+
const data = await oauthPost(auth.tokenUrl, form, headers, [
|
|
886
|
+
clientSecret.secret,
|
|
887
|
+
...clientAuthValues,
|
|
888
|
+
]);
|
|
889
|
+
return tokenFromResponse(data);
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
/** Lazy refresh: POST grant_type=refresh_token → fresh token set. */
|
|
893
|
+
async function refreshAccessToken(
|
|
894
|
+
auth: OAuth2Auth,
|
|
895
|
+
domain: string,
|
|
896
|
+
refreshToken: string,
|
|
897
|
+
): Promise<OAuthToken> {
|
|
898
|
+
const { clientId, clientSecret } = resolveClientCredentials(auth, domain);
|
|
899
|
+
const form: Record<string, string> = {
|
|
900
|
+
grant_type: "refresh_token",
|
|
901
|
+
refresh_token: refreshToken,
|
|
902
|
+
client_id: clientId,
|
|
903
|
+
};
|
|
904
|
+
const headers: Record<string, string> = {};
|
|
905
|
+
const clientAuthValues = applyClientAuth(
|
|
906
|
+
auth,
|
|
907
|
+
clientId,
|
|
908
|
+
clientSecret,
|
|
909
|
+
form,
|
|
910
|
+
headers,
|
|
911
|
+
);
|
|
912
|
+
const data = await oauthPost(auth.tokenUrl, form, headers, [
|
|
913
|
+
refreshToken,
|
|
914
|
+
...(clientSecret ? [clientSecret.secret] : []),
|
|
915
|
+
...clientAuthValues,
|
|
916
|
+
]);
|
|
917
|
+
const fresh = tokenFromResponse(data);
|
|
918
|
+
// RFC 6749 §6: the refresh response MAY omit refresh_token (e.g. GitHub,
|
|
919
|
+
// OSM) — the old one stays valid. Carry it forward so refresh capability
|
|
920
|
+
// isn't silently destroyed on the next expiry.
|
|
921
|
+
if (!fresh.refreshToken) fresh.refreshToken = refreshToken;
|
|
922
|
+
return fresh;
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
/**
|
|
926
|
+
* Best-effort revocation: POST the access token to the guide's declared
|
|
927
|
+
* `revokeUrl` (if any), then clear the local token store regardless.
|
|
928
|
+
*/
|
|
929
|
+
export async function revokeAccessToken(
|
|
930
|
+
auth: OAuth2Auth,
|
|
931
|
+
domain: string,
|
|
932
|
+
): Promise<void> {
|
|
933
|
+
const token = readToken(domain, auth.grant, auth.tokenUrl);
|
|
934
|
+
if (token && auth.revokeUrl) {
|
|
935
|
+
try {
|
|
936
|
+
const { clientId, clientSecret } = resolveClientCredentials(auth, domain);
|
|
937
|
+
const form: Record<string, string> = { token: token.accessToken };
|
|
938
|
+
const headers: Record<string, string> = {};
|
|
939
|
+
const clientAuthValues = applyClientAuth(
|
|
940
|
+
auth,
|
|
941
|
+
clientId,
|
|
942
|
+
clientSecret,
|
|
943
|
+
form,
|
|
944
|
+
headers,
|
|
945
|
+
);
|
|
946
|
+
await oauthPost(auth.revokeUrl, form, headers, [
|
|
947
|
+
token.accessToken,
|
|
948
|
+
...(clientSecret ? [clientSecret.secret] : []),
|
|
949
|
+
...clientAuthValues,
|
|
950
|
+
]);
|
|
951
|
+
} catch {
|
|
952
|
+
// best-effort — the local store is cleared regardless
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
deleteToken(domain, auth.grant, auth.tokenUrl);
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
// ═══════════════════════════════════════════════════════════════
|
|
959
|
+
// Guide-less bootstrap — shared synthetic-auth construction
|
|
960
|
+
// ═══════════════════════════════════════════════════════════════
|
|
961
|
+
|
|
962
|
+
/**
|
|
963
|
+
* Secrets-store domain for a not-yet-guided hostname: the hostname when it is
|
|
964
|
+
* itself provisioned, else the longest provisioned parent domain
|
|
965
|
+
* (api.openstreetmap.org → openstreetmap.org), else the hostname as-is (fail
|
|
966
|
+
* at exchange, not silently). Matched against the SECRETS store — the wizard
|
|
967
|
+
* and the probe both resolve credentials from it. ponytail: parent-suffix
|
|
968
|
+
* match against the store, not a public-suffix list — no dep, and the store
|
|
969
|
+
* is the source of truth for where secrets live.
|
|
970
|
+
*/
|
|
971
|
+
export function resolveProvisionedParentDomain(hostname: string): string {
|
|
972
|
+
const domains = listDomains();
|
|
973
|
+
if (domains.includes(hostname)) return hostname;
|
|
974
|
+
const parent = domains
|
|
975
|
+
.filter((d) => hostname.endsWith(`.${d}`))
|
|
976
|
+
.sort((a, b) => b.length - a.length)[0];
|
|
977
|
+
return parent ?? hostname;
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
/**
|
|
981
|
+
* Scrub-set forms for a resolved path-secret value: raw + both hex-encoded
|
|
982
|
+
* echo shapes (upper, as `fillPathTemplate` produces, and lower). A 401 body
|
|
983
|
+
* echoing the token inside a URL string (`bot123%3AABC…`) is the most likely
|
|
984
|
+
* echo shape — scrubSecretValues replaces raw values only. Single source for
|
|
985
|
+
* every site that folds path secrets into a body/header scrub set.
|
|
986
|
+
*/
|
|
987
|
+
export function pathScrubValues(values: Record<string, string>): string[] {
|
|
988
|
+
return Object.values(values).flatMap((v) => {
|
|
989
|
+
if (v.length === 0) return [];
|
|
990
|
+
const enc = encodeURIComponent(v);
|
|
991
|
+
return [v, enc, enc.replace(/%../g, (s) => s.toLowerCase())];
|
|
992
|
+
});
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
/** Hostname of an apiHost URL (falls back to the raw string). */
|
|
996
|
+
export function hostnameOf(apiHost: string): string {
|
|
997
|
+
try {
|
|
998
|
+
return new URL(apiHost).hostname;
|
|
999
|
+
} catch {
|
|
1000
|
+
return apiHost;
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
/** Fields the bootstrap surfaces collect into a synthetic `OAuth2Auth`. */
|
|
1005
|
+
export interface SyntheticOAuth2Fields {
|
|
1006
|
+
grant: OAuth2Grant;
|
|
1007
|
+
tokenUrl: string;
|
|
1008
|
+
/** secrets-store NAME — the value resolves at flow time, never a literal. */
|
|
1009
|
+
clientId: string;
|
|
1010
|
+
clientSecret?: string;
|
|
1011
|
+
authorizeUrl?: string;
|
|
1012
|
+
scopes?: string[];
|
|
1013
|
+
tokenEndpointAuthMethod?: OAuth2TokenEndpointAuthMethod;
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
/**
|
|
1017
|
+
* Build a synthetic oauth2 auth for the guide-less bootstrap paths (`/api
|
|
1018
|
+
* oauth init <domain>` and api-probe's mint arm). Shared construction pattern:
|
|
1019
|
+
* the synthetic auth feeds the existing resolveAccessToken / mintAuthCodeToken
|
|
1020
|
+
* machinery, so cache/refresh/lock/stamp is shared code. Fail-closed (command
|
|
1021
|
+
* semantics — the probe wraps its own try/catch around the flow): invalid
|
|
1022
|
+
* combinations throw instead of parsing loosely.
|
|
1023
|
+
*/
|
|
1024
|
+
export function buildSyntheticOAuth2Auth(f: SyntheticOAuth2Fields): OAuth2Auth {
|
|
1025
|
+
if (!isOAuth2Grant(f.grant)) {
|
|
1026
|
+
throw new Error(
|
|
1027
|
+
`--grant must be ${OAUTH2_GRANTS.join(" | ")} (got: ${String(f.grant)})`,
|
|
1028
|
+
);
|
|
1029
|
+
}
|
|
1030
|
+
if (!isHttpUrl(f.tokenUrl)) {
|
|
1031
|
+
throw new Error(`--token-url must be an http(s) URL (got: ${f.tokenUrl})`);
|
|
1032
|
+
}
|
|
1033
|
+
if (!f.clientId) {
|
|
1034
|
+
throw new Error("--client-id (a provisioned store NAME) is required.");
|
|
1035
|
+
}
|
|
1036
|
+
if (
|
|
1037
|
+
f.tokenEndpointAuthMethod !== undefined &&
|
|
1038
|
+
!isOAuth2TokenEndpointAuthMethod(f.tokenEndpointAuthMethod)
|
|
1039
|
+
) {
|
|
1040
|
+
throw new Error(
|
|
1041
|
+
`--token-endpoint-auth-method must be ${OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS.join(" | ")} (got: ${String(f.tokenEndpointAuthMethod)})`,
|
|
1042
|
+
);
|
|
1043
|
+
}
|
|
1044
|
+
if (f.authorizeUrl !== undefined && !isHttpUrl(f.authorizeUrl)) {
|
|
1045
|
+
throw new Error(
|
|
1046
|
+
`--authorize-url must be an http(s) URL (got: ${f.authorizeUrl})`,
|
|
1047
|
+
);
|
|
1048
|
+
}
|
|
1049
|
+
// An empty-string secret is a mistyped flag, not a credential — treat it
|
|
1050
|
+
// as absent so client_credentials fails loudly here (store resolution
|
|
1051
|
+
// would only misreport it later).
|
|
1052
|
+
const clientSecret = f.clientSecret || undefined;
|
|
1053
|
+
// Grant invariants — shared with the guide parser (parse-api-guide.ts);
|
|
1054
|
+
// one statement of the cross-field rules for both surfaces.
|
|
1055
|
+
const issue = oauth2GrantIssue({
|
|
1056
|
+
grant: f.grant,
|
|
1057
|
+
hasClientSecret: clientSecret !== undefined,
|
|
1058
|
+
authorizeUrl: f.authorizeUrl,
|
|
1059
|
+
tokenEndpointAuthMethod: f.tokenEndpointAuthMethod,
|
|
1060
|
+
});
|
|
1061
|
+
if (issue) {
|
|
1062
|
+
throw new Error(syntheticGrantIssueMessage(issue.code));
|
|
1063
|
+
}
|
|
1064
|
+
const auth: OAuth2Auth = {
|
|
1065
|
+
kind: "oauth2",
|
|
1066
|
+
grant: f.grant,
|
|
1067
|
+
tokenUrl: f.tokenUrl,
|
|
1068
|
+
clientId: { secret: f.clientId },
|
|
1069
|
+
};
|
|
1070
|
+
if (clientSecret !== undefined) {
|
|
1071
|
+
auth.clientSecret = { secret: clientSecret };
|
|
1072
|
+
}
|
|
1073
|
+
if (f.scopes !== undefined && f.scopes.length > 0) {
|
|
1074
|
+
auth.scopes = f.scopes;
|
|
1075
|
+
}
|
|
1076
|
+
if (f.tokenEndpointAuthMethod !== undefined) {
|
|
1077
|
+
auth.tokenEndpointAuthMethod = f.tokenEndpointAuthMethod;
|
|
1078
|
+
}
|
|
1079
|
+
if (f.authorizeUrl !== undefined) {
|
|
1080
|
+
auth.authorizeUrl = f.authorizeUrl;
|
|
1081
|
+
}
|
|
1082
|
+
return auth;
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
/** CLI-flag phrasing of the shared grant-invariant codes for the
|
|
1086
|
+
* bootstrap surfaces (`/api oauth init`, api-probe mint arm, oauth-mint). */
|
|
1087
|
+
function syntheticGrantIssueMessage(code: OAuth2GrantIssue["code"]): string {
|
|
1088
|
+
switch (code) {
|
|
1089
|
+
case "noneWithSecret":
|
|
1090
|
+
return "--token-endpoint-auth-method none sends no client credentials — drop --client-secret.";
|
|
1091
|
+
case "ccRequiresSecret":
|
|
1092
|
+
return "grant client_credentials requires --client-secret (a provisioned store NAME).";
|
|
1093
|
+
case "ccRejectsAuthorizeUrl":
|
|
1094
|
+
return "--authorize-url is only valid with --grant authorization_code (client_credentials is server-to-server).";
|
|
1095
|
+
case "acRequiresAuthorizeUrl":
|
|
1096
|
+
return "grant authorization_code requires --authorize-url (the provider's authorization endpoint).";
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
function isHttpUrl(s: string): boolean {
|
|
1101
|
+
try {
|
|
1102
|
+
const u = new URL(s);
|
|
1103
|
+
return u.protocol === "https:" || u.protocol === "http:";
|
|
1104
|
+
} catch {
|
|
1105
|
+
return false;
|
|
1106
|
+
}
|
|
1107
|
+
}
|