@flytedesk/app-kit 8.0.0 → 10.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.
Files changed (59) hide show
  1. package/README.md +135 -4
  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/errors.d.ts +34 -8
  39. package/dist/bigquery/errors.js +180 -22
  40. package/dist/bigquery/errors.js.map +1 -1
  41. package/dist/bigquery/index.d.ts +2 -1
  42. package/dist/bigquery/index.js +1 -1
  43. package/dist/bigquery/index.js.map +1 -1
  44. package/dist/bigquery/jobIdentity.d.ts +39 -0
  45. package/dist/bigquery/jobIdentity.js +83 -0
  46. package/dist/bigquery/jobIdentity.js.map +1 -0
  47. package/dist/bigquery/load.d.ts +11 -14
  48. package/dist/bigquery/load.js +132 -56
  49. package/dist/bigquery/load.js.map +1 -1
  50. package/dist/bigquery/query.d.ts +19 -1
  51. package/dist/bigquery/query.js +143 -50
  52. package/dist/bigquery/query.js.map +1 -1
  53. package/dist/bigquery/retry.d.ts +56 -0
  54. package/dist/bigquery/retry.js +110 -0
  55. package/dist/bigquery/retry.js.map +1 -0
  56. package/dist/bigquery/types.d.ts +40 -5
  57. package/dist/profile/plugin.js +11 -7
  58. package/dist/profile/plugin.js.map +1 -1
  59. package/package.json +5 -1
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Read-only enforcement for service principals. A service principal is read-only by
3
+ * kind: `@flytedesk/app-kit/auth/plugin` answers it `403 read_only_principal` on every
4
+ * request that is not a read, before any handler or guard runs. GET and HEAD are reads;
5
+ * a route that reads with another method (a query sent as a POST body) declares it with
6
+ * `config: readRoute`:
7
+ *
8
+ * app.post("/audiences/count", { config: readRoute, preHandler: requireAuth }, handler);
9
+ *
10
+ * Mark only routes that change nothing — no row written, nothing keyed to the caller.
11
+ * `appKitRead` is typed on Fastify's `FastifyContextConfig` by the plugin subpath.
12
+ */
13
+ /** Route config marking a non-GET/HEAD route as a read a service principal may call. */
14
+ export declare const readRoute: {
15
+ readonly appKitRead: true;
16
+ };
17
+ /** Whether a request is a read: a GET or HEAD, or any method on a route marked `readRoute`. */
18
+ export declare function isReadRequest(method: string, routeConfig: {
19
+ appKitRead?: boolean;
20
+ } | undefined): boolean;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Read-only enforcement for service principals. A service principal is read-only by
3
+ * kind: `@flytedesk/app-kit/auth/plugin` answers it `403 read_only_principal` on every
4
+ * request that is not a read, before any handler or guard runs. GET and HEAD are reads;
5
+ * a route that reads with another method (a query sent as a POST body) declares it with
6
+ * `config: readRoute`:
7
+ *
8
+ * app.post("/audiences/count", { config: readRoute, preHandler: requireAuth }, handler);
9
+ *
10
+ * Mark only routes that change nothing — no row written, nothing keyed to the caller.
11
+ * `appKitRead` is typed on Fastify's `FastifyContextConfig` by the plugin subpath.
12
+ */
13
+ /** Route config marking a non-GET/HEAD route as a read a service principal may call. */
14
+ export const readRoute = Object.freeze({ appKitRead: true });
15
+ const READ_METHODS = new Set(["GET", "HEAD"]);
16
+ /** Whether a request is a read: a GET or HEAD, or any method on a route marked `readRoute`. */
17
+ export function isReadRequest(method, routeConfig) {
18
+ return READ_METHODS.has(method) || routeConfig?.appKitRead === true;
19
+ }
20
+ //# sourceMappingURL=readRoute.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"readRoute.js","sourceRoot":"","sources":["../../src/auth/readRoute.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,wFAAwF;AACxF,MAAM,CAAC,MAAM,SAAS,GAAkC,MAAM,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;AAE5F,MAAM,YAAY,GAAwB,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC;AAEnE,+FAA+F;AAC/F,MAAM,UAAU,aAAa,CAAC,MAAc,EAAE,WAAiD;IAC7F,OAAO,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,WAAW,EAAE,UAAU,KAAK,IAAI,CAAC;AACtE,CAAC"}
@@ -0,0 +1,61 @@
1
+ export { IdpError, IdpTimeoutError, IdpUnavailableError, ServiceTokenRefusedError } from "../errors.js";
2
+ /** How long before its `exp` a cached service access token is replaced. */
3
+ export declare const DEFAULT_SERVICE_TOKEN_REFRESH_SKEW_MS = 60000;
4
+ /** A service access token and when it expires (its `exp` claim). */
5
+ export interface ServiceAccessToken {
6
+ accessToken: string;
7
+ expiresAt: Date;
8
+ }
9
+ export interface ExchangeServiceTokenOptions {
10
+ /** flytedesk ID's issuer URL, exactly as it signs tokens (no trailing slash). */
11
+ issuer: string;
12
+ /** The flytedesk ID app id the token is for — its `aud`. */
13
+ appId: string;
14
+ /** A Google ID token whose `aud` is `serviceTokenAudience(issuer)`. */
15
+ subjectToken: string;
16
+ /** Default `globalThis.fetch`. */
17
+ fetch?: typeof fetch;
18
+ /** Bounds the exchange request. Default `DEFAULT_IDP_REQUEST_TIMEOUT_MS` (5s). */
19
+ timeoutMs?: number;
20
+ }
21
+ export interface ServiceTokenSourceOptions {
22
+ /** flytedesk ID's issuer URL, exactly as it signs tokens (no trailing slash). */
23
+ issuer: string;
24
+ /** The flytedesk ID app id the tokens are for. */
25
+ appId: string;
26
+ /** Returns a fresh Google ID token for `audience` (always `serviceTokenAudience(issuer)`).
27
+ * Called once per exchange; whatever it throws reaches `accessToken()`'s caller. */
28
+ idToken: (audience: string) => Promise<string>;
29
+ /** Milliseconds since the epoch. Default `Date.now`. */
30
+ clock?: () => number;
31
+ /** A cached token is replaced this long before its `exp`. Default 60s. */
32
+ refreshSkewMs?: number;
33
+ /** Default `globalThis.fetch`. */
34
+ fetch?: typeof fetch;
35
+ /** Bounds each exchange request. Default `DEFAULT_IDP_REQUEST_TIMEOUT_MS` (5s). */
36
+ timeoutMs?: number;
37
+ }
38
+ export interface ServiceTokenSource {
39
+ /** A live service access token: the cached one until `refreshSkewMs` before its
40
+ * `exp`, otherwise a fresh exchange. Concurrent calls share one exchange; a failed
41
+ * exchange is not cached, so the next call tries again. */
42
+ accessToken(): Promise<string>;
43
+ }
44
+ /**
45
+ * The `aud` the Google ID token must carry, which is also the exchange endpoint:
46
+ * `{issuer}/service-token`. Throws for an issuer ending in `/` — flytedesk ID compares
47
+ * this string exactly, and the plugin compares the issued token's `iss` exactly.
48
+ */
49
+ export declare function serviceTokenAudience(issuer: string): string;
50
+ /**
51
+ * Exchanges a Google ID token for a flytedesk ID service access token for `appId`.
52
+ * Throws:
53
+ * - `ServiceTokenRefusedError` — flytedesk ID answered 4xx: the caller or its
54
+ * registration is refused (`oauthError` says why). Retrying will not help.
55
+ * - `IdpTimeoutError` — no answer within `timeoutMs`.
56
+ * - `IdpUnavailableError` — flytedesk ID unreachable, a 5xx, or an answer without a
57
+ * usable `access_token` (a JWT with an `exp`). Safe to retry later.
58
+ */
59
+ export declare function exchangeServiceToken(options: ExchangeServiceTokenOptions): Promise<ServiceAccessToken>;
60
+ /** A cached, self-refreshing source of service access tokens — see `ServiceTokenSource`. */
61
+ export declare function createServiceTokenSource(options: ServiceTokenSourceOptions): ServiceTokenSource;
@@ -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,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CAAC,KAAK,IAAI,IAAI,CAAC,GAAG,CAAC;IAExC,IAAI,MAAsC,CAAC;IAC3C,IAAI,QAAqC,CAAC;IAE1C,KAAK,UAAU,QAAQ;QACrB,MAAM,YAAY,GAAG,MAAM,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QACrD,MAAM,GAAG,MAAM,oBAAoB,CAAC;YAClC,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,KAAK,EAAE,OAAO,CAAC,KAAK;YACpB,YAAY;YACZ,KAAK,EAAE,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,CAAC,MAAM,wBAAwB,GAAG,MAAM,CAAC;AAE/C;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,iBAAiB,EAAE,wBAAwB,EAAE,2BAA2B,CAAU,CAAC;AAI1H;;;;;GAKG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,UAAU,CAAC;AAEhD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,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"}
1
+ {"version":3,"file":"shared-types.js","sourceRoot":"","sources":["../../src/auth/shared-types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAkDH;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,OAAO,CAAC;AAEzC;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,MAAM,CAAC;AAE/C;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,iBAAiB,EAAE,wBAAwB,EAAE,2BAA2B,CAAU,CAAC;AAI1H;;;;;GAKG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,UAAU,CAAC;AAEhD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,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
  }