fffleet 0.1.0 → 2.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 +1 -1
- package/index.d.ts +95 -4
- package/package.json +1 -1
- package/server.d.ts +66 -2
- package/src/auth.js +304 -0
- package/src/client.js +45 -15
- package/src/contract.js +55 -6
- package/src/executor.js +89 -14
- package/src/http-api.js +53 -16
- package/src/http-stream.js +29 -0
- package/src/index.js +5 -2
- package/src/input-cache.js +104 -0
- package/src/job-manager.js +106 -9
- package/src/metrics.js +227 -0
- package/src/s3.js +290 -0
- package/src/server.js +7 -1
- package/src/sse.js +3 -2
- package/src/types.js +1 -0
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}}
|
|
18
|
+
/** Name used in placeholders: {{input:name}}, {{inputdir:name}} (the directory holding that staged input) and {{output:name}}. */
|
|
18
19
|
name: string;
|
|
19
|
-
/**
|
|
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;
|
|
@@ -41,6 +45,8 @@ export interface JobSpecInput {
|
|
|
41
45
|
timeoutMs?: number | null;
|
|
42
46
|
/** Keep ffmpeg's stdin open for writes through the API. */
|
|
43
47
|
stdin?: boolean;
|
|
48
|
+
/** Stream jobs only: ffmpeg's `pipe:1` is readable through `job.stdout()`. No `-progress` is reported. */
|
|
49
|
+
stdout?: boolean;
|
|
44
50
|
inputs?: Endpoint[];
|
|
45
51
|
outputs?: Endpoint[];
|
|
46
52
|
ffmpeg?: { args: string[]; durationMs?: number | null };
|
|
@@ -128,6 +134,8 @@ export function validateSpec(input: unknown): { ok: true; spec: JobSpec } | { ok
|
|
|
128
134
|
export function parseSpec(input: unknown): JobSpec;
|
|
129
135
|
export function resolvePlaceholders(args: string[], values: { input: Record<string, string>; output: Record<string, string> }): string[];
|
|
130
136
|
export function canonicalJson(value: unknown): string;
|
|
137
|
+
/** Capabilities a job needs beyond `requires`: `type:<type>`, plus `scheme:s3` for s3: URIs. */
|
|
138
|
+
export function implicitRequirements(spec: Pick<JobSpec, 'type' | 'inputs' | 'outputs'>): string[];
|
|
131
139
|
|
|
132
140
|
export interface ExecutorRuntime {
|
|
133
141
|
workDir: string;
|
|
@@ -135,8 +143,10 @@ export interface ExecutorRuntime {
|
|
|
135
143
|
setState(state: JobState, extra?: object): void;
|
|
136
144
|
progress(progress: Progress): void;
|
|
137
145
|
attachStdin(stdin: Writable | null): void;
|
|
146
|
+
attachStdout?(stdout: import('node:stream').Readable): void;
|
|
138
147
|
ffmpegPath?: string;
|
|
139
148
|
fetch?: typeof fetch;
|
|
149
|
+
s3?: S3Client | null;
|
|
140
150
|
}
|
|
141
151
|
|
|
142
152
|
export interface ExecutorResult {
|
|
@@ -148,8 +158,10 @@ export interface ExecutorResult {
|
|
|
148
158
|
export type Executor = (spec: JobSpec & { id: string }, runtime: ExecutorRuntime) => Promise<ExecutorResult>;
|
|
149
159
|
|
|
150
160
|
export interface JobManagerOptions {
|
|
151
|
-
/** Slots per class pool, e.g. { default: 2, stream: 1 }
|
|
161
|
+
/** 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
162
|
slots?: Record<string, number> | string;
|
|
163
|
+
/** 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. */
|
|
164
|
+
kinds?: JobKind[] | string;
|
|
153
165
|
workRoot?: string;
|
|
154
166
|
ffmpegPath?: string;
|
|
155
167
|
maxQueued?: number;
|
|
@@ -158,6 +170,10 @@ export interface JobManagerOptions {
|
|
|
158
170
|
executors?: Record<string, Executor>;
|
|
159
171
|
workerId?: string | null;
|
|
160
172
|
fetch?: typeof fetch;
|
|
173
|
+
/** S3 settings or a client; enables s3: URIs. */
|
|
174
|
+
s3?: S3Config | S3Client | null;
|
|
175
|
+
/** 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). */
|
|
176
|
+
cache?: { dir: string; maxBytes?: number | string } | null;
|
|
161
177
|
}
|
|
162
178
|
|
|
163
179
|
export interface PoolStats {
|
|
@@ -168,6 +184,8 @@ export interface PoolStats {
|
|
|
168
184
|
export class JobManager {
|
|
169
185
|
constructor(opts?: JobManagerOptions);
|
|
170
186
|
readonly slots: Record<string, number>;
|
|
187
|
+
readonly kinds: JobKind[];
|
|
188
|
+
readonly cache: InputCache | null;
|
|
171
189
|
submit(spec: JobSpecInput): { created: boolean; queued?: boolean; job: JobSnapshot };
|
|
172
190
|
get(id: string): JobSnapshot | null;
|
|
173
191
|
list(): JobSnapshot[];
|
|
@@ -179,7 +197,18 @@ export class JobManager {
|
|
|
179
197
|
close(): Promise<void>;
|
|
180
198
|
}
|
|
181
199
|
|
|
182
|
-
export function normalizeSlots(slots: Record<string, number | string> | string): Record<string, number>;
|
|
200
|
+
export function normalizeSlots(slots: Record<string, number | string> | string, opts?: { kinds?: JobKind[]; cpus?: number }): Record<string, number>;
|
|
201
|
+
/** Parses 'batch,stream' or an array; no value means both kinds. */
|
|
202
|
+
export interface InputCache {
|
|
203
|
+
readonly stats: { hits: number; misses: number };
|
|
204
|
+
stage(opts: { key: string; validator: string; target: string; download: (path: string) => Promise<void> }): Promise<'hit' | 'miss'>;
|
|
205
|
+
}
|
|
206
|
+
export function createInputCache(opts: { dir: string; maxBytes?: number }): InputCache;
|
|
207
|
+
/** "500", "20MB", "50GB" (decimal units) as bytes. */
|
|
208
|
+
export function parseSize(value: number | string): number;
|
|
209
|
+
export function normalizeKinds(kinds?: JobKind[] | string): JobKind[];
|
|
210
|
+
/** Slot pools sized from the CPU count: batch only cores/2, stream only cores, both: default cores/2 plus stream cores/4. */
|
|
211
|
+
export function autoSlots(opts?: { cpus?: number; kinds?: JobKind[]; coresPerSlot?: number }): Record<string, number>;
|
|
183
212
|
export function runFfmpegJob(spec: JobSpec & { id: string }, runtime: ExecutorRuntime): Promise<Required<ExecutorResult>>;
|
|
184
213
|
|
|
185
214
|
export class JobHandle extends EventEmitter {
|
|
@@ -191,6 +220,10 @@ export class JobHandle extends EventEmitter {
|
|
|
191
220
|
readonly done: Promise<JobSnapshot>;
|
|
192
221
|
cancel(): Promise<unknown>;
|
|
193
222
|
write(data: Buffer | string): Promise<{ bytes: number }>;
|
|
223
|
+
/** Closes ffmpeg's stdin (EOF) after the last write. */
|
|
224
|
+
endStdin(): Promise<{ closed: boolean }>;
|
|
225
|
+
/** ffmpeg's stdout as a Readable (the job must have been submitted with `stdout: true`). */
|
|
226
|
+
stdout(): Promise<import('node:stream').Readable>;
|
|
194
227
|
on(event: 'event', listener: (event: JobEvent) => void): this;
|
|
195
228
|
on(event: 'state', listener: (state: JobState, event: JobEvent) => void): this;
|
|
196
229
|
on(event: 'progress', listener: (progress: Progress, event: JobEvent) => void): this;
|
|
@@ -200,7 +233,13 @@ export class JobHandle extends EventEmitter {
|
|
|
200
233
|
export interface FleetOptions {
|
|
201
234
|
/** A worker or an orchestrator. Without it every job runs on this machine. */
|
|
202
235
|
url?: string;
|
|
236
|
+
/** A static bearer token. */
|
|
203
237
|
token?: string;
|
|
238
|
+
/** With `clientSecret`: log in at the orchestrator (POST /v1/auth/token) and refresh the token before it expires. */
|
|
239
|
+
clientId?: string;
|
|
240
|
+
clientSecret?: string;
|
|
241
|
+
/** Narrow the token to some of the app's scopes, e.g. 'jobs'. */
|
|
242
|
+
scope?: string;
|
|
204
243
|
/** 'local' (default) runs a job here when the remote cannot be reached or answers 502/503. */
|
|
205
244
|
fallback?: 'local' | 'none';
|
|
206
245
|
/** Options for the local runner. */
|
|
@@ -253,3 +292,55 @@ export class JobRecord {
|
|
|
253
292
|
|
|
254
293
|
export function byPriority(a: JobRecord, b: JobRecord): number;
|
|
255
294
|
export function pruneFinished(jobs: Map<string, JobRecord>, keep: number): void;
|
|
295
|
+
|
|
296
|
+
export type Scope = 'jobs' | 'metrics' | 'admin';
|
|
297
|
+
export const SCOPES: readonly Scope[];
|
|
298
|
+
/** Hashes a client secret for the clients file (`scrypt$...`). */
|
|
299
|
+
export function hashSecret(secret: string): Promise<string>;
|
|
300
|
+
export function verifySecret(secret: string, stored: string | undefined): Promise<boolean>;
|
|
301
|
+
/** A random client secret. */
|
|
302
|
+
export function generateSecret(): string;
|
|
303
|
+
/** Gets tokens from an orchestrator and refreshes them before they expire. */
|
|
304
|
+
export function createTokenProvider(opts: {
|
|
305
|
+
url: string;
|
|
306
|
+
clientId: string;
|
|
307
|
+
clientSecret: string;
|
|
308
|
+
scope?: string;
|
|
309
|
+
fetch?: typeof fetch;
|
|
310
|
+
timeoutMs?: number;
|
|
311
|
+
}): { get(opts?: { refresh?: boolean }): Promise<string> };
|
|
312
|
+
|
|
313
|
+
export interface S3Config {
|
|
314
|
+
accessKeyId: string;
|
|
315
|
+
secretAccessKey: string;
|
|
316
|
+
sessionToken?: string;
|
|
317
|
+
/** Defaults to us-east-1. */
|
|
318
|
+
region?: string;
|
|
319
|
+
/** For S3-compatible stores, e.g. http://minio:9000. Defaults to AWS for the region. */
|
|
320
|
+
endpoint?: string;
|
|
321
|
+
/** Bucket in the path rather than the host name; defaults to true when `endpoint` is set. */
|
|
322
|
+
pathStyle?: boolean;
|
|
323
|
+
fetch?: typeof fetch;
|
|
324
|
+
/** Multipart part size in bytes (16 MiB by default; S3 needs at least 5 MiB). */
|
|
325
|
+
partSize?: number;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
export interface S3Client {
|
|
329
|
+
getFile(bucket: string, key: string, path: string, opts?: { signal?: AbortSignal }): Promise<void>;
|
|
330
|
+
head(bucket: string, key: string, opts?: { signal?: AbortSignal }): Promise<{ size: number; etag: string | null }>;
|
|
331
|
+
putFile(bucket: string, key: string, path: string, opts?: { contentType?: string; signal?: AbortSignal; forceMultipart?: boolean }): Promise<number>;
|
|
332
|
+
putDirectory(bucket: string, prefix: string, dir: string, opts?: { signal?: AbortSignal }): Promise<number>;
|
|
333
|
+
deleteObject(bucket: string, key: string, opts?: { signal?: AbortSignal }): Promise<void>;
|
|
334
|
+
createBucket(bucket: string, opts?: { signal?: AbortSignal }): Promise<void>;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
export function createS3Client(config: S3Config): S3Client;
|
|
338
|
+
/** Reads AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, AWS_REGION, FFFLEET_S3_ENDPOINT, FFFLEET_S3_PATH_STYLE. */
|
|
339
|
+
export function s3ConfigFromEnv(env?: Record<string, string | undefined>): S3Config | null;
|
|
340
|
+
export function parseS3Uri(uri: string): { bucket: string; key: string };
|
|
341
|
+
export function contentTypeFor(name: string): string;
|
|
342
|
+
export function signV4(
|
|
343
|
+
req: { method: string; url: URL; headers: Record<string, string>; payloadHash: string },
|
|
344
|
+
creds: { accessKeyId: string; secretAccessKey: string; region: string },
|
|
345
|
+
service?: string,
|
|
346
|
+
): string;
|
package/package.json
CHANGED
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,15 +16,78 @@ 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
|
-
|
|
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;
|
|
26
42
|
export function send(res: ServerResponse, status: number, body: unknown, headers?: Record<string, string>): void;
|
|
27
43
|
export function sendError(res: ServerResponse, err: unknown): void;
|
|
44
|
+
export function getStream(url: string, opts?: { headers?: Record<string, string>; signal?: AbortSignal }): Promise<import('node:http').IncomingMessage>;
|
|
28
45
|
export function readBody(req: IncomingMessage, limit: number): Promise<Buffer>;
|
|
29
46
|
export function readJson(req: IncomingMessage): Promise<unknown>;
|
|
47
|
+
|
|
48
|
+
export const METRICS_CONTENT_TYPE: string;
|
|
49
|
+
export class Registry {
|
|
50
|
+
counter(name: string, help: string, labelNames?: string[]): { inc(labels?: Record<string, string>, n?: number): void };
|
|
51
|
+
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 };
|
|
52
|
+
histogram(name: string, help: string, labelNames?: string[], buckets?: number[]): { observe(labels: Record<string, string>, v: number): void };
|
|
53
|
+
/** Runs before every render, to refresh gauges. */
|
|
54
|
+
collect(fn: () => void | Promise<void>): void;
|
|
55
|
+
render(): Promise<string>;
|
|
56
|
+
}
|
|
57
|
+
export function jobMetrics(registry: Registry, records: () => Iterable<unknown>): { track(record: unknown): void };
|
|
58
|
+
export function processMetrics(registry: Registry): void;
|
|
59
|
+
export function hostMetrics(registry: Registry, dir?: string): void;
|
|
60
|
+
export function procStats(pid: number): Promise<{ cpuSeconds: number; rssBytes: number } | null>;
|
|
61
|
+
|
|
62
|
+
export const SCOPES: readonly Scope[];
|
|
63
|
+
export function hashSecret(secret: string): Promise<string>;
|
|
64
|
+
export function verifySecret(secret: string, stored: string | undefined): Promise<boolean>;
|
|
65
|
+
export function generateSecret(): string;
|
|
66
|
+
export function loadSigningKey(path?: string | null): KeyObject;
|
|
67
|
+
export interface TokenSigner {
|
|
68
|
+
kid: string;
|
|
69
|
+
issuer: string;
|
|
70
|
+
ttlSeconds: number;
|
|
71
|
+
publicKey: KeyObject;
|
|
72
|
+
sign(claims: { sub: string; scope: string[] }): string;
|
|
73
|
+
jwks(): { keys: Record<string, unknown>[] };
|
|
74
|
+
}
|
|
75
|
+
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>;
|
|
77
|
+
export function createRemoteKeySet(url: string, opts?: { fetch?: typeof fetch; minRefreshMs?: number }): (kid: string) => Promise<KeyObject | null>;
|
|
78
|
+
export function createAuthenticator(opts: {
|
|
79
|
+
token?: string | null;
|
|
80
|
+
verify?: ((token: string) => Promise<{ sub: string; scope: string[] } | null>) | null;
|
|
81
|
+
isActive?: (sub: string) => boolean;
|
|
82
|
+
open?: boolean;
|
|
83
|
+
}): Authenticator;
|
|
84
|
+
export interface ClientEntry {
|
|
85
|
+
id: string;
|
|
86
|
+
secretHash: string;
|
|
87
|
+
scopes?: Scope[];
|
|
88
|
+
}
|
|
89
|
+
export function createClientStore(source: string | ClientEntry[] | null): { get(id: string): ClientEntry | null; has(id: string): boolean; readonly size: number } | null;
|
|
90
|
+
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> }>;
|
|
91
|
+
export function principal(sub: string, scopes: Iterable<Scope>): Principal;
|
|
92
|
+
export function bearerOf(req: IncomingMessage): string | null;
|
|
93
|
+
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
|
+
}
|