fffleet 0.1.0 → 1.0.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 CHANGED
@@ -7,7 +7,7 @@ import { createFleet } from 'fffleet';
7
7
 
8
8
  const fleet = createFleet({
9
9
  url: process.env.FFFLEET_URL, // omit to always run locally
10
- token: process.env.FFFLEET_TOKEN,
10
+ token: process.env.FFFLEET_TOKEN, // or log in as an app: clientId + clientSecret (refreshed automatically)
11
11
  fallback: 'local', // run here if the fleet is unreachable (default); 'none' to throw
12
12
  local: { slots: { default: 2 } }, // options for the local runner
13
13
  });
package/index.d.ts CHANGED
@@ -9,14 +9,18 @@ export const STATES: readonly JobState[];
9
9
  export const FILE_SCHEMES: readonly string[];
10
10
  export const HTTP_SCHEMES: readonly string[];
11
11
  export const PASSTHROUGH_SCHEMES: readonly string[];
12
+ export const OBJECT_SCHEMES: readonly string[];
12
13
 
13
14
  export type JobKind = 'stream' | 'batch';
14
15
  export type JobState = 'queued' | 'assigned' | 'staging' | 'running' | 'uploading' | 'succeeded' | 'failed' | 'cancelled';
15
16
 
16
17
  export interface Endpoint {
17
- /** Name used in placeholders: {{input:name}} / {{output:name}}. */
18
+ /** Name used in placeholders: {{input:name}}, {{inputdir:name}} (the directory holding that staged input) and {{output:name}}. */
18
19
  name: string;
19
- /** file:, http(s): (staged for batch jobs) or a live scheme such as rtmp:, srt:, udp:. */
20
+ /**
21
+ * file:, http(s): (staged for batch jobs), s3://bucket/key (batch jobs; a key ending in "/" is an
22
+ * output folder) or a live scheme such as rtmp:, srt:, udp:.
23
+ */
20
24
  uri: string;
21
25
  /** Content-Type sent when an http(s) output is uploaded. */
22
26
  contentType?: string;
@@ -128,6 +132,8 @@ export function validateSpec(input: unknown): { ok: true; spec: JobSpec } | { ok
128
132
  export function parseSpec(input: unknown): JobSpec;
129
133
  export function resolvePlaceholders(args: string[], values: { input: Record<string, string>; output: Record<string, string> }): string[];
130
134
  export function canonicalJson(value: unknown): string;
135
+ /** Capabilities a job needs beyond `requires`: `type:<type>`, plus `scheme:s3` for s3: URIs. */
136
+ export function implicitRequirements(spec: Pick<JobSpec, 'type' | 'inputs' | 'outputs'>): string[];
131
137
 
132
138
  export interface ExecutorRuntime {
133
139
  workDir: string;
@@ -137,6 +143,7 @@ export interface ExecutorRuntime {
137
143
  attachStdin(stdin: Writable | null): void;
138
144
  ffmpegPath?: string;
139
145
  fetch?: typeof fetch;
146
+ s3?: S3Client | null;
140
147
  }
141
148
 
142
149
  export interface ExecutorResult {
@@ -148,8 +155,10 @@ export interface ExecutorResult {
148
155
  export type Executor = (spec: JobSpec & { id: string }, runtime: ExecutorRuntime) => Promise<ExecutorResult>;
149
156
 
150
157
  export interface JobManagerOptions {
151
- /** Slots per class pool, e.g. { default: 2, stream: 1 } or 'default=2,stream=1'. */
158
+ /** Slots per class pool, e.g. { default: 2, stream: 1 }, 'default=2,stream=1', or 'auto' / 'auto:N' (sized from the CPU count; N cores per slot). */
152
159
  slots?: Record<string, number> | string;
160
+ /** Job kinds this runner accepts ('batch', 'stream'; a comma list or an array). Default: both. A job of another kind is refused with 422 UNSUPPORTED_KIND. */
161
+ kinds?: JobKind[] | string;
153
162
  workRoot?: string;
154
163
  ffmpegPath?: string;
155
164
  maxQueued?: number;
@@ -158,6 +167,10 @@ export interface JobManagerOptions {
158
167
  executors?: Record<string, Executor>;
159
168
  workerId?: string | null;
160
169
  fetch?: typeof fetch;
170
+ /** S3 settings or a client; enables s3: URIs. */
171
+ s3?: S3Config | S3Client | null;
172
+ /** Keeps staged s3: and http(s): inputs between jobs, hard-linked and checked against the ETag. Least recently used are removed above maxBytes (default 20 GB). */
173
+ cache?: { dir: string; maxBytes?: number | string } | null;
161
174
  }
162
175
 
163
176
  export interface PoolStats {
@@ -168,6 +181,8 @@ export interface PoolStats {
168
181
  export class JobManager {
169
182
  constructor(opts?: JobManagerOptions);
170
183
  readonly slots: Record<string, number>;
184
+ readonly kinds: JobKind[];
185
+ readonly cache: InputCache | null;
171
186
  submit(spec: JobSpecInput): { created: boolean; queued?: boolean; job: JobSnapshot };
172
187
  get(id: string): JobSnapshot | null;
173
188
  list(): JobSnapshot[];
@@ -179,7 +194,18 @@ export class JobManager {
179
194
  close(): Promise<void>;
180
195
  }
181
196
 
182
- export function normalizeSlots(slots: Record<string, number | string> | string): Record<string, number>;
197
+ export function normalizeSlots(slots: Record<string, number | string> | string, opts?: { kinds?: JobKind[]; cpus?: number }): Record<string, number>;
198
+ /** Parses 'batch,stream' or an array; no value means both kinds. */
199
+ export interface InputCache {
200
+ readonly stats: { hits: number; misses: number };
201
+ stage(opts: { key: string; validator: string; target: string; download: (path: string) => Promise<void> }): Promise<'hit' | 'miss'>;
202
+ }
203
+ export function createInputCache(opts: { dir: string; maxBytes?: number }): InputCache;
204
+ /** "500", "20MB", "50GB" (decimal units) as bytes. */
205
+ export function parseSize(value: number | string): number;
206
+ export function normalizeKinds(kinds?: JobKind[] | string): JobKind[];
207
+ /** Slot pools sized from the CPU count: batch only cores/2, stream only cores, both: default cores/2 plus stream cores/4. */
208
+ export function autoSlots(opts?: { cpus?: number; kinds?: JobKind[]; coresPerSlot?: number }): Record<string, number>;
183
209
  export function runFfmpegJob(spec: JobSpec & { id: string }, runtime: ExecutorRuntime): Promise<Required<ExecutorResult>>;
184
210
 
185
211
  export class JobHandle extends EventEmitter {
@@ -200,7 +226,13 @@ export class JobHandle extends EventEmitter {
200
226
  export interface FleetOptions {
201
227
  /** A worker or an orchestrator. Without it every job runs on this machine. */
202
228
  url?: string;
229
+ /** A static bearer token. */
203
230
  token?: string;
231
+ /** With `clientSecret`: log in at the orchestrator (POST /v1/auth/token) and refresh the token before it expires. */
232
+ clientId?: string;
233
+ clientSecret?: string;
234
+ /** Narrow the token to some of the app's scopes, e.g. 'jobs'. */
235
+ scope?: string;
204
236
  /** 'local' (default) runs a job here when the remote cannot be reached or answers 502/503. */
205
237
  fallback?: 'local' | 'none';
206
238
  /** Options for the local runner. */
@@ -253,3 +285,55 @@ export class JobRecord {
253
285
 
254
286
  export function byPriority(a: JobRecord, b: JobRecord): number;
255
287
  export function pruneFinished(jobs: Map<string, JobRecord>, keep: number): void;
288
+
289
+ export type Scope = 'jobs' | 'metrics' | 'admin';
290
+ export const SCOPES: readonly Scope[];
291
+ /** Hashes a client secret for the clients file (`scrypt$...`). */
292
+ export function hashSecret(secret: string): Promise<string>;
293
+ export function verifySecret(secret: string, stored: string | undefined): Promise<boolean>;
294
+ /** A random client secret. */
295
+ export function generateSecret(): string;
296
+ /** Gets tokens from an orchestrator and refreshes them before they expire. */
297
+ export function createTokenProvider(opts: {
298
+ url: string;
299
+ clientId: string;
300
+ clientSecret: string;
301
+ scope?: string;
302
+ fetch?: typeof fetch;
303
+ timeoutMs?: number;
304
+ }): { get(opts?: { refresh?: boolean }): Promise<string> };
305
+
306
+ export interface S3Config {
307
+ accessKeyId: string;
308
+ secretAccessKey: string;
309
+ sessionToken?: string;
310
+ /** Defaults to us-east-1. */
311
+ region?: string;
312
+ /** For S3-compatible stores, e.g. http://minio:9000. Defaults to AWS for the region. */
313
+ endpoint?: string;
314
+ /** Bucket in the path rather than the host name; defaults to true when `endpoint` is set. */
315
+ pathStyle?: boolean;
316
+ fetch?: typeof fetch;
317
+ /** Multipart part size in bytes (16 MiB by default; S3 needs at least 5 MiB). */
318
+ partSize?: number;
319
+ }
320
+
321
+ export interface S3Client {
322
+ getFile(bucket: string, key: string, path: string, opts?: { signal?: AbortSignal }): Promise<void>;
323
+ head(bucket: string, key: string, opts?: { signal?: AbortSignal }): Promise<{ size: number; etag: string | null }>;
324
+ putFile(bucket: string, key: string, path: string, opts?: { contentType?: string; signal?: AbortSignal; forceMultipart?: boolean }): Promise<number>;
325
+ putDirectory(bucket: string, prefix: string, dir: string, opts?: { signal?: AbortSignal }): Promise<number>;
326
+ deleteObject(bucket: string, key: string, opts?: { signal?: AbortSignal }): Promise<void>;
327
+ createBucket(bucket: string, opts?: { signal?: AbortSignal }): Promise<void>;
328
+ }
329
+
330
+ export function createS3Client(config: S3Config): S3Client;
331
+ /** Reads AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, AWS_REGION, FFFLEET_S3_ENDPOINT, FFFLEET_S3_PATH_STYLE. */
332
+ export function s3ConfigFromEnv(env?: Record<string, string | undefined>): S3Config | null;
333
+ export function parseS3Uri(uri: string): { bucket: string; key: string };
334
+ export function contentTypeFor(name: string): string;
335
+ export function signV4(
336
+ req: { method: string; url: URL; headers: Record<string, string>; payloadHash: string },
337
+ creds: { accessKeyId: string; secretAccessKey: string; region: string },
338
+ service?: string,
339
+ ): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fffleet",
3
- "version": "0.1.0",
3
+ "version": "1.0.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
@@ -1,7 +1,8 @@
1
1
  // Type declarations for fffleet/server: the HTTP job API used by fffleet-worker and fffleet-orchestrator.
2
2
 
3
+ import type { KeyObject } from 'node:crypto';
3
4
  import type { IncomingMessage, Server, ServerResponse } from 'node:http';
4
- import type { JobEvent, JobSnapshot, JobSpecInput } from './index.js';
5
+ import type { JobEvent, JobSnapshot, JobSpecInput, Scope } from './index.js';
5
6
 
6
7
  export interface JobBackend {
7
8
  submit(spec: JobSpecInput): { created: boolean; queued?: boolean; job: JobSnapshot } | Promise<{ created: boolean; queued?: boolean; job: JobSnapshot }>;
@@ -15,11 +16,26 @@ export interface JobBackend {
15
16
 
16
17
  export type RequestHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;
17
18
 
19
+ /** Who a request is from. Without `admin` a principal only sees and controls its own jobs. */
20
+ export interface Principal {
21
+ sub: string;
22
+ scopes: Set<Scope>;
23
+ admin: boolean;
24
+ }
25
+
26
+ export type Authenticator = (req: IncomingMessage) => Promise<Principal | null>;
27
+
18
28
  export function createApiHandler(opts: {
19
29
  backend: JobBackend;
30
+ /** A static admin token; ignored when `authenticate` is given. */
20
31
  token?: string | null;
21
- extraRoutes?: (req: IncomingMessage, res: ServerResponse, url: URL) => boolean | Promise<boolean>;
32
+ authenticate?: Authenticator;
33
+ /** Renders the Prometheus text for GET /metrics (needs the `metrics` scope). */
34
+ metrics?: (() => Promise<string>) | null;
35
+ extraRoutes?: (req: IncomingMessage, res: ServerResponse, url: URL, principal: Principal | null) => boolean | Promise<boolean>;
22
36
  }): RequestHandler;
37
+ /** Sends 401 or 403 and returns false when `who` lacks `scope`. */
38
+ export function allowed(res: ServerResponse, who: Principal | null, scope: Scope): who is Principal;
23
39
  export function listen(handler: RequestHandler, opts?: { port?: number; host?: string }): Promise<{ server: Server; port: number; url: string }>;
24
40
  export function close(server: Server): Promise<void>;
25
41
  export function checkBearer(req: IncomingMessage, token: string | null): boolean;
@@ -27,3 +43,50 @@ export function send(res: ServerResponse, status: number, body: unknown, headers
27
43
  export function sendError(res: ServerResponse, err: unknown): void;
28
44
  export function readBody(req: IncomingMessage, limit: number): Promise<Buffer>;
29
45
  export function readJson(req: IncomingMessage): Promise<unknown>;
46
+
47
+ export const METRICS_CONTENT_TYPE: string;
48
+ export class Registry {
49
+ counter(name: string, help: string, labelNames?: string[]): { inc(labels?: Record<string, string>, n?: number): void };
50
+ gauge(name: string, help: string, labelNames?: string[]): { set(labels: Record<string, string>, v: number): void; inc(labels?: Record<string, string>, n?: number): void; reset(): void };
51
+ histogram(name: string, help: string, labelNames?: string[], buckets?: number[]): { observe(labels: Record<string, string>, v: number): void };
52
+ /** Runs before every render, to refresh gauges. */
53
+ collect(fn: () => void | Promise<void>): void;
54
+ render(): Promise<string>;
55
+ }
56
+ export function jobMetrics(registry: Registry, records: () => Iterable<unknown>): { track(record: unknown): void };
57
+ export function processMetrics(registry: Registry): void;
58
+ export function hostMetrics(registry: Registry, dir?: string): void;
59
+ export function procStats(pid: number): Promise<{ cpuSeconds: number; rssBytes: number } | null>;
60
+
61
+ export const SCOPES: readonly Scope[];
62
+ export function hashSecret(secret: string): Promise<string>;
63
+ export function verifySecret(secret: string, stored: string | undefined): Promise<boolean>;
64
+ export function generateSecret(): string;
65
+ export function loadSigningKey(path?: string | null): KeyObject;
66
+ export interface TokenSigner {
67
+ kid: string;
68
+ issuer: string;
69
+ ttlSeconds: number;
70
+ publicKey: KeyObject;
71
+ sign(claims: { sub: string; scope: string[] }): string;
72
+ jwks(): { keys: Record<string, unknown>[] };
73
+ }
74
+ export function createTokenSigner(opts: { privateKey: KeyObject | string; issuer?: string; ttlSeconds?: number }): TokenSigner;
75
+ export function createTokenVerifier(opts: { getKey: (kid: string) => KeyObject | null | Promise<KeyObject | null>; issuer?: string }): (token: string) => Promise<{ sub: string; scope: string[]; exp: number } | null>;
76
+ export function createRemoteKeySet(url: string, opts?: { fetch?: typeof fetch; minRefreshMs?: number }): (kid: string) => Promise<KeyObject | null>;
77
+ export function createAuthenticator(opts: {
78
+ token?: string | null;
79
+ verify?: ((token: string) => Promise<{ sub: string; scope: string[] } | null>) | null;
80
+ isActive?: (sub: string) => boolean;
81
+ open?: boolean;
82
+ }): Authenticator;
83
+ export interface ClientEntry {
84
+ id: string;
85
+ secretHash: string;
86
+ scopes?: Scope[];
87
+ }
88
+ export function createClientStore(source: string | ClientEntry[] | null): { get(id: string): ClientEntry | null; has(id: string): boolean; readonly size: number } | null;
89
+ export function issueToken(opts: { req: IncomingMessage; body: unknown; clients: ReturnType<typeof createClientStore>; signer: TokenSigner }): Promise<{ status: number; body: Record<string, unknown>; headers?: Record<string, string> }>;
90
+ export function principal(sub: string, scopes: Iterable<Scope>): Principal;
91
+ export function bearerOf(req: IncomingMessage): string | null;
92
+ export const OPEN: Principal;
package/src/auth.js ADDED
@@ -0,0 +1,304 @@
1
+ // App login: OAuth2 client credentials, short-lived Ed25519-signed JWTs, scopes. No dependencies.
2
+
3
+ import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, randomUUID, scrypt, sign, timingSafeEqual, verify } from 'node:crypto';
4
+ import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';
5
+ import { promisify } from 'node:util';
6
+ import { FleetError } from './job-record.js';
7
+
8
+ const scryptAsync = promisify(scrypt);
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'];
12
+ const SCRYPT = { N: 16384, r: 8, p: 1, keylen: 32 };
13
+ const LEEWAY_S = 30;
14
+
15
+ const b64url = buf => Buffer.from(buf).toString('base64url');
16
+
17
+ /** Hashes a client secret for the clients file: `scrypt$N$r$p$salt$hash`. */
18
+ export async function hashSecret(secret) {
19
+ const salt = randomBytes(16);
20
+ const hash = await scryptAsync(secret, salt, SCRYPT.keylen, { N: SCRYPT.N, r: SCRYPT.r, p: SCRYPT.p });
21
+ return ['scrypt', SCRYPT.N, SCRYPT.r, SCRYPT.p, b64url(salt), b64url(hash)].join('$');
22
+ }
23
+
24
+ // Compared against when the client id is unknown, so a wrong id costs as long as a wrong secret.
25
+ const DUMMY_HASH = `scrypt$${SCRYPT.N}$${SCRYPT.r}$${SCRYPT.p}$${b64url(Buffer.alloc(16))}$${b64url(Buffer.alloc(32))}`;
26
+
27
+ /** Checks a secret against a `hashSecret` value in constant time. */
28
+ export async function verifySecret(secret, stored) {
29
+ const parts = String(stored ?? DUMMY_HASH).split('$');
30
+ if (parts.length !== 6 || parts[0] !== 'scrypt') return false;
31
+ const [, N, r, p, salt, hash] = parts;
32
+ const want = Buffer.from(hash, 'base64url');
33
+ let got;
34
+ try {
35
+ got = await scryptAsync(String(secret), Buffer.from(salt, 'base64url'), want.length, { N: Number(N), r: Number(r), p: Number(p), maxmem: 256 * Number(N) * Number(r) });
36
+ } catch {
37
+ return false;
38
+ }
39
+ return got.length === want.length && timingSafeEqual(got, want);
40
+ }
41
+
42
+ /** A random client secret (256 bits, base64url). */
43
+ export function generateSecret() {
44
+ return b64url(randomBytes(32));
45
+ }
46
+
47
+ /**
48
+ * Loads the Ed25519 signing key from `path`, creating it (mode 0600) when the file does not exist.
49
+ * Without a path the key is generated in memory: tokens then stop working when the process restarts.
50
+ */
51
+ export function loadSigningKey(path) {
52
+ if (path && existsSync(path)) return createPrivateKey(readFileSync(path));
53
+ const { privateKey } = generateKeyPairSync('ed25519');
54
+ if (path) writeFileSync(path, privateKey.export({ type: 'pkcs8', format: 'pem' }), { mode: 0o600 });
55
+ return privateKey;
56
+ }
57
+
58
+ function keyId(publicKey) {
59
+ return createHash('sha256').update(publicKey.export({ format: 'jwk' }).x).digest('base64url').slice(0, 16);
60
+ }
61
+
62
+ /**
63
+ * Issues tokens.
64
+ * @param {object} opts
65
+ * @param {import('node:crypto').KeyObject | string} opts.privateKey Ed25519 private key (KeyObject or PEM).
66
+ * @param {string} [opts.issuer]
67
+ * @param {number} [opts.ttlSeconds]
68
+ */
69
+ export function createTokenSigner({ privateKey, issuer = 'fffleet', ttlSeconds = 3600 }) {
70
+ const key = typeof privateKey === 'string' ? createPrivateKey(privateKey) : privateKey;
71
+ const publicKey = createPublicKey(key);
72
+ const kid = keyId(publicKey);
73
+ const header = b64url(JSON.stringify({ alg: 'EdDSA', typ: 'JWT', kid }));
74
+ return {
75
+ kid,
76
+ issuer,
77
+ ttlSeconds,
78
+ /** @param {{ sub: string, scope: string[] }} claims */
79
+ sign({ sub, scope }) {
80
+ const iat = Math.floor(Date.now() / 1000);
81
+ const payload = b64url(JSON.stringify({ iss: issuer, sub, scope: scope.join(' '), iat, exp: iat + ttlSeconds, jti: randomUUID() }));
82
+ const signature = sign(null, Buffer.from(`${header}.${payload}`), key);
83
+ return `${header}.${payload}.${b64url(signature)}`;
84
+ },
85
+ /** The public key as a JWK Set, for GET /v1/auth/keys. */
86
+ jwks() {
87
+ return { keys: [{ ...publicKey.export({ format: 'jwk' }), kid, alg: 'EdDSA', use: 'sig' }] };
88
+ },
89
+ publicKey,
90
+ };
91
+ }
92
+
93
+ /**
94
+ * Verifies tokens. `getKey(kid)` returns a public KeyObject or null.
95
+ * @returns {(token: string) => Promise<{ sub: string, scope: string[], exp: number } | null>}
96
+ */
97
+ export function createTokenVerifier({ getKey, issuer = 'fffleet' }) {
98
+ return async token => {
99
+ const parts = String(token).split('.');
100
+ if (parts.length !== 3) return null;
101
+ let header, claims;
102
+ try {
103
+ header = JSON.parse(Buffer.from(parts[0], 'base64url').toString('utf8'));
104
+ claims = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
105
+ } catch {
106
+ return null;
107
+ }
108
+ if (header?.alg !== 'EdDSA' || typeof header.kid !== 'string') return null;
109
+ const key = await getKey(header.kid);
110
+ if (!key) return null;
111
+ if (!verify(null, Buffer.from(`${parts[0]}.${parts[1]}`), key, Buffer.from(parts[2], 'base64url'))) return null;
112
+ const now = Math.floor(Date.now() / 1000);
113
+ 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 };
115
+ };
116
+ }
117
+
118
+ /**
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`.
121
+ */
122
+ export function createRemoteKeySet(url, { fetch: f = globalThis.fetch, minRefreshMs = 30000 } = {}) {
123
+ let keys = new Map();
124
+ let fetchedAt = 0;
125
+ let pending = null;
126
+ async function refresh() {
127
+ fetchedAt = Date.now();
128
+ const res = await f(url, { signal: AbortSignal.timeout(5000) });
129
+ if (!res.ok) throw new Error(`key set returned HTTP ${res.status}`);
130
+ 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' })]));
132
+ }
133
+ return async kid => {
134
+ if (!keys.has(kid) && Date.now() - fetchedAt >= minRefreshMs) {
135
+ pending ??= refresh().catch(() => {}).finally(() => (pending = null));
136
+ await pending;
137
+ }
138
+ return keys.get(kid) ?? null;
139
+ };
140
+ }
141
+
142
+ /**
143
+ * 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
145
+ */
146
+
147
+ /** @returns {Principal} */
148
+ export function principal(sub, scopes) {
149
+ const set = new Set(scopes);
150
+ if (set.has('admin')) for (const s of SCOPES) set.add(s);
151
+ return { sub, scopes: set, admin: set.has('admin') };
152
+ }
153
+
154
+ /** The principal used when no authentication is configured: everything is allowed. */
155
+ export const OPEN = principal('anonymous', ['admin']);
156
+
157
+ export function bearerOf(req) {
158
+ const header = req.headers.authorization ?? '';
159
+ return header.startsWith('Bearer ') ? header.slice(7).trim() : null;
160
+ }
161
+
162
+ export function sameSecret(a, b) {
163
+ const x = Buffer.from(String(a));
164
+ const y = Buffer.from(String(b));
165
+ return x.length === y.length && timingSafeEqual(x, y);
166
+ }
167
+
168
+ /**
169
+ * Builds an authenticator: a function from a request to a Principal, or null when the request
170
+ * carries no valid credentials.
171
+ * @param {object} opts
172
+ * @param {string | null} [opts.token] A static token that is granted `admin`.
173
+ * @param {((token: string) => Promise<{ sub: string, scope: string[] } | null>) | null} [opts.verify]
174
+ * @param {(sub: string) => boolean} [opts.isActive] Rejects tokens of clients that were removed.
175
+ * @param {boolean} [opts.open] Without any credentials configured, allow everything.
176
+ */
177
+ export function createAuthenticator({ token = null, verify: verifyToken = null, isActive = () => true, open = !token && !verifyToken }) {
178
+ return async req => {
179
+ if (open) return OPEN;
180
+ const given = bearerOf(req);
181
+ if (!given) return null;
182
+ if (token && sameSecret(given, token)) return principal('admin', ['admin']);
183
+ if (!verifyToken || given.split('.').length !== 3) return null;
184
+ const claims = await verifyToken(given);
185
+ if (!claims || !isActive(claims.sub)) return null;
186
+ return principal(claims.sub, claims.scope.filter(s => SCOPES.includes(s)));
187
+ };
188
+ }
189
+
190
+ /**
191
+ * Reads the clients file, reloading it when it changes on disk.
192
+ * Format: { "clients": [{ "id": "app", "secretHash": "scrypt$...", "scopes": ["jobs"] }] }
193
+ */
194
+ export function createClientStore(source) {
195
+ if (!source) return null;
196
+ if (typeof source !== 'string') return staticStore(source);
197
+ let mtime = -1;
198
+ let checkedAt = 0;
199
+ let store = staticStore([]);
200
+ const reload = () => {
201
+ if (Date.now() - checkedAt < 1000) return store;
202
+ checkedAt = Date.now();
203
+ const m = statSync(source).mtimeMs;
204
+ if (m !== mtime) {
205
+ store = staticStore(JSON.parse(readFileSync(source, 'utf8')).clients ?? []);
206
+ mtime = m;
207
+ }
208
+ return store;
209
+ };
210
+ reload();
211
+ return { get: id => reload().get(id), has: id => reload().has(id), get size() { return reload().size; } };
212
+ }
213
+
214
+ function staticStore(list) {
215
+ const map = new Map();
216
+ for (const c of list) {
217
+ if (!c || typeof c.id !== 'string' || !c.id || typeof c.secretHash !== 'string') throw new Error('each client needs id and secretHash');
218
+ const scopes = Array.isArray(c.scopes) && c.scopes.length ? c.scopes : ['jobs'];
219
+ for (const s of scopes) if (!SCOPES.includes(s)) throw new Error(`client ${c.id}: unknown scope "${s}"`);
220
+ map.set(c.id, { id: c.id, secretHash: c.secretHash, scopes });
221
+ }
222
+ return { get: id => map.get(id) ?? null, has: id => map.has(id), get size() { return map.size; } };
223
+ }
224
+
225
+ /**
226
+ * The OAuth2 token endpoint (client credentials grant, RFC 6749 4.4).
227
+ * Reads client_id/client_secret from HTTP Basic or the form body; `scope` may narrow the grant.
228
+ * @returns {Promise<{ status: number, body: object, headers?: Record<string, string> }>}
229
+ */
230
+ export async function issueToken({ req, body, clients, signer }) {
231
+ const params = body instanceof URLSearchParams ? Object.fromEntries(body) : (body ?? {});
232
+ let id = params.client_id;
233
+ let secret = params.client_secret;
234
+ let basic = false;
235
+ const header = req.headers.authorization ?? '';
236
+ if (header.startsWith('Basic ')) {
237
+ basic = true;
238
+ const raw = Buffer.from(header.slice(6), 'base64').toString('utf8');
239
+ const colon = raw.indexOf(':');
240
+ try {
241
+ id = decodeURIComponent(raw.slice(0, colon).replace(/\+/g, ' '));
242
+ secret = decodeURIComponent(raw.slice(colon + 1).replace(/\+/g, ' '));
243
+ } catch {
244
+ return oauthError(400, 'invalid_request', 'malformed Basic credentials');
245
+ }
246
+ }
247
+ if (params.grant_type !== 'client_credentials') return oauthError(400, 'unsupported_grant_type', 'only client_credentials is supported');
248
+ if (!id || !secret) return oauthError(401, 'invalid_client', 'client_id and client_secret are required', basic);
249
+ const client = clients?.get(id) ?? null;
250
+ const ok = await verifySecret(secret, client?.secretHash);
251
+ if (!client || !ok) return oauthError(401, 'invalid_client', 'unknown client or wrong secret', basic);
252
+ const requested = String(params.scope ?? '').split(/\s+/).filter(Boolean);
253
+ const scope = requested.length ? requested : client.scopes;
254
+ // `admin` implies every scope, so an admin app can ask for a narrower token.
255
+ const allowedScopes = principal(id, client.scopes).scopes;
256
+ if (!scope.every(s => allowedScopes.has(s))) return oauthError(400, 'invalid_scope', `client ${id} may request: ${[...allowedScopes].join(' ')}`);
257
+ return {
258
+ status: 200,
259
+ headers: { 'cache-control': 'no-store', pragma: 'no-cache' },
260
+ body: { access_token: signer.sign({ sub: id, scope }), token_type: 'Bearer', expires_in: signer.ttlSeconds, scope: scope.join(' ') },
261
+ };
262
+ }
263
+
264
+ function oauthError(status, error, description, basic = false) {
265
+ return {
266
+ status,
267
+ headers: { 'cache-control': 'no-store', ...(status === 401 && basic ? { 'www-authenticate': 'Basic realm="fffleet"' } : {}) },
268
+ body: { error, error_description: description },
269
+ };
270
+ }
271
+
272
+ /**
273
+ * Client side: gets tokens from an orchestrator and refreshes them before they expire.
274
+ * @returns {{ get: (opts?: { refresh?: boolean }) => Promise<string> }}
275
+ */
276
+ export function createTokenProvider({ url, clientId, clientSecret, scope, fetch: f = globalThis.fetch, timeoutMs = 10000 }) {
277
+ let token = null;
278
+ let expiresAt = 0;
279
+ let pending = null;
280
+ 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`, {
283
+ method: 'POST',
284
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
285
+ body,
286
+ signal: AbortSignal.timeout(timeoutMs),
287
+ });
288
+ const json = await res.json().catch(() => null);
289
+ if (!res.ok || !json?.access_token) {
290
+ throw new FleetError(res.status === 401 ? 'UNAUTHORIZED' : 'LOGIN_FAILED', `login as ${clientId} failed: ${json?.error_description ?? json?.error ?? `HTTP ${res.status}`}`, { status: res.status });
291
+ }
292
+ token = json.access_token;
293
+ // Refresh when 80% of the lifetime has passed.
294
+ expiresAt = Date.now() + (json.expires_in ?? 3600) * 800;
295
+ return token;
296
+ }
297
+ return {
298
+ async get({ refresh = false } = {}) {
299
+ if (!refresh && token && Date.now() < expiresAt) return token;
300
+ pending ??= fetchToken().finally(() => (pending = null));
301
+ return pending;
302
+ },
303
+ };
304
+ }
package/src/client.js CHANGED
@@ -4,6 +4,7 @@ import { isFinal, parseSpec } from './contract.js';
4
4
  import { detectCapabilities } from './capabilities.js';
5
5
  import { JobManager } from './job-manager.js';
6
6
  import { FleetError } from './job-record.js';
7
+ import { createTokenProvider } from './auth.js';
7
8
  import { followJobEvents } from './sse.js';
8
9
 
9
10
  /**
@@ -58,32 +59,43 @@ export class JobHandle extends EventEmitter {
58
59
  *
59
60
  * @param {object} [opts]
60
61
  * @param {string} [opts.url]
61
- * @param {string} [opts.token]
62
+ * @param {string} [opts.token] A static bearer token.
63
+ * @param {string} [opts.clientId] With clientSecret: log in at the orchestrator (POST /v1/auth/token) instead of using a static token.
64
+ * @param {string} [opts.clientSecret]
65
+ * @param {string} [opts.scope] Narrow the token to some of the client's scopes, e.g. 'jobs'.
62
66
  * @param {'local' | 'none'} [opts.fallback]
63
67
  * @param {ConstructorParameters<typeof JobManager>[0]} [opts.local] Options for the local runner.
64
68
  * @param {typeof fetch} [opts.fetch]
65
69
  * @param {number} [opts.requestTimeoutMs]
66
70
  */
67
- export function createFleet({ url, token, fallback = 'local', local = {}, fetch: f = globalThis.fetch, requestTimeoutMs = 10000 } = {}) {
71
+ export function createFleet({ url, token, clientId, clientSecret, scope, fallback = 'local', local = {}, fetch: f = globalThis.fetch, requestTimeoutMs = 10000 } = {}) {
68
72
  const base = url ? url.replace(/\/+$/, '') : null;
69
- const headers = token ? { authorization: `Bearer ${token}` } : {};
73
+ const login = base && clientId && clientSecret ? createTokenProvider({ url: base, clientId, clientSecret, scope, fetch: f, timeoutMs: requestTimeoutMs }) : null;
74
+ const authHeaders = async (refresh = false) => {
75
+ if (login) return { authorization: `Bearer ${await login.get({ refresh })}` };
76
+ return token ? { authorization: `Bearer ${token}` } : {};
77
+ };
70
78
  let manager = null;
71
79
  const localManager = () => (manager ??= new JobManager(local));
72
80
  const controllers = new Set();
73
81
 
74
82
  async function request(method, path, body, extraHeaders = {}) {
75
- const res = await f(`${base}${path}`, {
76
- method,
77
- headers: { ...headers, ...(body !== undefined && !Buffer.isBuffer(body) ? { 'content-type': 'application/json' } : {}), ...extraHeaders },
78
- body: body === undefined ? undefined : Buffer.isBuffer(body) ? body : JSON.stringify(body),
79
- signal: AbortSignal.timeout(requestTimeoutMs),
80
- });
81
- const text = await res.text();
82
- const json = text ? JSON.parse(text) : null;
83
- if (!res.ok) {
84
- throw new FleetError(json?.error?.code ?? 'HTTP_ERROR', json?.error?.message ?? `HTTP ${res.status}`, { status: res.status, details: json?.error?.details });
83
+ for (let attempt = 0; ; attempt++) {
84
+ const res = await f(`${base}${path}`, {
85
+ method,
86
+ headers: { ...(await authHeaders(attempt > 0)), ...(body !== undefined && !Buffer.isBuffer(body) ? { 'content-type': 'application/json' } : {}), ...extraHeaders },
87
+ body: body === undefined ? undefined : Buffer.isBuffer(body) ? body : JSON.stringify(body),
88
+ signal: AbortSignal.timeout(requestTimeoutMs),
89
+ });
90
+ const text = await res.text();
91
+ const json = text ? JSON.parse(text) : null;
92
+ // An expired or revoked token: log in again once.
93
+ if (res.status === 401 && login && attempt === 0) continue;
94
+ if (!res.ok) {
95
+ throw new FleetError(json?.error?.code ?? 'HTTP_ERROR', json?.error?.message ?? `HTTP ${res.status}`, { status: res.status, details: json?.error?.details });
96
+ }
97
+ return json;
85
98
  }
86
- return json;
87
99
  }
88
100
 
89
101
  function submitLocal(spec) {
@@ -111,7 +123,7 @@ export function createFleet({ url, token, fallback = 'local', local = {}, fetch:
111
123
  const enc = encodeURIComponent(job.id);
112
124
  handle._cancel = () => request('DELETE', `/v1/jobs/${enc}`);
113
125
  handle._write = data => request('POST', `/v1/jobs/${enc}/stdin`, data, { 'content-type': 'application/octet-stream' });
114
- followJobEvents({ url: `${base}/v1/jobs/${enc}/events`, headers, signal: ac.signal, fetch: f, onEvent: e => handle._event(e) })
126
+ followJobEvents({ url: `${base}/v1/jobs/${enc}/events`, headers: authHeaders, signal: ac.signal, fetch: f, onEvent: e => handle._event(e) })
115
127
  .then(async () => {
116
128
  handle.snapshot = await request('GET', `/v1/jobs/${enc}`).catch(() => handle.snapshot);
117
129
  handle._resolve(handle.snapshot);