@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.
Files changed (44) hide show
  1. package/README.md +121 -2
  2. package/dist/auth/errors.d.ts +20 -0
  3. package/dist/auth/errors.js +24 -0
  4. package/dist/auth/errors.js.map +1 -1
  5. package/dist/auth/guards.d.ts +18 -0
  6. package/dist/auth/guards.js +34 -0
  7. package/dist/auth/guards.js.map +1 -1
  8. package/dist/auth/idpFetch.d.ts +26 -0
  9. package/dist/auth/idpFetch.js +38 -0
  10. package/dist/auth/idpFetch.js.map +1 -0
  11. package/dist/auth/index.d.ts +10 -4
  12. package/dist/auth/index.js +8 -2
  13. package/dist/auth/index.js.map +1 -1
  14. package/dist/auth/oidc-client.d.ts +35 -7
  15. package/dist/auth/oidc-client.js +69 -37
  16. package/dist/auth/oidc-client.js.map +1 -1
  17. package/dist/auth/plugin.d.ts +5 -0
  18. package/dist/auth/plugin.js +158 -56
  19. package/dist/auth/plugin.js.map +1 -1
  20. package/dist/auth/readRoute.d.ts +20 -0
  21. package/dist/auth/readRoute.js +20 -0
  22. package/dist/auth/readRoute.js.map +1 -0
  23. package/dist/auth/service/index.d.ts +61 -0
  24. package/dist/auth/service/index.js +145 -0
  25. package/dist/auth/service/index.js.map +1 -0
  26. package/dist/auth/serviceTokenContract.d.ts +33 -0
  27. package/dist/auth/serviceTokenContract.js +40 -0
  28. package/dist/auth/serviceTokenContract.js.map +1 -0
  29. package/dist/auth/shared-types.d.ts +6 -3
  30. package/dist/auth/shared-types.js.map +1 -1
  31. package/dist/auth/testing/fake-idp.d.ts +97 -1
  32. package/dist/auth/testing/fake-idp.js +179 -1
  33. package/dist/auth/testing/fake-idp.js.map +1 -1
  34. package/dist/auth/testing/index.d.ts +1 -1
  35. package/dist/auth/testing/index.js +1 -1
  36. package/dist/auth/testing/index.js.map +1 -1
  37. package/dist/auth/types.d.ts +29 -5
  38. package/dist/bigquery/load.d.ts +1 -1
  39. package/dist/bigquery/load.js +4 -4
  40. package/dist/bigquery/query.js +58 -15
  41. package/dist/bigquery/query.js.map +1 -1
  42. package/dist/profile/plugin.js +11 -7
  43. package/dist/profile/plugin.js.map +1 -1
  44. package/package.json +5 -1
@@ -0,0 +1,145 @@
1
+ /**
2
+ * `@flytedesk/app-kit/auth/service` — the CALLER's side of a flytedesk ID service
3
+ * identity: an unattended Node process (a profiler, a job) getting a short-lived,
4
+ * read-only flytedesk ID service access token to call a flytedesk app's API as its
5
+ * service principal.
6
+ *
7
+ * No secret is stored anywhere. The caller proves who it is with a Google ID token
8
+ * (a Google service account's identity, e.g. from `gcloud auth print-identity-token
9
+ * --audiences=<serviceTokenAudience(issuer)>` or the metadata server — getting it is
10
+ * the caller's job), and flytedesk ID exchanges it (RFC 8693, `POST
11
+ * {issuer}/service-token`) for a 10-minute access token for one app. The app accepts
12
+ * it as `request.authUser.kind === "service"`, read-only (see the README's "Service
13
+ * principals").
14
+ *
15
+ * import { createServiceTokenSource } from "@flytedesk/app-kit/auth/service";
16
+ *
17
+ * const tokens = createServiceTokenSource({
18
+ * issuer: "https://id.flytedesk.com",
19
+ * appId: "sms-app",
20
+ * idToken: (audience) => googleIdTokenFor(audience),
21
+ * });
22
+ * await fetch(url, { headers: { Authorization: `Bearer ${await tokens.accessToken()}` } });
23
+ *
24
+ * Node-only, and never imports Fastify: a caller that is not a Fastify app gets none of
25
+ * the plugin's request augmentation in its program.
26
+ */
27
+ import { decodeJwt } from "jose";
28
+ import { IdpUnavailableError, ServiceTokenRefusedError } from "../errors.js";
29
+ import { DEFAULT_IDP_REQUEST_TIMEOUT_MS, idpFetch } from "../idpFetch.js";
30
+ import { ID_TOKEN_TYPE, SERVICE_TOKEN_PATH, TOKEN_EXCHANGE_GRANT_TYPE } from "../serviceTokenContract.js";
31
+ export { IdpError, IdpTimeoutError, IdpUnavailableError, ServiceTokenRefusedError } from "../errors.js";
32
+ /** How long before its `exp` a cached service access token is replaced. */
33
+ export const DEFAULT_SERVICE_TOKEN_REFRESH_SKEW_MS = 60_000;
34
+ /**
35
+ * The `aud` the Google ID token must carry, which is also the exchange endpoint:
36
+ * `{issuer}/service-token`. Throws for an issuer ending in `/` — flytedesk ID compares
37
+ * this string exactly, and the plugin compares the issued token's `iss` exactly.
38
+ */
39
+ export function serviceTokenAudience(issuer) {
40
+ if (issuer.length === 0 || issuer.endsWith("/")) {
41
+ throw new Error(`@flytedesk/app-kit/auth/service: issuer must be flytedesk ID's issuer URL with no trailing slash, got ${JSON.stringify(issuer)}`);
42
+ }
43
+ return `${issuer}${SERVICE_TOKEN_PATH}`;
44
+ }
45
+ /** An OAuth error body's `error` and `error_description`, when it has them. */
46
+ function oauthErrorOf(body) {
47
+ try {
48
+ const parsed = JSON.parse(body);
49
+ return {
50
+ error: typeof parsed.error === "string" ? parsed.error : undefined,
51
+ description: typeof parsed.error_description === "string" ? parsed.error_description : undefined,
52
+ };
53
+ }
54
+ catch {
55
+ return { error: undefined, description: undefined };
56
+ }
57
+ }
58
+ /**
59
+ * Exchanges a Google ID token for a flytedesk ID service access token for `appId`.
60
+ * Throws:
61
+ * - `ServiceTokenRefusedError` — flytedesk ID answered 4xx: the caller or its
62
+ * registration is refused (`oauthError` says why). Retrying will not help.
63
+ * - `IdpTimeoutError` — no answer within `timeoutMs`.
64
+ * - `IdpUnavailableError` — flytedesk ID unreachable, a 5xx, or an answer without a
65
+ * usable `access_token` (a JWT with an `exp`). Safe to retry later.
66
+ */
67
+ export async function exchangeServiceToken(options) {
68
+ const res = await idpFetch(serviceTokenAudience(options.issuer), {
69
+ method: "POST",
70
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
71
+ body: new URLSearchParams({
72
+ grant_type: TOKEN_EXCHANGE_GRANT_TYPE,
73
+ subject_token: options.subjectToken,
74
+ subject_token_type: ID_TOKEN_TYPE,
75
+ audience: options.appId,
76
+ }).toString(),
77
+ }, SERVICE_TOKEN_PATH, options.timeoutMs ?? DEFAULT_IDP_REQUEST_TIMEOUT_MS, options.fetch);
78
+ const text = await res.text().catch(() => "");
79
+ if (res.status >= 400 && res.status < 500) {
80
+ const { error, description } = oauthErrorOf(text);
81
+ throw new ServiceTokenRefusedError(`flytedesk-id refused the service-token exchange for "${options.appId}" (${res.status}${error ? ` ${error}` : ""})` +
82
+ (description ? `: ${description}` : ""), res.status, error, description);
83
+ }
84
+ if (!res.ok) {
85
+ throw new IdpUnavailableError(`flytedesk-id ${SERVICE_TOKEN_PATH} returned ${res.status}`);
86
+ }
87
+ let accessToken;
88
+ try {
89
+ accessToken = JSON.parse(text).access_token;
90
+ }
91
+ catch (err) {
92
+ throw new IdpUnavailableError(`flytedesk-id ${SERVICE_TOKEN_PATH} answered a body that is not JSON`, err);
93
+ }
94
+ if (typeof accessToken !== "string" || accessToken.length === 0) {
95
+ throw new IdpUnavailableError(`flytedesk-id ${SERVICE_TOKEN_PATH} answered without an access_token`);
96
+ }
97
+ let exp;
98
+ try {
99
+ exp = decodeJwt(accessToken).exp;
100
+ }
101
+ catch (err) {
102
+ throw new IdpUnavailableError(`flytedesk-id ${SERVICE_TOKEN_PATH} answered an access_token that is not a JWT`, err);
103
+ }
104
+ if (typeof exp !== "number" || !Number.isFinite(exp)) {
105
+ throw new IdpUnavailableError(`flytedesk-id ${SERVICE_TOKEN_PATH} answered an access_token without an exp`);
106
+ }
107
+ return { accessToken, expiresAt: new Date(exp * 1000) };
108
+ }
109
+ /** A cached, self-refreshing source of service access tokens — see `ServiceTokenSource`. */
110
+ export function createServiceTokenSource(options) {
111
+ const audience = serviceTokenAudience(options.issuer);
112
+ if (options.appId.length === 0) {
113
+ throw new Error("@flytedesk/app-kit/auth/service: appId is required");
114
+ }
115
+ const refreshSkewMs = options.refreshSkewMs ?? DEFAULT_SERVICE_TOKEN_REFRESH_SKEW_MS;
116
+ if (!Number.isFinite(refreshSkewMs) || refreshSkewMs < 0) {
117
+ throw new Error(`@flytedesk/app-kit/auth/service: refreshSkewMs must be a non-negative number, got ${refreshSkewMs}`);
118
+ }
119
+ const clock = options.clock ?? Date.now;
120
+ let cached;
121
+ let inFlight;
122
+ async function exchange() {
123
+ const subjectToken = await options.idToken(audience);
124
+ cached = await exchangeServiceToken({
125
+ issuer: options.issuer,
126
+ appId: options.appId,
127
+ subjectToken,
128
+ fetch: options.fetch,
129
+ timeoutMs: options.timeoutMs,
130
+ });
131
+ return cached.accessToken;
132
+ }
133
+ return {
134
+ accessToken() {
135
+ if (cached && clock() < cached.expiresAt.getTime() - refreshSkewMs) {
136
+ return Promise.resolve(cached.accessToken);
137
+ }
138
+ inFlight ??= exchange().finally(() => {
139
+ inFlight = undefined;
140
+ });
141
+ return inFlight;
142
+ },
143
+ };
144
+ }
145
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/auth/service/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC;AAC7E,OAAO,EAAE,8BAA8B,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AAE1G,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC;AAExG,2EAA2E;AAC3E,MAAM,CAAC,MAAM,qCAAqC,GAAG,MAAM,CAAC;AA8C5D;;;;GAIG;AACH,MAAM,UAAU,oBAAoB,CAAC,MAAc;IACjD,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QAChD,MAAM,IAAI,KAAK,CACb,yGAAyG,IAAI,CAAC,SAA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AE,OAAO,CAAC,KAAK;YACpB,SAAS,EAAE,OAAO,CAAC,SAAS;SAC7B,CAAC,CAAC;QACH,OAAO,MAAM,CAAC,WAAW,CAAC;IAC5B,CAAC;IAED,OAAO;QACL,WAAW;YACT,IAAI,MAAM,IAAI,KAAK,EAAE,GAAG,MAAM,CAAC,SAAS,CAAC,OAAO,EAAE,GAAG,aAAa,EAAE,CAAC;gBACnE,OAAO,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;YAC7C,CAAC;YACD,QAAQ,KAAK,QAAQ,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE;gBACnC,QAAQ,GAAG,SAAS,CAAC;YACvB,CAAC,CAAC,CAAC;YACH,OAAO,QAAQ,CAAC;QAClB,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The wire contract of a flytedesk ID service identity, in one place: what the token
3
+ * exchange (`POST {issuer}/service-token`, RFC 8693) takes, and what the access token
4
+ * it issues (an RFC 9068 JWT) carries. The plugin (`./plugin.ts`, accepting a token),
5
+ * the OIDC client (`./oidc-client.ts`, verifying it), the service client
6
+ * (`./service/index.ts`, getting one) and the fake IdP (`./testing/fake-idp.ts`,
7
+ * issuing one) all read these names from here, so the four can never drift apart.
8
+ *
9
+ * No runtime imports: `@flytedesk/app-kit/auth/service` depends on this module and must
10
+ * never pull Fastify (or its request augmentation) into a caller's program.
11
+ */
12
+ /** The exchange endpoint's path under the issuer. */
13
+ export declare const SERVICE_TOKEN_PATH = "/service-token";
14
+ /** RFC 8693 §2.1 `grant_type` for a token exchange. */
15
+ export declare const TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange";
16
+ /** RFC 8693 §3 token type of the `subject_token`: a Google ID token. */
17
+ export declare const ID_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:id_token";
18
+ /** RFC 8693 §3 token type of the issued token. */
19
+ export declare const ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
20
+ /** RFC 9068 §2.1 `typ` header of a JWT access token. */
21
+ export declare const SERVICE_ACCESS_TOKEN_TYP = "at+jwt";
22
+ /** The claim flytedesk ID sets to {@link SERVICE_TOKEN_KIND} on every service access token. */
23
+ export declare const SERVICE_TOKEN_KIND_CLAIM = "fd_kind";
24
+ export declare const SERVICE_TOKEN_KIND = "service";
25
+ /** The algorithm flytedesk ID signs service access tokens with (its provider key). */
26
+ export declare const SERVICE_ACCESS_TOKEN_ALG = "RS256";
27
+ /**
28
+ * Whether a JWT protected header's `typ` names a JWT access token. Compared the way
29
+ * jose's own `typ` check compares it (RFC 7515 §4.1.9: case-insensitive, and
30
+ * `application/` may be omitted), so this classification and the verification that
31
+ * follows it agree on every header.
32
+ */
33
+ export declare function isServiceAccessTokenTyp(typ: unknown): boolean;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The wire contract of a flytedesk ID service identity, in one place: what the token
3
+ * exchange (`POST {issuer}/service-token`, RFC 8693) takes, and what the access token
4
+ * it issues (an RFC 9068 JWT) carries. The plugin (`./plugin.ts`, accepting a token),
5
+ * the OIDC client (`./oidc-client.ts`, verifying it), the service client
6
+ * (`./service/index.ts`, getting one) and the fake IdP (`./testing/fake-idp.ts`,
7
+ * issuing one) all read these names from here, so the four can never drift apart.
8
+ *
9
+ * No runtime imports: `@flytedesk/app-kit/auth/service` depends on this module and must
10
+ * never pull Fastify (or its request augmentation) into a caller's program.
11
+ */
12
+ /** The exchange endpoint's path under the issuer. */
13
+ export const SERVICE_TOKEN_PATH = "/service-token";
14
+ /** RFC 8693 §2.1 `grant_type` for a token exchange. */
15
+ export const TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange";
16
+ /** RFC 8693 §3 token type of the `subject_token`: a Google ID token. */
17
+ export const ID_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:id_token";
18
+ /** RFC 8693 §3 token type of the issued token. */
19
+ export const ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
20
+ /** RFC 9068 §2.1 `typ` header of a JWT access token. */
21
+ export const SERVICE_ACCESS_TOKEN_TYP = "at+jwt";
22
+ /** The claim flytedesk ID sets to {@link SERVICE_TOKEN_KIND} on every service access token. */
23
+ export const SERVICE_TOKEN_KIND_CLAIM = "fd_kind";
24
+ export const SERVICE_TOKEN_KIND = "service";
25
+ /** The algorithm flytedesk ID signs service access tokens with (its provider key). */
26
+ export const SERVICE_ACCESS_TOKEN_ALG = "RS256";
27
+ /**
28
+ * Whether a JWT protected header's `typ` names a JWT access token. Compared the way
29
+ * jose's own `typ` check compares it (RFC 7515 §4.1.9: case-insensitive, and
30
+ * `application/` may be omitted), so this classification and the verification that
31
+ * follows it agree on every header.
32
+ */
33
+ export function isServiceAccessTokenTyp(typ) {
34
+ return typeof typ === "string" && normalizeTyp(typ) === normalizeTyp(SERVICE_ACCESS_TOKEN_TYP);
35
+ }
36
+ function normalizeTyp(typ) {
37
+ const lower = typ.toLowerCase();
38
+ return lower.includes("/") ? lower : `application/${lower}`;
39
+ }
40
+ //# sourceMappingURL=serviceTokenContract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serviceTokenContract.js","sourceRoot":"","sources":["../../src/auth/serviceTokenContract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,qDAAqD;AACrD,MAAM,CAAC,MAAM,kBAAkB,GAAG,gBAAgB,CAAC;AAEnD,uDAAuD;AACvD,MAAM,CAAC,MAAM,yBAAyB,GAAG,iDAAiD,CAAC;AAE3F,wEAAwE;AACxE,MAAM,CAAC,MAAM,aAAa,GAAG,2CAA2C,CAAC;AAEzE,kDAAkD;AAClD,MAAM,CAAC,MAAM,iBAAiB,GAAG,+CAA+C,CAAC;AAEjF,wDAAwD;AACxD,MAAM,CAAC,MAAM,wBAAwB,GAAG,QAAQ,CAAC;AAEjD,+FAA+F;AAC/F,MAAM,CAAC,MAAM,wBAAwB,GAAG,SAAS,CAAC;AAElD,MAAM,CAAC,MAAM,kBAAkB,GAAG,SAAS,CAAC;AAE5C,sFAAsF;AACtF,MAAM,CAAC,MAAM,wBAAwB,GAAG,OAAO,CAAC;AAEhD;;;;;GAKG;AACH,MAAM,UAAU,uBAAuB,CAAC,GAAY;IAClD,OAAO,OAAO,GAAG,KAAK,QAAQ,IAAI,YAAY,CAAC,GAAG,CAAC,KAAK,YAAY,CAAC,wBAAwB,CAAC,CAAC;AACjG,CAAC;AAED,SAAS,YAAY,CAAC,GAAW;IAC/B,MAAM,KAAK,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;IAChC,OAAO,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,eAAe,KAAK,EAAE,CAAC;AAC9D,CAAC"}
@@ -12,12 +12,15 @@ export interface IdpRole {
12
12
  key: string;
13
13
  name: string;
14
14
  }
15
- /** The shape of `request.authUser` (server) / `GET {api}{routePrefix}/me`'s `user`
16
- * (browser) —
15
+ /** A signed-in person: `request.authUser` (server) for a browser session, and `GET
16
+ * {api}{routePrefix}/me`'s `user` (browser) —
17
17
  * one definition, so a consuming app's browser code never hand-declares a copy that
18
18
  * can drift from what the server plugin actually attaches (see AK-16 AC 2247: SMS-5's
19
- * useAuthSession.ts redeclared this by hand before this type existed). */
19
+ * useAuthSession.ts redeclared this by hand before this type existed). The server's
20
+ * `AuthedUser` is this or a service principal (`ServicePrincipalUser`, ./types.ts);
21
+ * `kind` tells them apart. */
20
22
  export interface AuthedUserDto {
23
+ kind: "person";
21
24
  id: string;
22
25
  email: string;
23
26
  name: string;
@@ -1 +1 @@
1
- {"version":3,"file":"shared-types.js","sourceRoot":"","sources":["../../src/auth/shared-types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AA+CH;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,OAAO,CAAC;AAEzC;;;;;;;;GAQG;AACH,MAAM,C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,wBAAwB,GAAG,cAAc,CAAC;AAEvD;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,SAAS,EAAE,WAAW,EAAE,OAAO,CAAU,CAAC;AAI7E;;uBAEuB;AACvB,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC,KAAK,EAAE,OAAO;IACd,QAAQ,EAAE,UAAU;IACpB,OAAO,EAAE,SAAS;IAClB,MAAM,EAAE,QAAQ;IAChB,EAAE,EAAE,IAAI;IACR,IAAI,EAAE,MAAM;CAC6B,CAAC;AAI5C;;;qBAGqB;AACrB,MAAM,UAAU,aAAa,CAAC,MAAc,EAAE,OAAyB;IACrE,OAAO,GAAG,MAAM,IAAI,mBAAmB,CAAC,OAAO,CAAC,EAAE,CAAC;AACrD,CAAC"}
@@ -8,7 +8,14 @@ import type { AppSwitcherEntry } from "../oidc-client.js";
8
8
  * S256, Basic client auth), `/me` (userinfo), `/apps/:appId/authorization` (roles +
9
9
  * permissions), `/me/apps` (the "All flytedesk apps" switcher feed, `fetchMyApps`) and
10
10
  * `/session/end` (RP-initiated logout, AK-35) —
11
- * so a consumer's REAL login → callback → refresh chain runs UNMODIFIED against it. No
11
+ * so a consumer's REAL login → callback → refresh chain runs UNMODIFIED against it.
12
+ *
13
+ * It models flytedesk ID's service identities too (`servicePrincipals`): `POST
14
+ * /service-token` exchanges a Google ID token for a service access token, and
15
+ * `/apps/:appId/authorization` answers a service access token as `kind: "service"`.
16
+ * Google itself is played by this fixture's own test signer — `mintGoogleIdToken`
17
+ * issues the subject tokens `/service-token` accepts — and `mintServiceAccessToken`
18
+ * issues a service access token directly, with overrides for every negative path. No
12
19
  * bypass ever lands in production code: the consuming app simply points
13
20
  * `FLYTEDESK_ID_ISSUER` at this server in its own e2e setup.
14
21
  *
@@ -39,6 +46,53 @@ export interface FakeIdpIdentity {
39
46
  * rejection (AK-23). */
40
47
  emailVerified?: boolean;
41
48
  }
49
+ /** A flytedesk ID service principal this fixture knows (`FakeIdpOptions.servicePrincipals`). */
50
+ export interface FakeIdpServicePrincipal {
51
+ /** The principal's id — the issued token's `sub`, e.g. `svc-sms-app-prod-profiler`. */
52
+ id: string;
53
+ name: string;
54
+ /** Its roles in this fixture's app. Empty: it holds none, so `/service-token` answers
55
+ * `invalid_target`. */
56
+ roles: Array<{
57
+ id: string;
58
+ key: string;
59
+ name: string;
60
+ }>;
61
+ /** UNPREFIXED permission keys, app-prefixed on the authorization answer as for a person. */
62
+ permissions: string[];
63
+ /** The Google service account's subject (`sub`) its Google ID token must carry. */
64
+ googleSubject: string;
65
+ /** The Google service account's email its Google ID token must carry. */
66
+ googleEmail: string;
67
+ /** A disabled principal is refused at `/service-token` and at authorization (401). */
68
+ disabled?: boolean;
69
+ }
70
+ /** Claims a test can override on `FakeIdp.mintServiceAccessToken` to drive a negative path. */
71
+ export interface ServiceAccessTokenOverrides {
72
+ /** `aud`. Default: this fixture's `appId`. */
73
+ audience?: string;
74
+ /** `iss`. Default: this fixture's URL. */
75
+ issuer?: string;
76
+ /** The header `typ`; `null` omits it. Default `at+jwt`. */
77
+ typ?: string | null;
78
+ /** The `fd_kind` claim; `null` omits it. Default `service`. */
79
+ fdKind?: string | null;
80
+ /** `exp` relative to now, in seconds; negative is already expired. Default 600. */
81
+ expiresInSeconds?: number;
82
+ }
83
+ /** What `FakeIdp.mintGoogleIdToken` puts in a Google ID token. */
84
+ export interface GoogleIdTokenClaims {
85
+ sub: string;
86
+ email: string;
87
+ /** `aud`. Default: this fixture's `{url}/service-token`, what `/service-token` requires. */
88
+ audience?: string;
89
+ /** `iss`. Default `https://accounts.google.com`. */
90
+ issuer?: string;
91
+ /** Default `true`. */
92
+ emailVerified?: boolean;
93
+ /** `exp` relative to now, in seconds; negative is already expired. Default 3600. */
94
+ expiresInSeconds?: number;
95
+ }
42
96
  export interface FakeIdpOptions {
43
97
  clientId: string;
44
98
  /** Defaults to `clientId` — distinct because real flytedesk-id keys the authorization
@@ -69,6 +123,8 @@ export interface FakeIdpOptions {
69
123
  * `post_logout_redirect_uri` is then refused, like an unregistered one.
70
124
  */
71
125
  postLogoutRedirectUris?: string[];
126
+ /** Every service principal this fixture knows. Defaults to none. */
127
+ servicePrincipals?: FakeIdpServicePrincipal[];
72
128
  }
73
129
  export declare class FakeIdp {
74
130
  private server?;
@@ -92,6 +148,11 @@ export declare class FakeIdp {
92
148
  private forceInvalidClient;
93
149
  private myAppsFailureStatus;
94
150
  private refreshGrants;
151
+ private readonly servicePrincipals;
152
+ private forceServicePrincipalMismatch;
153
+ private serviceTokensIssued;
154
+ private serviceAuthorizations;
155
+ private googleKeys;
95
156
  private keys;
96
157
  private publicJwk;
97
158
  private readonly kid;
@@ -174,6 +235,29 @@ export declare class FakeIdp {
174
235
  * session (AK-16), which the plain "log in as a different identity" flow can't do.
175
236
  */
176
237
  updateIdentity(key: string, patch: Partial<Omit<FakeIdpIdentity, "sub">>): void;
238
+ /** Disables (or re-enables) a service principal — instant, as in flytedesk ID: its
239
+ * next `/service-token` and its next authorization are both refused. */
240
+ setServicePrincipalDisabled(principalId: string, disabled: boolean): void;
241
+ /** Makes `/apps/:appId/authorization` answer a service access token with a
242
+ * `principalId` other than the token's `sub` — drives the plugin's principal-mismatch
243
+ * rejection. */
244
+ setForceServicePrincipalMismatch(force: boolean): void;
245
+ /** How many service access tokens `/service-token` has issued. */
246
+ get serviceTokenIssueCount(): number;
247
+ /** How many service-token authorization lookups `/apps/:appId/authorization` has answered. */
248
+ get serviceAuthorizationCount(): number;
249
+ /**
250
+ * A flytedesk ID service access token for a registered principal, signed with this
251
+ * fixture's provider key (so its `/jwks` verifies it): header `{alg: RS256, kid, typ:
252
+ * at+jwt}`, claims `iss`, `sub`, `aud`, `client_id`, `fd_kind: service`, `iat`,
253
+ * `exp`, `jti` — what `/service-token` issues. `overrides` bend one claim for a
254
+ * negative test.
255
+ */
256
+ mintServiceAccessToken(principalId: string, overrides?: ServiceAccessTokenOverrides): Promise<string>;
257
+ /** A Google ID token from this fixture's Google stand-in — the `subject_token`
258
+ * `/service-token` takes. Only this fixture accepts it. */
259
+ mintGoogleIdToken(claims: GoogleIdTokenClaims): Promise<string>;
260
+ private servicePrincipal;
177
261
  get url(): string;
178
262
  start(port?: number): Promise<string>;
179
263
  stop(): Promise<void>;
@@ -201,5 +285,17 @@ export declare class FakeIdp {
201
285
  * client's grant in the session, access tokens included), then redirects to
202
286
  * `postLogoutRedirectUri` — or shows a signed-out page when there is none. */
203
287
  private endSession;
288
+ /** Whether a bearer's header says it is a JWT access token — flytedesk ID's split
289
+ * between its two authentication paths. */
290
+ private isServiceAccessToken;
291
+ /** `/apps/:appId/authorization` for a service access token, as flytedesk ID answers it:
292
+ * the token verified locally (this fixture's key, issuer, `fd_kind`, expiry), its
293
+ * audience this app (403 otherwise), its principal registered and enabled (401
294
+ * otherwise). */
295
+ private answerServiceAuthorization;
296
+ /** `POST /service-token` (RFC 8693), as flytedesk ID answers it: a Google ID token
297
+ * (from this fixture's Google stand-in) exchanged for a service access token for the
298
+ * `audience` app. Errors per RFC 6749 §5.2. */
299
+ private exchangeServiceToken;
204
300
  private tokenGrant;
205
301
  }
@@ -1,6 +1,11 @@
1
1
  import { createServer } from "node:http";
2
2
  import { createHash, randomBytes } from "node:crypto";
3
- import { generateKeyPair, exportJWK, jwtVerify, SignJWT } from "jose";
3
+ import { decodeProtectedHeader, generateKeyPair, exportJWK, jwtVerify, SignJWT } from "jose";
4
+ import { ACCESS_TOKEN_TYPE, ID_TOKEN_TYPE, isServiceAccessTokenTyp, SERVICE_ACCESS_TOKEN_ALG, SERVICE_ACCESS_TOKEN_TYP, SERVICE_TOKEN_KIND, SERVICE_TOKEN_KIND_CLAIM, SERVICE_TOKEN_PATH, TOKEN_EXCHANGE_GRANT_TYPE, } from "../serviceTokenContract.js";
5
+ /** The two issuer spellings Google uses in an ID token's `iss`. */
6
+ const GOOGLE_ISSUERS = new Set(["https://accounts.google.com", "accounts.google.com"]);
7
+ /** How long a service access token from `/service-token` lives, as flytedesk ID issues it. */
8
+ const SERVICE_ACCESS_TOKEN_TTL_SECONDS = 600;
4
9
  /** Escapes a value for a double-quoted HTML attribute. */
5
10
  function escapeHtmlAttribute(value) {
6
11
  return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
@@ -44,6 +49,12 @@ export class FakeIdp {
44
49
  forceInvalidClient = false;
45
50
  myAppsFailureStatus = null;
46
51
  refreshGrants = 0;
52
+ servicePrincipals;
53
+ forceServicePrincipalMismatch = false;
54
+ serviceTokensIssued = 0;
55
+ serviceAuthorizations = 0;
56
+ // Plays Google: signs the subject tokens /service-token accepts (mintGoogleIdToken).
57
+ googleKeys;
47
58
  keys;
48
59
  publicJwk;
49
60
  kid = "fake-idp-key";
@@ -56,6 +67,7 @@ export class FakeIdp {
56
67
  this.accessTokenTtlSeconds = opts.accessTokenTtlSeconds ?? 900;
57
68
  this.advertiseRevocationEndpoint = opts.advertiseRevocationEndpoint ?? false;
58
69
  this.postLogoutRedirectUris = new Set(opts.postLogoutRedirectUris ?? []);
70
+ this.servicePrincipals = new Map((opts.servicePrincipals ?? []).map((principal) => [principal.id, principal]));
59
71
  if (!(opts.defaultIdentityKey in this.identities)) {
60
72
  throw new Error(`FakeIdp: defaultIdentityKey "${opts.defaultIdentityKey}" is not in identities`);
61
73
  }
@@ -175,6 +187,69 @@ export class FakeIdp {
175
187
  }
176
188
  Object.assign(identity, patch);
177
189
  }
190
+ /** Disables (or re-enables) a service principal — instant, as in flytedesk ID: its
191
+ * next `/service-token` and its next authorization are both refused. */
192
+ setServicePrincipalDisabled(principalId, disabled) {
193
+ this.servicePrincipal(principalId).disabled = disabled;
194
+ }
195
+ /** Makes `/apps/:appId/authorization` answer a service access token with a
196
+ * `principalId` other than the token's `sub` — drives the plugin's principal-mismatch
197
+ * rejection. */
198
+ setForceServicePrincipalMismatch(force) {
199
+ this.forceServicePrincipalMismatch = force;
200
+ }
201
+ /** How many service access tokens `/service-token` has issued. */
202
+ get serviceTokenIssueCount() {
203
+ return this.serviceTokensIssued;
204
+ }
205
+ /** How many service-token authorization lookups `/apps/:appId/authorization` has answered. */
206
+ get serviceAuthorizationCount() {
207
+ return this.serviceAuthorizations;
208
+ }
209
+ /**
210
+ * A flytedesk ID service access token for a registered principal, signed with this
211
+ * fixture's provider key (so its `/jwks` verifies it): header `{alg: RS256, kid, typ:
212
+ * at+jwt}`, claims `iss`, `sub`, `aud`, `client_id`, `fd_kind: service`, `iat`,
213
+ * `exp`, `jti` — what `/service-token` issues. `overrides` bend one claim for a
214
+ * negative test.
215
+ */
216
+ async mintServiceAccessToken(principalId, overrides = {}) {
217
+ this.servicePrincipal(principalId);
218
+ const iat = Math.floor(Date.now() / 1000);
219
+ const typ = overrides.typ === undefined ? SERVICE_ACCESS_TOKEN_TYP : overrides.typ;
220
+ const fdKind = overrides.fdKind === undefined ? SERVICE_TOKEN_KIND : overrides.fdKind;
221
+ return new SignJWT({
222
+ client_id: principalId,
223
+ ...(fdKind === null ? {} : { [SERVICE_TOKEN_KIND_CLAIM]: fdKind }),
224
+ })
225
+ .setProtectedHeader({ alg: SERVICE_ACCESS_TOKEN_ALG, kid: this.kid, ...(typ === null ? {} : { typ }) })
226
+ .setIssuer(overrides.issuer ?? this.url)
227
+ .setSubject(principalId)
228
+ .setAudience(overrides.audience ?? this.appId)
229
+ .setIssuedAt(iat)
230
+ .setExpirationTime(iat + (overrides.expiresInSeconds ?? SERVICE_ACCESS_TOKEN_TTL_SECONDS))
231
+ .setJti(randomBytes(12).toString("base64url"))
232
+ .sign(this.keys.privateKey);
233
+ }
234
+ /** A Google ID token from this fixture's Google stand-in — the `subject_token`
235
+ * `/service-token` takes. Only this fixture accepts it. */
236
+ async mintGoogleIdToken(claims) {
237
+ const iat = Math.floor(Date.now() / 1000);
238
+ return new SignJWT({ email: claims.email, email_verified: claims.emailVerified ?? true })
239
+ .setProtectedHeader({ alg: "RS256", kid: "fake-google-key" })
240
+ .setIssuer(claims.issuer ?? "https://accounts.google.com")
241
+ .setSubject(claims.sub)
242
+ .setAudience(claims.audience ?? `${this.url}${SERVICE_TOKEN_PATH}`)
243
+ .setIssuedAt(iat)
244
+ .setExpirationTime(iat + (claims.expiresInSeconds ?? 3600))
245
+ .sign(this.googleKeys.privateKey);
246
+ }
247
+ servicePrincipal(principalId) {
248
+ const principal = this.servicePrincipals.get(principalId);
249
+ if (!principal)
250
+ throw new Error(`FakeIdp: no service principal registered for "${principalId}"`);
251
+ return principal;
252
+ }
178
253
  get url() {
179
254
  if (!this.baseUrl)
180
255
  throw new Error("FakeIdp not started");
@@ -182,6 +257,7 @@ export class FakeIdp {
182
257
  }
183
258
  async start(port = 0) {
184
259
  this.keys = await generateKeyPair("RS256", { extractable: true });
260
+ this.googleKeys = await generateKeyPair("RS256");
185
261
  this.publicJwk = {
186
262
  ...(await exportJWK(this.keys.publicKey)),
187
263
  kid: this.kid,
@@ -449,14 +525,22 @@ export class FakeIdp {
449
525
  name: grant.identity.name,
450
526
  });
451
527
  }
528
+ if (req.method === "POST" && path === SERVICE_TOKEN_PATH) {
529
+ return this.exchangeServiceToken(req, res);
530
+ }
452
531
  if (req.method === "GET" && path === `/apps/${this.appId}/authorization`) {
453
532
  if (this.hangAuthorizationMs > 0) {
454
533
  await new Promise((resolve) => setTimeout(resolve, this.hangAuthorizationMs));
455
534
  }
535
+ const bearer = this.bearer(req);
536
+ if (bearer && this.isServiceAccessToken(bearer)) {
537
+ return this.answerServiceAuthorization(res, bearer);
538
+ }
456
539
  const grant = this.tokenGrant(req);
457
540
  if (!grant)
458
541
  return this.json(res, 401, { error: "invalid_token" });
459
542
  return this.json(res, 200, {
543
+ kind: "person",
460
544
  userId: grant.identity.sub,
461
545
  appId: this.appId,
462
546
  roles: grant.identity.roles,
@@ -646,6 +730,100 @@ export class FakeIdp {
646
730
  res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
647
731
  res.end(`<!doctype html><title>FakeIdp signed out</title><h1>Signed out of FakeIdp</h1>`);
648
732
  }
733
+ /** Whether a bearer's header says it is a JWT access token — flytedesk ID's split
734
+ * between its two authentication paths. */
735
+ isServiceAccessToken(bearer) {
736
+ try {
737
+ return isServiceAccessTokenTyp(decodeProtectedHeader(bearer).typ);
738
+ }
739
+ catch {
740
+ return false;
741
+ }
742
+ }
743
+ /** `/apps/:appId/authorization` for a service access token, as flytedesk ID answers it:
744
+ * the token verified locally (this fixture's key, issuer, `fd_kind`, expiry), its
745
+ * audience this app (403 otherwise), its principal registered and enabled (401
746
+ * otherwise). */
747
+ async answerServiceAuthorization(res, bearer) {
748
+ let sub;
749
+ let audience;
750
+ try {
751
+ const { payload } = await jwtVerify(bearer, this.keys.publicKey, {
752
+ issuer: this.baseUrl,
753
+ typ: SERVICE_ACCESS_TOKEN_TYP,
754
+ algorithms: [SERVICE_ACCESS_TOKEN_ALG],
755
+ requiredClaims: ["exp", "sub", SERVICE_TOKEN_KIND_CLAIM],
756
+ });
757
+ if (payload[SERVICE_TOKEN_KIND_CLAIM] !== SERVICE_TOKEN_KIND)
758
+ throw new Error("not a service token");
759
+ sub = payload.sub;
760
+ audience = payload.aud;
761
+ }
762
+ catch {
763
+ return this.json(res, 401, { error: "invalid_token" });
764
+ }
765
+ if (audience !== this.appId)
766
+ return this.json(res, 403, { error: "forbidden", detail: "audience is another app" });
767
+ const principal = this.servicePrincipals.get(sub);
768
+ if (!principal || principal.disabled)
769
+ return this.json(res, 401, { error: "invalid_token" });
770
+ this.serviceAuthorizations += 1;
771
+ return this.json(res, 200, {
772
+ kind: SERVICE_TOKEN_KIND,
773
+ principalId: this.forceServicePrincipalMismatch ? `${principal.id}-mismatch` : principal.id,
774
+ name: principal.name,
775
+ appId: this.appId,
776
+ roles: principal.roles,
777
+ permissions: principal.permissions.map((p) => `${this.appId}:${p}`),
778
+ });
779
+ }
780
+ /** `POST /service-token` (RFC 8693), as flytedesk ID answers it: a Google ID token
781
+ * (from this fixture's Google stand-in) exchanged for a service access token for the
782
+ * `audience` app. Errors per RFC 6749 §5.2. */
783
+ async exchangeServiceToken(req, res) {
784
+ const refuse = (error, description) => this.json(res, 400, { error, error_description: description });
785
+ const form = await this.readForm(req);
786
+ const subjectToken = form.get("subject_token");
787
+ const audience = form.get("audience");
788
+ if (form.get("grant_type") !== TOKEN_EXCHANGE_GRANT_TYPE) {
789
+ return refuse("unsupported_grant_type", "grant_type must be token-exchange");
790
+ }
791
+ if (!subjectToken || !audience || form.get("subject_token_type") !== ID_TOKEN_TYPE) {
792
+ return refuse("invalid_request", "subject_token, subject_token_type=id_token and audience are required");
793
+ }
794
+ let google;
795
+ try {
796
+ const { payload } = await jwtVerify(subjectToken, this.googleKeys.publicKey, {
797
+ audience: `${this.baseUrl}${SERVICE_TOKEN_PATH}`,
798
+ requiredClaims: ["exp", "sub", "iss"],
799
+ });
800
+ if (!GOOGLE_ISSUERS.has(payload.iss))
801
+ throw new Error("not issued by Google");
802
+ google = { sub: payload.sub, email: payload.email, emailVerified: payload.email_verified };
803
+ }
804
+ catch (err) {
805
+ return refuse("invalid_grant", `subject_token refused: ${err instanceof Error ? err.message : String(err)}`);
806
+ }
807
+ if (google.emailVerified !== true)
808
+ return refuse("invalid_grant", "subject_token email is not verified");
809
+ const principal = [...this.servicePrincipals.values()].find((p) => p.googleSubject === google.sub);
810
+ if (!principal)
811
+ return refuse("invalid_grant", "no service principal for this Google subject");
812
+ if (principal.googleEmail !== google.email)
813
+ return refuse("invalid_grant", "subject_token email does not match");
814
+ if (principal.disabled)
815
+ return refuse("invalid_grant", "service principal is disabled");
816
+ if (audience !== this.appId || principal.roles.length === 0) {
817
+ return refuse("invalid_target", `service principal holds no role in "${audience}"`);
818
+ }
819
+ this.serviceTokensIssued += 1;
820
+ return this.json(res, 200, {
821
+ access_token: await this.mintServiceAccessToken(principal.id),
822
+ issued_token_type: ACCESS_TOKEN_TYPE,
823
+ token_type: "Bearer",
824
+ expires_in: SERVICE_ACCESS_TOKEN_TTL_SECONDS,
825
+ });
826
+ }
649
827
  tokenGrant(req) {
650
828
  const token = this.bearer(req);
651
829
  return token ? (this.grants.get(token) ?? null) : null;