fffleet 2.9.0 → 2.10.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/index.d.ts CHANGED
@@ -336,6 +336,10 @@ export interface FleetOptions {
336
336
  /** With `clientSecret`: log in at the orchestrator (POST /v1/auth/token) and refresh the token before it expires. */
337
337
  clientId?: string;
338
338
  clientSecret?: string;
339
+ /** With `clientId`/`clientSecret`: get tokens from this OAuth2 token endpoint (an external issuer) instead of the orchestrator's own. */
340
+ tokenUrl?: string;
341
+ /** Resource indicator (RFC 8707) sent with the token request, for issuers that bind tokens to an audience. */
342
+ tokenResource?: string;
339
343
  /** Narrow the token to some of the app's scopes, e.g. 'jobs'. */
340
344
  scope?: string;
341
345
  /** 'local' (default) runs a job here when the remote cannot be reached or answers 502/503. */
@@ -409,7 +413,7 @@ export class JobRecord {
409
413
  export function byPriority(a: JobRecord, b: JobRecord): number;
410
414
  export function pruneFinished(jobs: Map<string, JobRecord>, keep: number): void;
411
415
 
412
- export type Scope = 'jobs' | 'metrics' | 'admin';
416
+ export type Scope = 'jobs' | 'metrics' | 'admin' | 'worker' | 'dispatch';
413
417
  export const SCOPES: readonly Scope[];
414
418
  /** Hashes a client secret for the clients file (`scrypt$...`). */
415
419
  export function hashSecret(secret: string): Promise<string>;
@@ -418,7 +422,12 @@ export function verifySecret(secret: string, stored: string | undefined): Promis
418
422
  export function generateSecret(): string;
419
423
  /** Gets tokens from an orchestrator and refreshes them before they expire. */
420
424
  export function createTokenProvider(opts: {
421
- url: string;
425
+ /** The orchestrator; its /v1/auth/token is used unless `tokenUrl` is given. */
426
+ url?: string;
427
+ /** Any OAuth2 token endpoint (client credentials grant). */
428
+ tokenUrl?: string;
429
+ /** Resource indicator (RFC 8707). */
430
+ resource?: string;
422
431
  clientId: string;
423
432
  clientSecret: string;
424
433
  scope?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fffleet",
3
- "version": "2.9.0",
3
+ "version": "2.10.0",
4
4
  "description": "Run ffmpeg jobs locally, on one worker or across a pool, through one client and one job contract",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/server.d.ts CHANGED
@@ -21,6 +21,8 @@ export interface Principal {
21
21
  sub: string;
22
22
  scopes: Set<Scope>;
23
23
  admin: boolean;
24
+ /** Sees and controls every owner's jobs: `admin`, and `dispatch` (the orchestrator calling a worker). */
25
+ all: boolean;
24
26
  }
25
27
 
26
28
  export type Authenticator = (req: IncomingMessage) => Promise<Principal | null>;
@@ -73,14 +75,36 @@ export interface TokenSigner {
73
75
  jwks(): { keys: Record<string, unknown>[] };
74
76
  }
75
77
  export function createTokenSigner(opts: { privateKey: KeyObject | string; issuer?: string; ttlSeconds?: number }): TokenSigner;
76
- export function createTokenVerifier(opts: { getKey: (kid: string) => KeyObject | null | Promise<KeyObject | null>; issuer?: string }): (token: string) => Promise<{ sub: string; scope: string[]; exp: number } | null>;
78
+ export function createTokenVerifier(opts: { getKey: (kid: string) => KeyObject | null | Promise<KeyObject | null>; issuer?: string; audience?: string | null; algorithms?: ('EdDSA' | 'RS256')[] }): (token: string) => Promise<{ sub: string; scope: string[]; exp: number } | null>;
77
79
  export function createRemoteKeySet(url: string, opts?: { fetch?: typeof fetch; minRefreshMs?: number }): (kid: string) => Promise<KeyObject | null>;
78
80
  export function createAuthenticator(opts: {
79
81
  token?: string | null;
80
82
  verify?: ((token: string) => Promise<{ sub: string; scope: string[] } | null>) | null;
81
83
  isActive?: (sub: string) => boolean;
84
+ /** Tokens from an external issuer; see `createExternalIssuer`. Revocation is the token's lifetime. */
85
+ external?: ExternalIssuer | null;
82
86
  open?: boolean;
83
87
  }): Authenticator;
88
+ /** External scope names mapped to {@link Scope}s unless mapped otherwise. */
89
+ export const DEFAULT_EXTERNAL_SCOPES: Readonly<Record<string, Scope>>;
90
+ /** Parses `external=internal` pairs ("fleet:submit=jobs,fleet:work=worker"), an object or a Map; `null` gives the defaults. */
91
+ export function parseScopeMap(spec?: string | Record<string, string> | Map<string, string> | null): Map<string, Scope>;
92
+ export interface ExternalIssuerOptions {
93
+ issuer: string;
94
+ jwksUrl: string;
95
+ /** Expected `aud`: this surface's resource identifier. */
96
+ audience: string;
97
+ scopes?: string | Record<string, string> | Map<string, string>;
98
+ algorithms?: ('EdDSA' | 'RS256')[];
99
+ fetch?: typeof fetch;
100
+ }
101
+ export interface ExternalIssuer {
102
+ issuer: string;
103
+ audience: string;
104
+ scopeMap: Map<string, Scope>;
105
+ verify: (token: string) => Promise<{ sub: string; scope: string[]; exp: number } | null>;
106
+ }
107
+ export function createExternalIssuer(opts: ExternalIssuerOptions): ExternalIssuer;
84
108
  export interface ClientEntry {
85
109
  id: string;
86
110
  secretHash: string;
package/src/auth.js CHANGED
@@ -7,8 +7,21 @@ import { FleetError } from './job-record.js';
7
7
 
8
8
  const scryptAsync = promisify(scrypt);
9
9
 
10
- /** `jobs`: submit and see your own jobs. `metrics`: /metrics and service discovery. `admin`: everything, all owners. */
11
- export const SCOPES = ['jobs', 'metrics', 'admin'];
10
+ /**
11
+ * `jobs`: submit and see your own jobs. `metrics`: /metrics and service discovery. `admin`: everything, all owners.
12
+ * `worker`: register a worker and send heartbeats, nothing else. `dispatch`: call a worker's job API for every
13
+ * owner (held by the orchestrator only).
14
+ */
15
+ export const SCOPES = ['jobs', 'metrics', 'admin', 'worker', 'dispatch'];
16
+
17
+ /** External (issuer) scope names mapped to the scopes above unless the operator maps them differently. */
18
+ export const DEFAULT_EXTERNAL_SCOPES = Object.freeze({
19
+ 'fleet:submit': 'jobs',
20
+ 'fleet:work': 'worker',
21
+ 'fleet:dispatch': 'dispatch',
22
+ 'fleet:admin': 'admin',
23
+ 'fleet:metrics': 'metrics',
24
+ });
12
25
  const SCRYPT = { N: 16384, r: 8, p: 1, keylen: 32 };
13
26
  const LEEWAY_S = 30;
14
27
 
@@ -92,9 +105,11 @@ export function createTokenSigner({ privateKey, issuer = 'fffleet', ttlSeconds =
92
105
 
93
106
  /**
94
107
  * Verifies tokens. `getKey(kid)` returns a public KeyObject or null.
108
+ * Only the algorithms in `algorithms` are accepted (default EdDSA, fffleet's own tokens; an external
109
+ * issuer's tokens are typically `['RS256']`). With `audience` the token's `aud` must contain it.
95
110
  * @returns {(token: string) => Promise<{ sub: string, scope: string[], exp: number } | null>}
96
111
  */
97
- export function createTokenVerifier({ getKey, issuer = 'fffleet' }) {
112
+ export function createTokenVerifier({ getKey, issuer = 'fffleet', audience = null, algorithms = ['EdDSA'] }) {
98
113
  return async token => {
99
114
  const parts = String(token).split('.');
100
115
  if (parts.length !== 3) return null;
@@ -105,19 +120,37 @@ export function createTokenVerifier({ getKey, issuer = 'fffleet' }) {
105
120
  } catch {
106
121
  return null;
107
122
  }
108
- if (header?.alg !== 'EdDSA' || typeof header.kid !== 'string') return null;
123
+ if (!algorithms.includes(header?.alg) || typeof header.kid !== 'string') return null;
109
124
  const key = await getKey(header.kid);
110
125
  if (!key) return null;
111
- if (!verify(null, Buffer.from(`${parts[0]}.${parts[1]}`), key, Buffer.from(parts[2], 'base64url'))) return null;
126
+ const data = Buffer.from(`${parts[0]}.${parts[1]}`);
127
+ const sig = Buffer.from(parts[2], 'base64url');
128
+ let ok = false;
129
+ try {
130
+ if (header.alg === 'EdDSA') ok = key.asymmetricKeyType === 'ed25519' && verify(null, data, key, sig);
131
+ else if (header.alg === 'RS256') ok = key.asymmetricKeyType === 'rsa' && verify('sha256', data, key, sig);
132
+ } catch {
133
+ ok = false;
134
+ }
135
+ if (!ok) return null;
112
136
  const now = Math.floor(Date.now() / 1000);
113
137
  if (claims.iss !== issuer || typeof claims.sub !== 'string' || typeof claims.exp !== 'number' || claims.exp + LEEWAY_S < now) return null;
114
- return { sub: claims.sub, scope: String(claims.scope ?? '').split(' ').filter(Boolean), exp: claims.exp };
138
+ if (typeof claims.nbf === 'number' && claims.nbf - LEEWAY_S > now) return null;
139
+ if (audience) {
140
+ const aud = [].concat(claims.aud ?? []);
141
+ if (!aud.includes(audience)) return null;
142
+ }
143
+ // `scope` is a space-separated string (RFC 8693) or, with some issuers, `scp`/`scope` as an array.
144
+ const raw = claims.scope ?? claims.scp ?? '';
145
+ const scope = (Array.isArray(raw) ? raw : String(raw).split(' ')).filter(Boolean);
146
+ return { sub: claims.sub, scope, exp: claims.exp };
115
147
  };
116
148
  }
117
149
 
118
150
  /**
119
- * Fetches public keys from a JWK Set URL (an orchestrator's /v1/auth/keys) and caches them.
120
- * An unknown key id triggers a refetch at most every `minRefreshMs`.
151
+ * Fetches public keys from a JWK Set URL (an orchestrator's /v1/auth/keys, or an external issuer's) and caches them.
152
+ * Ed25519 and RSA keys are read. An unknown key id triggers a refetch at most every `minRefreshMs`.
153
+ * A failed refetch keeps the keys already cached, so a short outage of the issuer does not stop verification.
121
154
  */
122
155
  export function createRemoteKeySet(url, { fetch: f = globalThis.fetch, minRefreshMs = 30000 } = {}) {
123
156
  let keys = new Map();
@@ -128,7 +161,16 @@ export function createRemoteKeySet(url, { fetch: f = globalThis.fetch, minRefres
128
161
  const res = await f(url, { signal: AbortSignal.timeout(5000) });
129
162
  if (!res.ok) throw new Error(`key set returned HTTP ${res.status}`);
130
163
  const body = await res.json();
131
- keys = new Map((body.keys ?? []).filter(k => k.kty === 'OKP' && k.crv === 'Ed25519').map(k => [k.kid, createPublicKey({ key: k, format: 'jwk' })]));
164
+ const next = new Map();
165
+ for (const k of body.keys ?? []) {
166
+ if (typeof k.kid !== 'string' || k.use === 'enc' || !((k.kty === 'OKP' && k.crv === 'Ed25519') || k.kty === 'RSA')) continue;
167
+ try {
168
+ next.set(k.kid, createPublicKey({ key: k, format: 'jwk' }));
169
+ } catch {
170
+ // A malformed key is skipped; the others still work.
171
+ }
172
+ }
173
+ keys = next;
132
174
  }
133
175
  return async kid => {
134
176
  if (!keys.has(kid) && Date.now() - fetchedAt >= minRefreshMs) {
@@ -141,14 +183,16 @@ export function createRemoteKeySet(url, { fetch: f = globalThis.fetch, minRefres
141
183
 
142
184
  /**
143
185
  * Who a request is from. `scopes` decide what it may do; `admin` sees and controls every owner's jobs.
144
- * @typedef {{ sub: string, scopes: Set<string>, admin: boolean }} Principal
186
+ * @typedef {{ sub: string, scopes: Set<string>, admin: boolean, all: boolean }} Principal
187
+ * `all`: sees and controls every owner's jobs (`admin`, and `dispatch`, which is the orchestrator calling a worker).
145
188
  */
146
189
 
147
190
  /** @returns {Principal} */
148
191
  export function principal(sub, scopes) {
149
192
  const set = new Set(scopes);
150
193
  if (set.has('admin')) for (const s of SCOPES) set.add(s);
151
- return { sub, scopes: set, admin: set.has('admin') };
194
+ if (set.has('dispatch')) set.add('jobs');
195
+ return { sub, scopes: set, admin: set.has('admin'), all: set.has('admin') || set.has('dispatch') };
152
196
  }
153
197
 
154
198
  /** The principal used when no authentication is configured: everything is allowed. */
@@ -165,6 +209,57 @@ export function sameSecret(a, b) {
165
209
  return x.length === y.length && timingSafeEqual(x, y);
166
210
  }
167
211
 
212
+ /**
213
+ * Parses `external=internal` pairs ("fleet:submit=jobs,fleet:work=worker") into a map.
214
+ * Accepts a string, an object or a Map; `null` gives the defaults. Unknown internal scopes are an error.
215
+ * @returns {Map<string, string>}
216
+ */
217
+ export function parseScopeMap(spec = null) {
218
+ let entries;
219
+ if (spec instanceof Map) entries = [...spec];
220
+ else if (spec && typeof spec === 'object') entries = Object.entries(spec);
221
+ else if (typeof spec === 'string' && spec.trim()) entries = spec.split(',').map(p => p.trim()).filter(Boolean).map(p => p.split('=').map(x => x.trim()));
222
+ else entries = Object.entries(DEFAULT_EXTERNAL_SCOPES);
223
+ const map = new Map();
224
+ for (const [from, to] of entries) {
225
+ if (!from || !SCOPES.includes(to)) throw new Error(`scope map: "${from}=${to}" must map to one of ${SCOPES.join(', ')}`);
226
+ map.set(from, to);
227
+ }
228
+ return map;
229
+ }
230
+
231
+ /**
232
+ * Settings for tokens from an external OIDC issuer (a service-token provider), RS256 or EdDSA.
233
+ * @typedef {object} ExternalIssuer
234
+ * @property {string} issuer Expected `iss`.
235
+ * @property {string} jwksUrl Where the public keys are.
236
+ * @property {string} audience Expected `aud` (this surface's resource identifier).
237
+ * @property {string | object | Map<string, string>} [scopes] External scope name to internal scope (see parseScopeMap).
238
+ * @property {typeof globalThis.fetch} [fetch]
239
+ */
240
+
241
+ /**
242
+ * Builds the `external` option of createAuthenticator from ExternalIssuer settings.
243
+ * @param {ExternalIssuer} opts
244
+ */
245
+ export function createExternalIssuer({ issuer, jwksUrl, audience, scopes = null, fetch: f = globalThis.fetch, algorithms = ['RS256', 'EdDSA'] }) {
246
+ if (!issuer || !jwksUrl || !audience) throw new Error('an external issuer needs issuer, jwksUrl and audience');
247
+ return {
248
+ issuer,
249
+ audience,
250
+ scopeMap: parseScopeMap(scopes),
251
+ verify: createTokenVerifier({ getKey: createRemoteKeySet(jwksUrl, { fetch: f }), issuer, audience, algorithms }),
252
+ };
253
+ }
254
+
255
+ function peekIssuer(jwt) {
256
+ try {
257
+ return JSON.parse(Buffer.from(jwt.split('.')[1], 'base64url').toString('utf8'))?.iss ?? null;
258
+ } catch {
259
+ return null;
260
+ }
261
+ }
262
+
168
263
  /**
169
264
  * Builds an authenticator: a function from a request to a Principal, or null when the request
170
265
  * carries no valid credentials.
@@ -172,15 +267,24 @@ export function sameSecret(a, b) {
172
267
  * @param {string | null} [opts.token] A static token that is granted `admin`.
173
268
  * @param {((token: string) => Promise<{ sub: string, scope: string[] } | null>) | null} [opts.verify]
174
269
  * @param {(sub: string) => boolean} [opts.isActive] Rejects tokens of clients that were removed.
270
+ * @param {ReturnType<typeof createExternalIssuer> | null} [opts.external] Tokens from an external issuer. Revocation is the token's lifetime (no `isActive` check).
175
271
  * @param {boolean} [opts.open] Without any credentials configured, allow everything.
176
272
  */
177
- export function createAuthenticator({ token = null, verify: verifyToken = null, isActive = () => true, open = !token && !verifyToken }) {
273
+ export function createAuthenticator({ token = null, verify: verifyToken = null, isActive = () => true, external = null, open = !token && !verifyToken && !external }) {
178
274
  return async req => {
179
275
  if (open) return OPEN;
180
276
  const given = bearerOf(req);
181
277
  if (!given) return null;
182
278
  if (token && sameSecret(given, token)) return principal('admin', ['admin']);
183
- if (!verifyToken || given.split('.').length !== 3) return null;
279
+ if (given.split('.').length !== 3) return null;
280
+ // The issuer is read from the unverified payload only to choose which verifier runs; nothing is trusted before its signature is checked.
281
+ if (external && peekIssuer(given) === external.issuer) {
282
+ const claims = await external.verify(given);
283
+ if (!claims) return null;
284
+ const scopes = claims.scope.map(s => external.scopeMap.get(s)).filter(Boolean);
285
+ return principal(claims.sub, scopes);
286
+ }
287
+ if (!verifyToken) return null;
184
288
  const claims = await verifyToken(given);
185
289
  if (!claims || !isActive(claims.sub)) return null;
186
290
  return principal(claims.sub, claims.scope.filter(s => SCOPES.includes(s)));
@@ -270,16 +374,17 @@ function oauthError(status, error, description, basic = false) {
270
374
  }
271
375
 
272
376
  /**
273
- * Client side: gets tokens from an orchestrator and refreshes them before they expire.
377
+ * Client side: gets tokens from an orchestrator (`url`, its /v1/auth/token) or from any OAuth2 token endpoint (`tokenUrl`,
378
+ * optionally with a `resource` indicator, RFC 8707) and refreshes them before they expire.
274
379
  * @returns {{ get: (opts?: { refresh?: boolean }) => Promise<string> }}
275
380
  */
276
- export function createTokenProvider({ url, clientId, clientSecret, scope, fetch: f = globalThis.fetch, timeoutMs = 10000 }) {
381
+ export function createTokenProvider({ url, tokenUrl, resource, clientId, clientSecret, scope, fetch: f = globalThis.fetch, timeoutMs = 10000 }) {
277
382
  let token = null;
278
383
  let expiresAt = 0;
279
384
  let pending = null;
280
385
  async function fetchToken() {
281
- const body = new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret, ...(scope ? { scope } : {}) });
282
- const res = await f(`${url.replace(/\/+$/, '')}/v1/auth/token`, {
386
+ const body = new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret, ...(scope ? { scope } : {}), ...(resource ? { resource } : {}) });
387
+ const res = await f(tokenUrl ?? `${url.replace(/\/+$/, '')}/v1/auth/token`, {
283
388
  method: 'POST',
284
389
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
285
390
  body,
package/src/client.js CHANGED
@@ -85,15 +85,17 @@ export class JobHandle extends EventEmitter {
85
85
  * @param {string} [opts.token] A static bearer token.
86
86
  * @param {string} [opts.clientId] With clientSecret: log in at the orchestrator (POST /v1/auth/token) instead of using a static token.
87
87
  * @param {string} [opts.clientSecret]
88
+ * @param {string} [opts.tokenUrl] With clientId/clientSecret: an OAuth2 token endpoint of an external issuer instead of the orchestrator's.
89
+ * @param {string} [opts.tokenResource] Resource indicator (RFC 8707) sent with the token request.
88
90
  * @param {string} [opts.scope] Narrow the token to some of the client's scopes, e.g. 'jobs'.
89
91
  * @param {'local' | 'none'} [opts.fallback]
90
92
  * @param {ConstructorParameters<typeof JobManager>[0]} [opts.local] Options for the local runner.
91
93
  * @param {typeof fetch} [opts.fetch]
92
94
  * @param {number} [opts.requestTimeoutMs]
93
95
  */
94
- export function createFleet({ url, token, clientId, clientSecret, scope, fallback = 'local', local = {}, fetch: f = globalThis.fetch, requestTimeoutMs = 10000 } = {}) {
96
+ export function createFleet({ url, token, clientId, clientSecret, tokenUrl, tokenResource, scope, fallback = 'local', local = {}, fetch: f = globalThis.fetch, requestTimeoutMs = 10000 } = {}) {
95
97
  const base = url ? url.replace(/\/+$/, '') : null;
96
- const login = base && clientId && clientSecret ? createTokenProvider({ url: base, clientId, clientSecret, scope, fetch: f, timeoutMs: requestTimeoutMs }) : null;
98
+ const login = (base || tokenUrl) && clientId && clientSecret ? createTokenProvider({ url: base, tokenUrl, resource: tokenResource, clientId, clientSecret, scope, fetch: f, timeoutMs: requestTimeoutMs }) : null;
97
99
  const authHeaders = async (refresh = false) => {
98
100
  if (login) return { authorization: `Bearer ${await login.get({ refresh })}` };
99
101
  return token ? { authorization: `Bearer ${token}` } : {};
package/src/http-api.js CHANGED
@@ -56,13 +56,13 @@ export function createApiHandler({ backend, token = null, authenticate = createA
56
56
  return res.end(text);
57
57
  }
58
58
  if (!allowed(res, who, 'jobs')) return;
59
- const mine = job => job && (who.admin || job.owner === who.sub) ? job : null;
59
+ const mine = job => job && (who.all || job.owner === who.sub) ? job : null;
60
60
 
61
61
  if (url.pathname === '/v1/capabilities' && req.method === 'GET') return send(res, 200, await backend.capabilities());
62
62
  if (url.pathname === '/v1/jobs') {
63
63
  if (req.method === 'POST') {
64
64
  const input = await readJson(req);
65
- if (!who.admin && input && typeof input === 'object' && !Array.isArray(input)) input.owner = who.sub;
65
+ if (!who.all && input && typeof input === 'object' && !Array.isArray(input)) input.owner = who.sub;
66
66
  const { created, queued, job } = await backend.submit(input);
67
67
  // 201: took a slot (or was handed to a worker) now; 202: waiting in the queue; 200: already known.
68
68
  return send(res, created ? ((queued ?? job.state === 'queued') ? 202 : 201) : 200, job);
package/src/server.js CHANGED
@@ -4,5 +4,5 @@ export { getStream } from './http-stream.js';
4
4
  export { Registry, jobMetrics, processMetrics, hostMetrics, procStats, METRICS_CONTENT_TYPE } from './metrics.js';
5
5
  export {
6
6
  SCOPES, hashSecret, verifySecret, generateSecret, loadSigningKey, createTokenSigner, createTokenVerifier,
7
- createRemoteKeySet, createAuthenticator, createClientStore, issueToken, principal, bearerOf, OPEN,
7
+ createRemoteKeySet, createAuthenticator, createExternalIssuer, parseScopeMap, DEFAULT_EXTERNAL_SCOPES, createClientStore, issueToken, principal, bearerOf, OPEN,
8
8
  } from './auth.js';