@flytedesk/app-kit 9.0.0 → 10.0.1
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 +121 -2
- package/dist/auth/errors.d.ts +20 -0
- package/dist/auth/errors.js +24 -0
- package/dist/auth/errors.js.map +1 -1
- package/dist/auth/guards.d.ts +18 -0
- package/dist/auth/guards.js +34 -0
- package/dist/auth/guards.js.map +1 -1
- package/dist/auth/idpFetch.d.ts +26 -0
- package/dist/auth/idpFetch.js +38 -0
- package/dist/auth/idpFetch.js.map +1 -0
- package/dist/auth/index.d.ts +10 -4
- package/dist/auth/index.js +8 -2
- package/dist/auth/index.js.map +1 -1
- package/dist/auth/oidc-client.d.ts +35 -7
- package/dist/auth/oidc-client.js +69 -37
- package/dist/auth/oidc-client.js.map +1 -1
- package/dist/auth/plugin.d.ts +5 -0
- package/dist/auth/plugin.js +158 -56
- package/dist/auth/plugin.js.map +1 -1
- package/dist/auth/readRoute.d.ts +20 -0
- package/dist/auth/readRoute.js +20 -0
- package/dist/auth/readRoute.js.map +1 -0
- package/dist/auth/service/index.d.ts +61 -0
- package/dist/auth/service/index.js +145 -0
- package/dist/auth/service/index.js.map +1 -0
- package/dist/auth/serviceTokenContract.d.ts +33 -0
- package/dist/auth/serviceTokenContract.js +40 -0
- package/dist/auth/serviceTokenContract.js.map +1 -0
- package/dist/auth/shared-types.d.ts +6 -3
- package/dist/auth/shared-types.js.map +1 -1
- package/dist/auth/testing/fake-idp.d.ts +97 -1
- package/dist/auth/testing/fake-idp.js +179 -1
- package/dist/auth/testing/fake-idp.js.map +1 -1
- package/dist/auth/testing/index.d.ts +1 -1
- package/dist/auth/testing/index.js +1 -1
- package/dist/auth/testing/index.js.map +1 -1
- package/dist/auth/types.d.ts +29 -5
- package/dist/bigquery/load.d.ts +1 -1
- package/dist/bigquery/load.js +4 -4
- package/dist/bigquery/query.js +58 -15
- package/dist/bigquery/query.js.map +1 -1
- package/dist/profile/plugin.js +11 -7
- package/dist/profile/plugin.js.map +1 -1
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -6,7 +6,8 @@ what `danx` is for the PHP apps.
|
|
|
6
6
|
Five subpath modules, one npm package:
|
|
7
7
|
|
|
8
8
|
- `@flytedesk/app-kit/auth` — the flytedesk-id BFF/OIDC client (PKCE, session issuance,
|
|
9
|
-
live per-request authorization)
|
|
9
|
+
live per-request authorization), which also accepts read-only flytedesk ID service
|
|
10
|
+
principals; `@flytedesk/app-kit/auth/service` is the service caller's side.
|
|
10
11
|
- `@flytedesk/app-kit/trace` — a Postgres-native trace/audit layer (HTTP request → job →
|
|
11
12
|
DB write → logs, one queryable trace), buffered through Pub/Sub, with a scheduled
|
|
12
13
|
retention/prune job.
|
|
@@ -336,6 +337,124 @@ callback redirects to the same place with `?signin_error=<expired|cancelled|othe
|
|
|
336
337
|
(never the raw internal reason, which is logged server-side only); the browser lifecycle
|
|
337
338
|
reads and strips it and shows the sign-in-failed state with a manual retry.
|
|
338
339
|
|
|
340
|
+
### Service principals (10.0)
|
|
341
|
+
|
|
342
|
+
A **service principal** is a flytedesk ID identity for an unattended caller — a profiler,
|
|
343
|
+
a job — rather than a person. It calls an app's API with a short-lived flytedesk ID
|
|
344
|
+
**service access token** and is **read-only by kind**: it can read whatever its roles
|
|
345
|
+
allow and can never write. There is no secret anywhere: the caller proves who it is with
|
|
346
|
+
a Google ID token (a Google service account), and flytedesk ID exchanges that for a
|
|
347
|
+
10-minute token for one app (`POST {issuer}/service-token`, RFC 8693).
|
|
348
|
+
|
|
349
|
+
**How the plugin accepts one.** `flytedeskAuth` reads the bearer token's protected header
|
|
350
|
+
first. `typ: at+jwt` is a service access token (RFC 9068); anything else is the app's own
|
|
351
|
+
session token, verified exactly as before. Each kind is verified only its own way — a
|
|
352
|
+
token that fails its path never falls back to the other. A service token must be RS256,
|
|
353
|
+
signed by a key at `{issuer}/jwks`, with `iss` = `issuer`, `aud` = this app's `appId`, an
|
|
354
|
+
unexpired `exp`, and `fd_kind: service` (so a flytedesk ID id_token for the same app is
|
|
355
|
+
refused). The plugin then asks `GET {issuer}/apps/{appId}/authorization` live, with that
|
|
356
|
+
same token, who the principal is and what it may do here; the answer must be
|
|
357
|
+
`kind: "service"` for the token's `sub`. So a principal disabled in flytedesk ID, or a
|
|
358
|
+
role revoked, is refused on its very next request.
|
|
359
|
+
|
|
360
|
+
- Refused token or principal: `request.authUser` stays unset, so `requireAuth` answers
|
|
361
|
+
`401 unauthenticated`.
|
|
362
|
+
- flytedesk ID or its JWKS unreachable: `503 idp_unavailable`, as for a person.
|
|
363
|
+
- `authorizationCacheTtlMs`, when set, caches the answer per principal.
|
|
364
|
+
- `onAuthorizeUser` runs for service principals too; the user it returns must keep its
|
|
365
|
+
`kind` (a hook that returns another kind is answered `503 authorization_hook_failed`).
|
|
366
|
+
|
|
367
|
+
**`request.authUser` is a union.** `AuthedUser = AuthedUserDto | ServicePrincipalUser`:
|
|
368
|
+
|
|
369
|
+
```ts
|
|
370
|
+
// a person (a browser session)
|
|
371
|
+
{ kind: "person", id, email, name, sessionId, roles, permissions }
|
|
372
|
+
// a service principal: no email, no session
|
|
373
|
+
{ kind: "service", id /* e.g. "svc-sms-app-prod-profiler" */, name, roles, permissions }
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
Narrow on `kind` before reading `email` or `sessionId`. `GET {routePrefix}/me` answers
|
|
377
|
+
whichever one the caller is.
|
|
378
|
+
|
|
379
|
+
**What a service principal can do:** `GET` and `HEAD` on any route, and any other method
|
|
380
|
+
on a route marked `readRoute`. `requireAuth` and `requirePermission` work for it exactly
|
|
381
|
+
as for a person, so its roles still decide which reads it may make.
|
|
382
|
+
|
|
383
|
+
**What it cannot do:**
|
|
384
|
+
|
|
385
|
+
- Any other request. The plugin answers `403 read_only_principal` from its own
|
|
386
|
+
`onRequest` hook, before any guard or handler runs, even on a route with no guard and
|
|
387
|
+
even when the principal holds every permission. That includes the plugin's own `POST
|
|
388
|
+
{routePrefix}/refresh` and `/logout`.
|
|
389
|
+
- A route guarded by `requirePerson`: `403 person_only`. The plugin's `GET
|
|
390
|
+
{routePrefix}/apps` and `@flytedesk/app-kit/profile`'s routes are person-only.
|
|
391
|
+
|
|
392
|
+
**Marking reads.** A route that only reads but is not a GET — a query sent as a POST
|
|
393
|
+
body — declares it with `config: readRoute`:
|
|
394
|
+
|
|
395
|
+
```ts
|
|
396
|
+
import { readRoute, requirePermission } from "@flytedesk/app-kit/auth";
|
|
397
|
+
|
|
398
|
+
app.post("/audiences/count", { config: readRoute, preHandler: requirePermission("access") }, countAudience);
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
Mark only routes that change nothing. A principal has no row in the app's own user
|
|
402
|
+
table, so a GET (or a marked route) that writes something keyed to the caller — an
|
|
403
|
+
audit row, a "last run by" foreign key — must be made safe for it, or guarded with
|
|
404
|
+
`requirePerson`.
|
|
405
|
+
|
|
406
|
+
**Person-only routes.** Guard a route that is about a person (their own data, anything
|
|
407
|
+
keyed to a session or an email) with `requirePerson`, and read the person with
|
|
408
|
+
`authedPerson(request)`, already narrowed:
|
|
409
|
+
|
|
410
|
+
```ts
|
|
411
|
+
import { authedPerson, requirePerson } from "@flytedesk/app-kit/auth";
|
|
412
|
+
|
|
413
|
+
app.post("/imports", { preHandler: requirePerson }, async (request) => {
|
|
414
|
+
const { id, email } = authedPerson(request);
|
|
415
|
+
// ...
|
|
416
|
+
});
|
|
417
|
+
```
|
|
418
|
+
|
|
419
|
+
**The caller's side: `@flytedesk/app-kit/auth/service`.** Node-only, and it never
|
|
420
|
+
imports Fastify, so a caller that is not a Fastify app gets none of the plugin's request
|
|
421
|
+
augmentation. Getting the Google ID token is the caller's job — `gcloud auth
|
|
422
|
+
print-identity-token --impersonate-service-account=<sa> --audiences=<audience>
|
|
423
|
+
--include-email`, or the metadata server — for the audience
|
|
424
|
+
`serviceTokenAudience(issuer)` (`{issuer}/service-token`).
|
|
425
|
+
|
|
426
|
+
```ts
|
|
427
|
+
import { createServiceTokenSource } from "@flytedesk/app-kit/auth/service";
|
|
428
|
+
|
|
429
|
+
const tokens = createServiceTokenSource({
|
|
430
|
+
issuer: "https://id.flytedesk.com", // exactly flytedesk ID's issuer, no trailing slash
|
|
431
|
+
appId: "sms-app",
|
|
432
|
+
idToken: (audience) => googleIdTokenFor(audience),
|
|
433
|
+
});
|
|
434
|
+
const res = await fetch(url, { headers: { Authorization: `Bearer ${await tokens.accessToken()}` } });
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
- `createServiceTokenSource({ issuer, appId, idToken, clock?, refreshSkewMs = 60_000,
|
|
438
|
+
fetch?, timeoutMs? })` caches the token until `refreshSkewMs` before its `exp`;
|
|
439
|
+
concurrent calls share one exchange, and a failed exchange is not cached.
|
|
440
|
+
- `exchangeServiceToken({ issuer, appId, subjectToken, fetch?, timeoutMs? })` is the one
|
|
441
|
+
exchange, answering `{ accessToken, expiresAt }`.
|
|
442
|
+
- Errors: `ServiceTokenRefusedError` (flytedesk ID answered 4xx; `oauthError` is
|
|
443
|
+
`invalid_grant` for a refused Google token or an unknown, mismatched or disabled
|
|
444
|
+
principal, `invalid_target` for a principal with no role in the app, `invalid_request`
|
|
445
|
+
for a malformed request — retrying will not help), `IdpTimeoutError` and
|
|
446
|
+
`IdpUnavailableError` (an outage or an unusable answer — retry later).
|
|
447
|
+
|
|
448
|
+
**Testing.** `FakeIdp` models service identities: register them with `servicePrincipals`
|
|
449
|
+
(`id`, `name`, `roles`, `permissions`, `googleSubject`, `googleEmail`, `disabled`). Its
|
|
450
|
+
`POST /service-token` exchanges a Google ID token from its own Google stand-in
|
|
451
|
+
(`mintGoogleIdToken`), and its authorization endpoint answers a service token as
|
|
452
|
+
`kind: "service"`. `mintServiceAccessToken(principalId, overrides)` mints a token
|
|
453
|
+
directly, with overrides (`audience`, `issuer`, `typ`, `fdKind`, `expiresInSeconds`) for
|
|
454
|
+
the negative paths. Controls: `setServicePrincipalDisabled`,
|
|
455
|
+
`setForceServicePrincipalMismatch`, `serviceTokenIssueCount`,
|
|
456
|
+
`serviceAuthorizationCount`.
|
|
457
|
+
|
|
339
458
|
## BigQuery (`@flytedesk/app-kit/bigquery`)
|
|
340
459
|
|
|
341
460
|
This module takes no hard dependency on any GCP SDK — every function accepts a
|
|
@@ -378,7 +497,7 @@ and a 403 `PermissionDeniedError`. There is no retry. A table without `insert` t
|
|
|
378
497
|
- **A load's `jobId` is now the id the job is submitted under, and reusing one is not an error.** In v8.0.0 `BigQueryLoadOptions.jobId` reached only a stream load, where an id that already existed failed with a 409. Now both load helpers use it (a random id when omitted), and an id that already exists means that job is waited on and ITS result returned (for a stream load, the rows it counted when the job exists from this call, otherwise the `outputRows` BigQuery reports): nothing is loaded again. Give each logical load its own id.
|
|
379
498
|
- When attempts or the time budget run out, the transient error is thrown, classified, with the attempt count in its message.
|
|
380
499
|
|
|
381
|
-
**Client-side wait bound** — `jobTimeoutMs` is ONE total budget for the whole `runQuery` / `estimateQueryBytes` call: the creation of every job, every results wait, and every retry backoff. Each job is created with a `jobTimeoutMs` of only what remains, and every `getQueryResults` waits at most what remains
|
|
500
|
+
**Client-side wait bound** — `jobTimeoutMs` is ONE total budget for the whole `runQuery` / `estimateQueryBytes` call: the creation of every job, every results wait, and every retry backoff. Each job is created with a `jobTimeoutMs` of only what remains, and every `getQueryResults` waits at most what remains. BigQuery holds one request for at most about 197 s, so a job still unfinished after that makes the SDK reject with "did not complete before Nms" with budget left; that rejection (like a `jobComplete: false` answer) is asked again with what remains, and `JobTimeoutError` is thrown only once the budget is spent or when BigQuery stops the job. No attempt or request starts once the budget is spent (a backoff is clamped to what remains); the transient error is then thrown, classified, with the attempt count. A later-page fetch (`pageToken`) passes `jobTimeoutMs` as its `timeoutMs` unchanged.
|
|
382
501
|
|
|
383
502
|
**Row unwrapping** — `unwrapBigQueryRow(row)` returns a new object with `unwrapBigQueryValue`
|
|
384
503
|
applied to every field.
|
package/dist/auth/errors.d.ts
CHANGED
|
@@ -34,6 +34,26 @@ export declare class IdpTimeoutError extends IdpUnavailableError {
|
|
|
34
34
|
export declare class IdpAccessRevokedError extends IdpError {
|
|
35
35
|
constructor(message: string, cause?: unknown);
|
|
36
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* flytedesk ID refused a service-token exchange (`POST {issuer}/service-token`) with a
|
|
39
|
+
* 4xx — a verdict about this caller, not an outage: the Google ID token was rejected
|
|
40
|
+
* (`invalid_grant`: wrong audience or issuer, expired, unverified email, an unknown,
|
|
41
|
+
* mismatched or disabled principal), the principal holds no role in the requested app
|
|
42
|
+
* (`invalid_target`), or the request was malformed (`invalid_request`). Retrying the
|
|
43
|
+
* same request will not help; fix the principal's registration or the caller.
|
|
44
|
+
*/
|
|
45
|
+
export declare class ServiceTokenRefusedError extends IdpError {
|
|
46
|
+
readonly status: number;
|
|
47
|
+
/** The RFC 6749 §5.2 `error` code, when the body carried one. */
|
|
48
|
+
readonly oauthError: string | undefined;
|
|
49
|
+
/** The body's `error_description`, when it carried one. */
|
|
50
|
+
readonly description: string | undefined;
|
|
51
|
+
constructor(message: string, status: number,
|
|
52
|
+
/** The RFC 6749 §5.2 `error` code, when the body carried one. */
|
|
53
|
+
oauthError: string | undefined,
|
|
54
|
+
/** The body's `error_description`, when it carried one. */
|
|
55
|
+
description: string | undefined);
|
|
56
|
+
}
|
|
37
57
|
/** The injected AuthStore (findIdpSession/updateIdpSession/deleteIdpSession/...) threw —
|
|
38
58
|
* a storage-layer failure (DB down, constraint violation, ...), never to be confused
|
|
39
59
|
* with "no session found" (which is a legitimate, expected outcome, not an error). */
|
package/dist/auth/errors.js
CHANGED
|
@@ -47,6 +47,30 @@ export class IdpAccessRevokedError extends IdpError {
|
|
|
47
47
|
this.name = "IdpAccessRevokedError";
|
|
48
48
|
}
|
|
49
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* flytedesk ID refused a service-token exchange (`POST {issuer}/service-token`) with a
|
|
52
|
+
* 4xx — a verdict about this caller, not an outage: the Google ID token was rejected
|
|
53
|
+
* (`invalid_grant`: wrong audience or issuer, expired, unverified email, an unknown,
|
|
54
|
+
* mismatched or disabled principal), the principal holds no role in the requested app
|
|
55
|
+
* (`invalid_target`), or the request was malformed (`invalid_request`). Retrying the
|
|
56
|
+
* same request will not help; fix the principal's registration or the caller.
|
|
57
|
+
*/
|
|
58
|
+
export class ServiceTokenRefusedError extends IdpError {
|
|
59
|
+
status;
|
|
60
|
+
oauthError;
|
|
61
|
+
description;
|
|
62
|
+
constructor(message, status,
|
|
63
|
+
/** The RFC 6749 §5.2 `error` code, when the body carried one. */
|
|
64
|
+
oauthError,
|
|
65
|
+
/** The body's `error_description`, when it carried one. */
|
|
66
|
+
description) {
|
|
67
|
+
super(message);
|
|
68
|
+
this.status = status;
|
|
69
|
+
this.oauthError = oauthError;
|
|
70
|
+
this.description = description;
|
|
71
|
+
this.name = "ServiceTokenRefusedError";
|
|
72
|
+
}
|
|
73
|
+
}
|
|
50
74
|
/** The injected AuthStore (findIdpSession/updateIdpSession/deleteIdpSession/...) threw —
|
|
51
75
|
* a storage-layer failure (DB down, constraint violation, ...), never to be confused
|
|
52
76
|
* with "no session found" (which is a legitimate, expected outcome, not an error). */
|
package/dist/auth/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/auth/errors.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,mFAAmF;AACnF,MAAM,OAAO,QAAS,SAAQ,KAAK;IAGf;IAFlB,YACE,OAAe,EACC,KAAe;QAE/B,KAAK,CAAC,OAAO,CAAC,CAAC;QAFC,UAAK,GAAL,KAAK,CAAU;QAG/B,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;IACzB,CAAC;CACF;AAED;;sBAEsB;AACtB,MAAM,OAAO,mBAAoB,SAAQ,QAAQ;IAC/C,YAAY,OAAe,EAAE,KAAe;QAC1C,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACtB,IAAI,CAAC,IA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UAA8B;QAE9C,KAAK,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAFP,eAAU,GAAV,UAAU,CAAoB;QAG9C,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAC/B,CAAC;CACF;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,gBAAgB,CAAC,GAAY;IAC3C,IAAI,GAAG,YAAY,qBAAqB,IAAI,GAAG,YAAY,mBAAmB;QAAE,OAAO,GAAG,CAAC;IAE3F,MAAM,OAAO,GACX,GAAG,YAAY,cAAc;QAC3B,CAAC,CAAC,GAAG,CAAC,UAAU,KAAK,eAAe;QACpC,CAAC,CAAC,GAAG,YAAY,aAAa,IAAI,CAAC,GAAG,CAAC,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,CAAC,CAAC;IACjF,IAAI,OAAO,EAAE,CAAC;QACZ,OAAO,IAAI,qBAAqB,CAAE,GAAa,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;IAChE,CAAC;IACD,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACjE,OAAO,IAAI,mBAAmB,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AAC/C,CAAC"}
|
package/dist/auth/guards.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { FastifyReply, FastifyRequest } from "fastify";
|
|
2
|
+
import type { AuthedUserDto } from "./shared-types.js";
|
|
2
3
|
/**
|
|
3
4
|
* Answers the request when it carries no authorized user, and returns whether it did.
|
|
4
5
|
* AK-23: when the plugin could not DECIDE (flytedesk-id or the AuthStore unavailable,
|
|
@@ -15,3 +16,20 @@ export declare function requireAuth(request: FastifyRequest, reply: FastifyReply
|
|
|
15
16
|
/** Every route re-checks permissions server-side. 403s name the missing permission(s)
|
|
16
17
|
* in `detail`, so a caller (or its UI) can tell exactly what was missing. */
|
|
17
18
|
export declare function requirePermission(...permission: string[]): (request: FastifyRequest, reply: FastifyReply, done: () => void) => void;
|
|
19
|
+
/**
|
|
20
|
+
* Answers the request unless it carries a signed-in PERSON, and returns whether it did:
|
|
21
|
+
* `rejectUnauthenticated`'s 401/503 first, then `403 person_only` for a service
|
|
22
|
+
* principal. The one person check: `requirePerson`, the plugin's `GET
|
|
23
|
+
* {routePrefix}/apps` and the `@flytedesk/app-kit/profile` routes all answer through it.
|
|
24
|
+
*/
|
|
25
|
+
export declare function rejectUnlessPerson(request: FastifyRequest, reply: FastifyReply): boolean;
|
|
26
|
+
/** For a route that only a signed-in person may use (a person's own data, anything
|
|
27
|
+
* keyed to a session or an email): a service principal is answered `403 person_only`.
|
|
28
|
+
* Read the person with `authedPerson(request)`. */
|
|
29
|
+
export declare function requirePerson(request: FastifyRequest, reply: FastifyReply, done: () => void): void;
|
|
30
|
+
/**
|
|
31
|
+
* `request.authUser`, narrowed to the person — for a handler behind `requirePerson`
|
|
32
|
+
* (or after `rejectUnlessPerson` answered `false`). Throws when the request carries no
|
|
33
|
+
* person: that is a route missing its guard, a bug to fix, never a caller's fault.
|
|
34
|
+
*/
|
|
35
|
+
export declare function authedPerson(request: FastifyRequest): AuthedUserDto;
|
package/dist/auth/guards.js
CHANGED
|
@@ -43,4 +43,38 @@ export function requirePermission(...permission) {
|
|
|
43
43
|
done();
|
|
44
44
|
};
|
|
45
45
|
}
|
|
46
|
+
/**
|
|
47
|
+
* Answers the request unless it carries a signed-in PERSON, and returns whether it did:
|
|
48
|
+
* `rejectUnauthenticated`'s 401/503 first, then `403 person_only` for a service
|
|
49
|
+
* principal. The one person check: `requirePerson`, the plugin's `GET
|
|
50
|
+
* {routePrefix}/apps` and the `@flytedesk/app-kit/profile` routes all answer through it.
|
|
51
|
+
*/
|
|
52
|
+
export function rejectUnlessPerson(request, reply) {
|
|
53
|
+
if (rejectUnauthenticated(request, reply))
|
|
54
|
+
return true;
|
|
55
|
+
if (request.authUser.kind === "person")
|
|
56
|
+
return false;
|
|
57
|
+
reply.code(403).send({ error: "Only a signed-in person can use this route", code: "person_only" });
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
/** For a route that only a signed-in person may use (a person's own data, anything
|
|
61
|
+
* keyed to a session or an email): a service principal is answered `403 person_only`.
|
|
62
|
+
* Read the person with `authedPerson(request)`. */
|
|
63
|
+
export function requirePerson(request, reply, done) {
|
|
64
|
+
if (rejectUnlessPerson(request, reply))
|
|
65
|
+
return;
|
|
66
|
+
done();
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* `request.authUser`, narrowed to the person — for a handler behind `requirePerson`
|
|
70
|
+
* (or after `rejectUnlessPerson` answered `false`). Throws when the request carries no
|
|
71
|
+
* person: that is a route missing its guard, a bug to fix, never a caller's fault.
|
|
72
|
+
*/
|
|
73
|
+
export function authedPerson(request) {
|
|
74
|
+
const user = request.authUser;
|
|
75
|
+
if (user?.kind !== "person") {
|
|
76
|
+
throw new Error(`@flytedesk/app-kit/auth: authedPerson() on a request without a signed-in person (${user ? `a ${user.kind} principal` : "unauthenticated"}) — guard the route with requirePerson`);
|
|
77
|
+
}
|
|
78
|
+
return user;
|
|
79
|
+
}
|
|
46
80
|
//# sourceMappingURL=guards.js.map
|
package/dist/auth/guards.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"guards.js","sourceRoot":"","sources":["../../src/auth/guards.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"guards.js","sourceRoot":"","sources":["../../src/auth/guards.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAEvD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,qBAAqB,CAAC,OAAuB,EAAE,KAAmB;IAChF,IAAI,OAAO,CAAC,QAAQ;QAAE,OAAO,KAAK,CAAC;IACnC,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC;Q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AO,CAAC,QAAS,CAAC,IAAI,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACtD,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,4CAA4C,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC,CAAC;IACnG,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;oDAEoD;AACpD,MAAM,UAAU,aAAa,CAAC,OAAuB,EAAE,KAAmB,EAAE,IAAgB;IAC1F,IAAI,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC;QAAE,OAAO;IAC/C,IAAI,EAAE,CAAC;AACT,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,OAAuB;IAClD,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,CAAC;IAC9B,IAAI,IAAI,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC5B,MAAM,IAAI,KAAK,CACb,oFAAoF,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,IAAI,YAAY,CAAC,CAAC,CAAC,iBAAiB,wCAAwC,CAClL,CAAC;IACJ,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Sane default for EVERY flytedesk-id call this package makes (AK-20, gap 1 —
|
|
2
|
+
* generalized from AK-14 gap 5's `/token`-only timeout) — matches media-planner's
|
|
3
|
+
* `IDP_TOKEN_TIMEOUT_MS`, which `services/idpSession.ts` there sizes a DB transaction +
|
|
4
|
+
* advisory lock around specifically so it can never be held open while a flytedesk-id
|
|
5
|
+
* call is still in flight. Configurable via `OidcClientOptions.idpRequestTimeoutMs`
|
|
6
|
+
* (and `timeoutMs` on `@flytedesk/app-kit/auth/service`). */
|
|
7
|
+
export declare const DEFAULT_IDP_REQUEST_TIMEOUT_MS = 5000;
|
|
8
|
+
/**
|
|
9
|
+
* The ONE bounded-request helper every flytedesk-id call in this package goes through
|
|
10
|
+
* (AK-20, gap 1): `./oidc-client.ts`'s calls and `./service/index.ts`'s token exchange.
|
|
11
|
+
* Bounded by `AbortSignal.timeout`: a hung flytedesk-id response — most importantly the
|
|
12
|
+
* authorization lookup, which runs on every authenticated request via `./plugin.ts` —
|
|
13
|
+
* can never hold open whatever the caller wraps it in (for a consumer following
|
|
14
|
+
* media-planner's model, a Postgres transaction + advisory lock). A timeout throws the
|
|
15
|
+
* more specific `IdpTimeoutError`; any other network failure (DNS, refused connection,
|
|
16
|
+
* ...) is classified as `IdpUnavailableError` rather than propagating an unclassified
|
|
17
|
+
* error — both are typed, neither is swallowed. Deliberately does NOT inspect `res.ok`:
|
|
18
|
+
* a non-2xx response is still a normal, successfully-received `Response`, and each call
|
|
19
|
+
* site classifies it into its own message/error shape.
|
|
20
|
+
*
|
|
21
|
+
* `fetchImpl` defaults to the global `fetch`, looked up at call time.
|
|
22
|
+
*
|
|
23
|
+
* No imports beyond `./errors.js`: `@flytedesk/app-kit/auth/service` depends on this
|
|
24
|
+
* module and must never reach Fastify.
|
|
25
|
+
*/
|
|
26
|
+
export declare function idpFetch(url: string, init: RequestInit, label: string, timeoutMs: number, fetchImpl?: typeof fetch): Promise<Response>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { IdpTimeoutError, IdpUnavailableError } from "./errors.js";
|
|
2
|
+
/** Sane default for EVERY flytedesk-id call this package makes (AK-20, gap 1 —
|
|
3
|
+
* generalized from AK-14 gap 5's `/token`-only timeout) — matches media-planner's
|
|
4
|
+
* `IDP_TOKEN_TIMEOUT_MS`, which `services/idpSession.ts` there sizes a DB transaction +
|
|
5
|
+
* advisory lock around specifically so it can never be held open while a flytedesk-id
|
|
6
|
+
* call is still in flight. Configurable via `OidcClientOptions.idpRequestTimeoutMs`
|
|
7
|
+
* (and `timeoutMs` on `@flytedesk/app-kit/auth/service`). */
|
|
8
|
+
export const DEFAULT_IDP_REQUEST_TIMEOUT_MS = 5_000;
|
|
9
|
+
/**
|
|
10
|
+
* The ONE bounded-request helper every flytedesk-id call in this package goes through
|
|
11
|
+
* (AK-20, gap 1): `./oidc-client.ts`'s calls and `./service/index.ts`'s token exchange.
|
|
12
|
+
* Bounded by `AbortSignal.timeout`: a hung flytedesk-id response — most importantly the
|
|
13
|
+
* authorization lookup, which runs on every authenticated request via `./plugin.ts` —
|
|
14
|
+
* can never hold open whatever the caller wraps it in (for a consumer following
|
|
15
|
+
* media-planner's model, a Postgres transaction + advisory lock). A timeout throws the
|
|
16
|
+
* more specific `IdpTimeoutError`; any other network failure (DNS, refused connection,
|
|
17
|
+
* ...) is classified as `IdpUnavailableError` rather than propagating an unclassified
|
|
18
|
+
* error — both are typed, neither is swallowed. Deliberately does NOT inspect `res.ok`:
|
|
19
|
+
* a non-2xx response is still a normal, successfully-received `Response`, and each call
|
|
20
|
+
* site classifies it into its own message/error shape.
|
|
21
|
+
*
|
|
22
|
+
* `fetchImpl` defaults to the global `fetch`, looked up at call time.
|
|
23
|
+
*
|
|
24
|
+
* No imports beyond `./errors.js`: `@flytedesk/app-kit/auth/service` depends on this
|
|
25
|
+
* module and must never reach Fastify.
|
|
26
|
+
*/
|
|
27
|
+
export async function idpFetch(url, init, label, timeoutMs, fetchImpl = fetch) {
|
|
28
|
+
try {
|
|
29
|
+
return await fetchImpl(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
|
|
30
|
+
}
|
|
31
|
+
catch (err) {
|
|
32
|
+
if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
|
|
33
|
+
throw new IdpTimeoutError(`flytedesk-id ${label} did not respond within ${timeoutMs}ms`, err);
|
|
34
|
+
}
|
|
35
|
+
throw new IdpUnavailableError(`flytedesk-id ${label} request failed: ${err instanceof Error ? err.message : String(err)}`, err);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=idpFetch.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"idpFetch.js","sourceRoot":"","sources":["../../src/auth/idpFetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAEnE;;;;;8DAK8D;AAC9D,MAAM,CAAC,MAAM,8BAA8B,GAAG,KAAK,CAAC;AAEpD;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ,CAC5B,GAAW,EACX,IAAiB,EACjB,KAAa,EACb,SAAiB,EACjB,YAA0B,KAAK;IAE/B,IAAI,CAAC;QACH,OAAO,MAAM,SAAS,CAAC,GAAG,EAAE,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;IACnF,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,IAAI,GAAG,YAAY,KAAK,IAAI,CAAC,GAAG,CAAC,IAAI,KAAK,cAAc,IAAI,GAAG,CAAC,IAAI,KAAK,YAAY,CAAC,EAAE,CAAC;YACvF,MAAM,IAAI,eAAe,CAAC,gBAAgB,KAAK,2BAA2B,SAAS,IAAI,EAAE,GAAG,CAAC,CAAC;QAChG,CAAC;QACD,MAAM,IAAI,mBAAmB,CAC3B,gBAAgB,KAAK,oBAAoB,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,EAC3F,GAAG,CACJ,CAAC;IACJ,CAAC;AACH,CAAC"}
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -41,13 +41,19 @@
|
|
|
41
41
|
* });
|
|
42
42
|
*
|
|
43
43
|
* app.get("/me", { preHandler: requireAuth }, async (request) => request.authUser);
|
|
44
|
+
*
|
|
45
|
+
* `request.authUser` is a person (`kind: "person"`, a browser session) or a read-only
|
|
46
|
+
* flytedesk ID service principal (`kind: "service"`) — see `ServicePrincipalUser`,
|
|
47
|
+
* `readRoute` and `requirePerson`, and `@flytedesk/app-kit/auth/service` for the
|
|
48
|
+
* caller's side.
|
|
44
49
|
*/
|
|
45
|
-
export { requireAuth, requirePermission } from "./guards.js";
|
|
46
|
-
export
|
|
47
|
-
export type {
|
|
50
|
+
export { authedPerson, requireAuth, requirePermission, requirePerson } from "./guards.js";
|
|
51
|
+
export { readRoute } from "./readRoute.js";
|
|
52
|
+
export type { AuthedUser, AuthStore, CreateIdpSessionInput, CreateRefreshTokenInput, FlytedeskAuthOptions, IdpRole, IdpSessionLockedStore, IdpSessionRow, RefreshTokenRevocation, RefreshTokenRevocationReason, RefreshTokenRow, RevokeFamilyReason, ServicePrincipalUser, UpdateIdpSessionInput, UserinfoClaims, } from "./types.js";
|
|
53
|
+
export type { AppSwitcherEntry, IdpAuthorization, IdpServiceAuthorization, IdpTokenResponse, IdTokenClaims, OidcClient, OidcClientOptions, ServiceAccessTokenClaims, } from "./oidc-client.js";
|
|
48
54
|
export { createOidcClient, DEFAULT_OIDC_SCOPES, DEFAULT_IDP_REQUEST_TIMEOUT_MS } from "./oidc-client.js";
|
|
49
55
|
export type { ApiErrorBody, AuthUnavailableCode, SignInErrorCode, } from "./shared-types.js";
|
|
50
56
|
export { AUTH_REQUEST_DEADLINE_MS, AUTH_ROUTE_PREFIX, AUTH_ROUTE_SEGMENTS, AUTH_UNAVAILABLE_CODES, authRoutePath, SIGNIN_ERROR_QUERY_PARAM, SIGNIN_ERROR_CODES, type AuthRouteSegment, } from "./shared-types.js";
|
|
51
|
-
export { IdpError, IdpUnavailableError, IdpTimeoutError, IdpAccessRevokedError, AuthStoreError, OidcHttpError, OidcTokenError, classifyIdpError, } from "./errors.js";
|
|
57
|
+
export { IdpError, IdpUnavailableError, IdpTimeoutError, IdpAccessRevokedError, AuthStoreError, OidcHttpError, OidcTokenError, ServiceTokenRefusedError, classifyIdpError, } from "./errors.js";
|
|
52
58
|
export { generatePkce, randomState, type PkcePair } from "./pkce.js";
|
|
53
59
|
export { generateRefreshToken, hashRefreshToken, signAccessToken, verifyAccessToken, type AccessTokenClaims, } from "./tokens.js";
|
package/dist/auth/index.js
CHANGED
|
@@ -41,11 +41,17 @@
|
|
|
41
41
|
* });
|
|
42
42
|
*
|
|
43
43
|
* app.get("/me", { preHandler: requireAuth }, async (request) => request.authUser);
|
|
44
|
+
*
|
|
45
|
+
* `request.authUser` is a person (`kind: "person"`, a browser session) or a read-only
|
|
46
|
+
* flytedesk ID service principal (`kind: "service"`) — see `ServicePrincipalUser`,
|
|
47
|
+
* `readRoute` and `requirePerson`, and `@flytedesk/app-kit/auth/service` for the
|
|
48
|
+
* caller's side.
|
|
44
49
|
*/
|
|
45
|
-
export { requireAuth, requirePermission } from "./guards.js";
|
|
50
|
+
export { authedPerson, requireAuth, requirePermission, requirePerson } from "./guards.js";
|
|
51
|
+
export { readRoute } from "./readRoute.js";
|
|
46
52
|
export { createOidcClient, DEFAULT_OIDC_SCOPES, DEFAULT_IDP_REQUEST_TIMEOUT_MS } from "./oidc-client.js";
|
|
47
53
|
export { AUTH_REQUEST_DEADLINE_MS, AUTH_ROUTE_PREFIX, AUTH_ROUTE_SEGMENTS, AUTH_UNAVAILABLE_CODES, authRoutePath, SIGNIN_ERROR_QUERY_PARAM, SIGNIN_ERROR_CODES, } from "./shared-types.js";
|
|
48
|
-
export { IdpError, IdpUnavailableError, IdpTimeoutError, IdpAccessRevokedError, AuthStoreError, OidcHttpError, OidcTokenError, classifyIdpError, } from "./errors.js";
|
|
54
|
+
export { IdpError, IdpUnavailableError, IdpTimeoutError, IdpAccessRevokedError, AuthStoreError, OidcHttpError, OidcTokenError, ServiceTokenRefusedError, classifyIdpError, } from "./errors.js";
|
|
49
55
|
export { generatePkce, randomState } from "./pkce.js";
|
|
50
56
|
export { generateRefreshToken, hashRefreshToken, signAccessToken, verifyAccessToken, } from "./tokens.js";
|
|
51
57
|
//# sourceMappingURL=index.js.map
|
package/dist/auth/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDG;AACH,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC1F,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AA8B3C,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,8BAA8B,EAAE,MAAM,kBAAkB,CAAC;AAOzG,OAAO,EACL,wBAAwB,EACxB,iBAAiB,EACjB,mBAAmB,EACnB,sBAAsB,EACtB,aAAa,EACb,wBAAwB,EACxB,kBAAkB,GAEnB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,QAAQ,EACR,mBAAmB,EACnB,eAAe,EACf,qBAAqB,EACrB,cAAc,EACd,aAAa,EACb,cAAc,EACd,wBAAwB,EACxB,gBAAgB,GACjB,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,YAAY,EAAE,WAAW,EAAiB,MAAM,WAAW,CAAC;AAErE,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,eAAe,EACf,iBAAiB,GAElB,MAAM,aAAa,CAAC"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { DEFAULT_IDP_REQUEST_TIMEOUT_MS } from "./idpFetch.js";
|
|
2
|
+
import type { AppSwitcherEntry, IdpRole } from "./shared-types.js";
|
|
2
3
|
import type { UserinfoClaims } from "./types.js";
|
|
3
4
|
/**
|
|
4
5
|
* Requested by default (AK-14, gap 1): without `offline_access`, flytedesk-id's
|
|
@@ -10,12 +11,7 @@ import type { UserinfoClaims } from "./types.js";
|
|
|
10
11
|
* narrower grant can override via `FlytedeskAuthOptions.scopes`/`OidcClientOptions.scopes`.
|
|
11
12
|
*/
|
|
12
13
|
export declare const DEFAULT_OIDC_SCOPES: readonly ["openid", "email", "profile", "offline_access"];
|
|
13
|
-
|
|
14
|
-
* generalized from AK-14 gap 5's `/token`-only timeout) — matches media-planner's
|
|
15
|
-
* `IDP_TOKEN_TIMEOUT_MS`, which `services/idpSession.ts` there sizes a DB transaction +
|
|
16
|
-
* advisory lock around specifically so it can never be held open while a flytedesk-id
|
|
17
|
-
* call is still in flight. Configurable via `OidcClientOptions.idpRequestTimeoutMs`. */
|
|
18
|
-
export declare const DEFAULT_IDP_REQUEST_TIMEOUT_MS = 5000;
|
|
14
|
+
export { DEFAULT_IDP_REQUEST_TIMEOUT_MS };
|
|
19
15
|
export interface OidcClientOptions {
|
|
20
16
|
issuer: string;
|
|
21
17
|
clientId: string;
|
|
@@ -60,6 +56,22 @@ export interface IdpAuthorization {
|
|
|
60
56
|
}>;
|
|
61
57
|
permissions: string[];
|
|
62
58
|
}
|
|
59
|
+
/** `GET {issuer}/apps/{appId}/authorization`'s answer for a service access token. */
|
|
60
|
+
export interface IdpServiceAuthorization {
|
|
61
|
+
kind: "service";
|
|
62
|
+
principalId: string;
|
|
63
|
+
name: string;
|
|
64
|
+
appId: string;
|
|
65
|
+
roles: IdpRole[];
|
|
66
|
+
/** App-prefixed (`${appId}:...`), as for a person. */
|
|
67
|
+
permissions: string[];
|
|
68
|
+
}
|
|
69
|
+
/** A service access token's claims, once its signature and every required claim check
|
|
70
|
+
* out (`OidcClient.verifyServiceAccessToken`). */
|
|
71
|
+
export interface ServiceAccessTokenClaims {
|
|
72
|
+
/** The service principal's flytedesk ID id. */
|
|
73
|
+
sub: string;
|
|
74
|
+
}
|
|
63
75
|
export type { AppSwitcherEntry };
|
|
64
76
|
export interface OidcClient {
|
|
65
77
|
/** `prompt` is passed straight through to flytedesk-id's `/auth` endpoint (OIDC Core
|
|
@@ -90,6 +102,22 @@ export interface OidcClient {
|
|
|
90
102
|
verifyIdToken(idToken: string): Promise<IdTokenClaims>;
|
|
91
103
|
fetchUserinfo(idpAccessToken: string): Promise<UserinfoClaims>;
|
|
92
104
|
fetchAuthorization(idpAccessToken: string, appId: string): Promise<IdpAuthorization>;
|
|
105
|
+
/**
|
|
106
|
+
* Verifies a flytedesk ID service access token locally against flytedesk ID's JWKS:
|
|
107
|
+
* RS256, header `typ: at+jwt`, `iss` = the issuer, `aud` = `appId`, an unexpired `exp`,
|
|
108
|
+
* a `sub`, and `fd_kind: service`. Throws `IdpUnavailableError` when the JWKS cannot be
|
|
109
|
+
* fetched (flytedesk ID down: no verdict); anything else it throws means the token is
|
|
110
|
+
* refused.
|
|
111
|
+
*/
|
|
112
|
+
verifyServiceAccessToken(token: string, appId: string): Promise<ServiceAccessTokenClaims>;
|
|
113
|
+
/**
|
|
114
|
+
* `GET {issuer}/apps/{appId}/authorization` with a service access token — live, like
|
|
115
|
+
* `fetchAuthorization`. flytedesk ID must answer it as the service principal
|
|
116
|
+
* `principalId` (`kind: "service"`); any other answer throws `IdpAccessRevokedError`.
|
|
117
|
+
* A non-2xx answer throws `OidcHttpError` (classify it with `classifyIdpError`), and an
|
|
118
|
+
* unusable body throws `IdpUnavailableError`.
|
|
119
|
+
*/
|
|
120
|
+
fetchServiceAuthorization(serviceAccessToken: string, appId: string, principalId: string): Promise<IdpServiceAuthorization>;
|
|
93
121
|
/** `GET {issuer}/me/apps` — every app the caller holds any role in, for feeding the
|
|
94
122
|
* design system's "All flytedesk apps" switcher. Computed live by flytedesk-id on
|
|
95
123
|
* every call (never cached there — see fetchAuthorization's doc comment, same
|
package/dist/auth/oidc-client.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
2
|
-
import {
|
|
1
|
+
import { createRemoteJWKSet, errors as joseErrors, jwtVerify } from "jose";
|
|
2
|
+
import { IdpAccessRevokedError, IdpUnavailableError, OidcHttpError, OidcTokenError } from "./errors.js";
|
|
3
|
+
import { DEFAULT_IDP_REQUEST_TIMEOUT_MS, idpFetch as boundedIdpFetch } from "./idpFetch.js";
|
|
4
|
+
import { SERVICE_ACCESS_TOKEN_ALG, SERVICE_ACCESS_TOKEN_TYP, SERVICE_TOKEN_KIND, SERVICE_TOKEN_KIND_CLAIM, } from "./serviceTokenContract.js";
|
|
3
5
|
/**
|
|
4
6
|
* Requested by default (AK-14, gap 1): without `offline_access`, flytedesk-id's
|
|
5
7
|
* oidc-provider never issues a refresh token, and every session dies the moment its
|
|
@@ -10,12 +12,7 @@ import { IdpTimeoutError, IdpUnavailableError, OidcHttpError, OidcTokenError } f
|
|
|
10
12
|
* narrower grant can override via `FlytedeskAuthOptions.scopes`/`OidcClientOptions.scopes`.
|
|
11
13
|
*/
|
|
12
14
|
export const DEFAULT_OIDC_SCOPES = ["openid", "email", "profile", "offline_access"];
|
|
13
|
-
|
|
14
|
-
* generalized from AK-14 gap 5's `/token`-only timeout) — matches media-planner's
|
|
15
|
-
* `IDP_TOKEN_TIMEOUT_MS`, which `services/idpSession.ts` there sizes a DB transaction +
|
|
16
|
-
* advisory lock around specifically so it can never be held open while a flytedesk-id
|
|
17
|
-
* call is still in flight. Configurable via `OidcClientOptions.idpRequestTimeoutMs`. */
|
|
18
|
-
export const DEFAULT_IDP_REQUEST_TIMEOUT_MS = 5_000;
|
|
15
|
+
export { DEFAULT_IDP_REQUEST_TIMEOUT_MS };
|
|
19
16
|
/**
|
|
20
17
|
* One instance per FlytedeskAuthOptions (i.e. per plugin registration), not a module
|
|
21
18
|
* singleton — keeps the JWKS/discovery caches below scoped to one issuer/client pair
|
|
@@ -40,31 +37,12 @@ export function createOidcClient(opts) {
|
|
|
40
37
|
return "Basic " + Buffer.from(`${clientId}:${clientSecret}`).toString("base64");
|
|
41
38
|
}
|
|
42
39
|
const idpRequestTimeoutMs = opts.idpRequestTimeoutMs ?? DEFAULT_IDP_REQUEST_TIMEOUT_MS;
|
|
43
|
-
/**
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
* which runs on every authenticated request via `../plugin.ts`'s `loadAuthedUser` —
|
|
50
|
-
* could hold open whatever the caller wraps it in (for a consumer following
|
|
51
|
-
* media-planner's model, a Postgres transaction + advisory lock). A timeout throws the
|
|
52
|
-
* more specific `IdpTimeoutError`; any other network failure (DNS, refused connection,
|
|
53
|
-
* ...) is classified as `IdpUnavailableError` rather than propagating an unclassified
|
|
54
|
-
* error — both are typed, neither is swallowed. Deliberately does NOT inspect
|
|
55
|
-
* `res.ok`: a non-2xx response is still a normal, successfully-received `Response`,
|
|
56
|
-
* and each call site classifies it into its own message/error shape.
|
|
57
|
-
*/
|
|
58
|
-
async function idpFetch(url, init, label) {
|
|
59
|
-
try {
|
|
60
|
-
return await fetch(url, { ...init, signal: AbortSignal.timeout(idpRequestTimeoutMs) });
|
|
61
|
-
}
|
|
62
|
-
catch (err) {
|
|
63
|
-
if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
|
|
64
|
-
throw new IdpTimeoutError(`flytedesk-id ${label} did not respond within ${idpRequestTimeoutMs}ms`, err);
|
|
65
|
-
}
|
|
66
|
-
throw new IdpUnavailableError(`flytedesk-id ${label} request failed: ${err instanceof Error ? err.message : String(err)}`, err);
|
|
67
|
-
}
|
|
40
|
+
/** Every flytedesk-id call in this client — `tokenRequest` below, `fetchUserinfo`,
|
|
41
|
+
* the authorization lookups, `fetchMyApps`, `getDiscovery` and `revokeIdpToken`'s own
|
|
42
|
+
* POST — goes through the shared bounded helper (`./idpFetch.ts`), never `fetch`
|
|
43
|
+
* directly, so each one fails with a typed error within `idpRequestTimeoutMs`. */
|
|
44
|
+
function idpFetch(url, init, label) {
|
|
45
|
+
return boundedIdpFetch(url, init, label, idpRequestTimeoutMs);
|
|
68
46
|
}
|
|
69
47
|
/** The RFC 6749 §5.2 `error` code of a /token error body, when it has one. */
|
|
70
48
|
function oauthErrorCode(body) {
|
|
@@ -96,6 +74,32 @@ export function createOidcClient(opts) {
|
|
|
96
74
|
jwks ??= createRemoteJWKSet(new URL(issuerUrl("/jwks")));
|
|
97
75
|
return jwks;
|
|
98
76
|
}
|
|
77
|
+
/**
|
|
78
|
+
* The JWKS key lookup for service access tokens: `getJwks()`, with a failure to
|
|
79
|
+
* FETCH the key set (flytedesk ID down, a timeout, a non-200 or unparseable answer)
|
|
80
|
+
* raised as `IdpUnavailableError`, so an outage is never mistaken for a refused token.
|
|
81
|
+
* A key set that was fetched but has no (or more than one) key for the token's header
|
|
82
|
+
* is a verdict about the token and passes through as jose raised it.
|
|
83
|
+
*/
|
|
84
|
+
const serviceTokenKey = async (header, token) => {
|
|
85
|
+
try {
|
|
86
|
+
return await getJwks()(header, token);
|
|
87
|
+
}
|
|
88
|
+
catch (err) {
|
|
89
|
+
if (err instanceof joseErrors.JWKSNoMatchingKey || err instanceof joseErrors.JWKSMultipleMatchingKeys) {
|
|
90
|
+
throw err;
|
|
91
|
+
}
|
|
92
|
+
throw new IdpUnavailableError(`flytedesk-id JWKS could not be fetched: ${err instanceof Error ? err.message : String(err)}`, err);
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
/** `GET {issuer}/apps/{appId}/authorization`'s JSON body, for either kind of bearer. */
|
|
96
|
+
async function authorizationRequest(bearer, appId) {
|
|
97
|
+
const res = await idpFetch(issuerUrl(`/apps/${appId}/authorization`), { headers: { Authorization: `Bearer ${bearer}` } }, "authorization endpoint");
|
|
98
|
+
if (!res.ok) {
|
|
99
|
+
throw new OidcHttpError(`flytedesk-id authorization endpoint returned ${res.status}`, res.status);
|
|
100
|
+
}
|
|
101
|
+
return res.json();
|
|
102
|
+
}
|
|
99
103
|
/** The discovery document, fetched once and cached — but only once it has actually
|
|
100
104
|
* been read: a failed fetch (flytedesk-id down, a timeout) is forgotten, so the next
|
|
101
105
|
* call tries again instead of every later caller inheriting that one failure until
|
|
@@ -198,11 +202,39 @@ export function createOidcClient(opts) {
|
|
|
198
202
|
* by calling this live rather than memoizing the result — see FlytedeskAuthOptions
|
|
199
203
|
* authorizationCacheTtlMs's doc comment for the one sanctioned exception. */
|
|
200
204
|
async fetchAuthorization(idpAccessToken, appId) {
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
205
|
+
return (await authorizationRequest(idpAccessToken, appId));
|
|
206
|
+
},
|
|
207
|
+
async verifyServiceAccessToken(token, appId) {
|
|
208
|
+
const { payload } = await jwtVerify(token, serviceTokenKey, {
|
|
209
|
+
issuer: opts.issuer,
|
|
210
|
+
audience: appId,
|
|
211
|
+
typ: SERVICE_ACCESS_TOKEN_TYP,
|
|
212
|
+
algorithms: [SERVICE_ACCESS_TOKEN_ALG],
|
|
213
|
+
requiredClaims: ["exp", "sub", SERVICE_TOKEN_KIND_CLAIM],
|
|
214
|
+
});
|
|
215
|
+
if (payload[SERVICE_TOKEN_KIND_CLAIM] !== SERVICE_TOKEN_KIND) {
|
|
216
|
+
throw new Error(`flytedesk-id access token is not a service token (${SERVICE_TOKEN_KIND_CLAIM} is not "${SERVICE_TOKEN_KIND}")`);
|
|
217
|
+
}
|
|
218
|
+
if (typeof payload.sub !== "string" || payload.sub.length === 0) {
|
|
219
|
+
throw new Error("flytedesk-id service access token has no usable sub claim");
|
|
220
|
+
}
|
|
221
|
+
return { sub: payload.sub };
|
|
222
|
+
},
|
|
223
|
+
async fetchServiceAuthorization(serviceAccessToken, appId, principalId) {
|
|
224
|
+
const body = await authorizationRequest(serviceAccessToken, appId);
|
|
225
|
+
const answer = (typeof body === "object" && body !== null ? body : {});
|
|
226
|
+
if (answer.kind !== SERVICE_TOKEN_KIND || answer.principalId !== principalId) {
|
|
227
|
+
throw new IdpAccessRevokedError(`flytedesk-id did not authorize this token as service principal "${principalId}" ` +
|
|
228
|
+
`(answered kind ${JSON.stringify(answer.kind)}, principalId ${JSON.stringify(answer.principalId)})`);
|
|
229
|
+
}
|
|
230
|
+
if (typeof answer.name !== "string" ||
|
|
231
|
+
typeof answer.appId !== "string" ||
|
|
232
|
+
!Array.isArray(answer.roles) ||
|
|
233
|
+
!Array.isArray(answer.permissions) ||
|
|
234
|
+
!answer.permissions.every((p) => typeof p === "string")) {
|
|
235
|
+
throw new IdpUnavailableError("flytedesk-id answered an unusable service authorization (name, appId, roles or permissions)");
|
|
204
236
|
}
|
|
205
|
-
return
|
|
237
|
+
return answer;
|
|
206
238
|
},
|
|
207
239
|
/** `GET {issuer}/me/apps` — see fetchMyApps's doc comment on OidcClient above. */
|
|
208
240
|
async fetchMyApps(idpAccessToken) {
|