@flytedesk/app-kit 12.5.0 → 12.6.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 -0
  2. package/dist/auth/idpRequest.d.ts +16 -0
  3. package/dist/auth/idpRequest.js +37 -0
  4. package/dist/auth/idpRequest.js.map +1 -0
  5. package/dist/auth/jwks.d.ts +16 -0
  6. package/dist/auth/jwks.js +38 -0
  7. package/dist/auth/jwks.js.map +1 -0
  8. package/dist/auth/oidc-client.js +7 -25
  9. package/dist/auth/oidc-client.js.map +1 -1
  10. package/dist/auth/people/lookup.js +9 -16
  11. package/dist/auth/people/lookup.js.map +1 -1
  12. package/dist/auth/service/index.js +12 -19
  13. package/dist/auth/service/index.js.map +1 -1
  14. package/dist/connections/cipher/index.d.ts +20 -0
  15. package/dist/connections/cipher/index.js +26 -0
  16. package/dist/connections/cipher/index.js.map +1 -0
  17. package/dist/connections/cipher/kmsDecrypt.d.ts +3 -0
  18. package/dist/connections/cipher/kmsDecrypt.js +25 -0
  19. package/dist/connections/cipher/kmsDecrypt.js.map +1 -0
  20. package/dist/connections/cipher/kmsEncrypt.d.ts +3 -0
  21. package/dist/connections/cipher/kmsEncrypt.js +24 -0
  22. package/dist/connections/cipher/kmsEncrypt.js.map +1 -0
  23. package/dist/connections/cipher/localDecrypt.d.ts +3 -0
  24. package/dist/connections/cipher/localDecrypt.js +25 -0
  25. package/dist/connections/cipher/localDecrypt.js.map +1 -0
  26. package/dist/connections/cipher/localEncrypt.d.ts +3 -0
  27. package/dist/connections/cipher/localEncrypt.js +22 -0
  28. package/dist/connections/cipher/localEncrypt.js.map +1 -0
  29. package/dist/connections/cipher/localFormat.d.ts +5 -0
  30. package/dist/connections/cipher/localFormat.js +18 -0
  31. package/dist/connections/cipher/localFormat.js.map +1 -0
  32. package/dist/connections/cipher/types.d.ts +39 -0
  33. package/dist/connections/cipher/types.js +2 -0
  34. package/dist/connections/cipher/types.js.map +1 -0
  35. package/dist/connections/client.d.ts +52 -0
  36. package/dist/connections/client.js +227 -0
  37. package/dist/connections/client.js.map +1 -0
  38. package/dist/connections/contract.d.ts +63 -0
  39. package/dist/connections/contract.js +38 -0
  40. package/dist/connections/contract.js.map +1 -0
  41. package/dist/connections/errors.d.ts +36 -0
  42. package/dist/connections/errors.js +54 -0
  43. package/dist/connections/errors.js.map +1 -0
  44. package/dist/connections/index.d.ts +27 -0
  45. package/dist/connections/index.js +27 -0
  46. package/dist/connections/index.js.map +1 -0
  47. package/dist/connections/kinds.d.ts +151 -0
  48. package/dist/connections/kinds.js +61 -0
  49. package/dist/connections/kinds.js.map +1 -0
  50. package/dist/connections/testHandler.d.ts +44 -0
  51. package/dist/connections/testHandler.js +92 -0
  52. package/dist/connections/testHandler.js.map +1 -0
  53. package/dist/connections/testers/mysql.d.ts +14 -0
  54. package/dist/connections/testers/mysql.js +74 -0
  55. package/dist/connections/testers/mysql.js.map +1 -0
  56. package/dist/connections/testers/postgres.d.ts +41 -0
  57. package/dist/connections/testers/postgres.js +249 -0
  58. package/dist/connections/testers/postgres.js.map +1 -0
  59. package/package.json +6 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kmsEncrypt.js","sourceRoot":"","sources":["../../../src/connections/cipher/kmsEncrypt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAGrD,0GAA0G;AAC1G,MAAM,UAAU,kBAAkB,CAAC,MAAkC;IACnE,OAAO;QACL,KAAK,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,GAAG,EAAE;YACvC,IAAI,CAAC;gBACH,MAAM,CAAC,QAAQ,CAAC,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC;oBACtC,IAAI,EAAE,OAAO;oBACb,SAAS,EAAE,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC;oBACzC,2BAA2B,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC;iBAC9C,CAAC,CAAC;gBACH,MAAM,UAAU,GAAG,QAAQ,CAAC,UAAU,CAAC;gBACvC,IAAI,UAAU,KAAK,SAAS,IAAI,UAAU,KAAK,IAAI;oBAAE,MAAM,IAAI,KAAK,CAAC,gBAAgB,CAAC,CAAC;gBACvF,OAAO,CAAC,OAAO,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,CAC5G,QAAQ,CACT,CAAC;YACJ,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,MAAM,IAAI,GAAI,GAAiC,EAAE,IAAI,CAAC;gBACtD,MAAM,IAAI,qBAAqB,CAC7B,4CAA4C,OAAO,GAAG,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,cAAc,IAAI,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAC9G,CAAC;YACJ,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { ConnectionDecryptor } from "./types.js";
2
+ /** The local AES-256-GCM cipher's decrypt side, for local development and tests. */
3
+ export declare function createLocalDecryptor(masterKey: Uint8Array): ConnectionDecryptor;
@@ -0,0 +1,25 @@
1
+ import { createDecipheriv } from "node:crypto";
2
+ import { ConnectionCipherError } from "../errors.js";
3
+ import { assertLocalMasterKey, deriveLocalKey, LOCAL_IV_BYTES, LOCAL_TAG_BYTES } from "./localFormat.js";
4
+ /** The local AES-256-GCM cipher's decrypt side, for local development and tests. */
5
+ export function createLocalDecryptor(masterKey) {
6
+ assertLocalMasterKey(masterKey);
7
+ return {
8
+ async decrypt({ keyName, ciphertext, aad }) {
9
+ try {
10
+ const raw = Buffer.from(ciphertext, "base64");
11
+ const iv = raw.subarray(0, LOCAL_IV_BYTES);
12
+ const tag = raw.subarray(LOCAL_IV_BYTES, LOCAL_IV_BYTES + LOCAL_TAG_BYTES);
13
+ const body = raw.subarray(LOCAL_IV_BYTES + LOCAL_TAG_BYTES);
14
+ const decipher = createDecipheriv("aes-256-gcm", deriveLocalKey(masterKey, keyName), iv);
15
+ decipher.setAAD(Buffer.from(aad));
16
+ decipher.setAuthTag(tag);
17
+ return Buffer.concat([decipher.update(body), decipher.final()]).toString("utf8");
18
+ }
19
+ catch {
20
+ throw new ConnectionCipherError(`a value could not be decrypted under key ${keyName}`);
21
+ }
22
+ },
23
+ };
24
+ }
25
+ //# sourceMappingURL=localDecrypt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"localDecrypt.js","sourceRoot":"","sources":["../../../src/connections/cipher/localDecrypt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAErD,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAEzG,oFAAoF;AACpF,MAAM,UAAU,oBAAoB,CAAC,SAAqB;IACxD,oBAAoB,CAAC,SAAS,CAAC,CAAC;IAChC,OAAO;QACL,KAAK,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,UAAU,EAAE,GAAG,EAAE;YACxC,IAAI,CAAC;gBACH,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;gBAC9C,MAAM,EAAE,GAAG,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,cAAc,CAAC,CAAC;gBAC3C,MAAM,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,cAAc,EAAE,cAAc,GAAG,eAAe,CAAC,CAAC;gBAC3E,MAAM,IAAI,GAAG,GAAG,CAAC,QAAQ,CAAC,cAAc,GAAG,eAAe,CAAC,CAAC;gBAC5D,MAAM,QAAQ,GAAG,gBAAgB,CAAC,aAAa,EAAE,cAAc,CAAC,SAAS,EAAE,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC;gBACzF,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;gBAClC,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;gBACzB,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;YACnF,CAAC;YAAC,MAAM,CAAC;gBACP,MAAM,IAAI,qBAAqB,CAAC,4CAA4C,OAAO,EAAE,CAAC,CAAC;YACzF,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { ConnectionEncryptor } from "./types.js";
2
+ /** The local AES-256-GCM cipher's encrypt side, for local development and tests. */
3
+ export declare function createLocalEncryptor(masterKey: Uint8Array): ConnectionEncryptor;
@@ -0,0 +1,22 @@
1
+ import { createCipheriv, randomBytes } from "node:crypto";
2
+ import { ConnectionCipherError } from "../errors.js";
3
+ import { assertLocalMasterKey, deriveLocalKey, LOCAL_IV_BYTES } from "./localFormat.js";
4
+ /** The local AES-256-GCM cipher's encrypt side, for local development and tests. */
5
+ export function createLocalEncryptor(masterKey) {
6
+ assertLocalMasterKey(masterKey);
7
+ return {
8
+ async encrypt({ keyName, plaintext, aad }) {
9
+ try {
10
+ const iv = randomBytes(LOCAL_IV_BYTES);
11
+ const cipher = createCipheriv("aes-256-gcm", deriveLocalKey(masterKey, keyName), iv);
12
+ cipher.setAAD(Buffer.from(aad));
13
+ const body = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
14
+ return Buffer.concat([iv, cipher.getAuthTag(), body]).toString("base64");
15
+ }
16
+ catch {
17
+ throw new ConnectionCipherError(`a value could not be encrypted under key ${keyName}`);
18
+ }
19
+ },
20
+ };
21
+ }
22
+ //# sourceMappingURL=localEncrypt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"localEncrypt.js","sourceRoot":"","sources":["../../../src/connections/cipher/localEncrypt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAErD,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAExF,oFAAoF;AACpF,MAAM,UAAU,oBAAoB,CAAC,SAAqB;IACxD,oBAAoB,CAAC,SAAS,CAAC,CAAC;IAChC,OAAO;QACL,KAAK,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,GAAG,EAAE;YACvC,IAAI,CAAC;gBACH,MAAM,EAAE,GAAG,WAAW,CAAC,cAAc,CAAC,CAAC;gBACvC,MAAM,MAAM,GAAG,cAAc,CAAC,aAAa,EAAE,cAAc,CAAC,SAAS,EAAE,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC;gBACrF,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;gBAChC,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;gBAC/E,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,EAAE,MAAM,CAAC,UAAU,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;YAC3E,CAAC;YAAC,MAAM,CAAC;gBACP,MAAM,IAAI,qBAAqB,CAAC,4CAA4C,OAAO,EAAE,CAAC,CAAC;YACzF,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,5 @@
1
+ export declare const LOCAL_IV_BYTES = 12;
2
+ export declare const LOCAL_TAG_BYTES = 16;
3
+ export declare const LOCAL_KEY_BYTES = 32;
4
+ export declare function assertLocalMasterKey(masterKey: Uint8Array): void;
5
+ export declare function deriveLocalKey(masterKey: Uint8Array, keyName: string): Buffer;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The one copy of the local cipher's format, used by both sides: AES-256-GCM under a key
3
+ * derived from the local master key and the key name, the additional authenticated data
4
+ * bound as GCM AAD, laid out as `iv (12) | tag (16) | ciphertext`.
5
+ */
6
+ import { hkdfSync } from "node:crypto";
7
+ export const LOCAL_IV_BYTES = 12;
8
+ export const LOCAL_TAG_BYTES = 16;
9
+ export const LOCAL_KEY_BYTES = 32;
10
+ export function assertLocalMasterKey(masterKey) {
11
+ if (masterKey.length !== LOCAL_KEY_BYTES) {
12
+ throw new Error(`the local cipher's key must be ${LOCAL_KEY_BYTES} bytes, got ${masterKey.length}`);
13
+ }
14
+ }
15
+ export function deriveLocalKey(masterKey, keyName) {
16
+ return Buffer.from(hkdfSync("sha256", masterKey, Buffer.alloc(0), `flytedesk-id:local:${keyName}`, LOCAL_KEY_BYTES));
17
+ }
18
+ //# sourceMappingURL=localFormat.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"localFormat.js","sourceRoot":"","sources":["../../../src/connections/cipher/localFormat.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,MAAM,CAAC,MAAM,cAAc,GAAG,EAAE,CAAC;AACjC,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,CAAC;AAClC,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,CAAC;AAElC,MAAM,UAAU,oBAAoB,CAAC,SAAqB;IACxD,IAAI,SAAS,CAAC,MAAM,KAAK,eAAe,EAAE,CAAC;QACzC,MAAM,IAAI,KAAK,CAAC,kCAAkC,eAAe,eAAe,SAAS,CAAC,MAAM,EAAE,CAAC,CAAC;IACtG,CAAC;AACH,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,SAAqB,EAAE,OAAe;IACnE,OAAO,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,SAAS,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,sBAAsB,OAAO,EAAE,EAAE,eAAe,CAAC,CAAC,CAAC;AACvH,CAAC"}
@@ -0,0 +1,39 @@
1
+ /** Decrypts a connection secret: an app's side. `ciphertext` is base64; the result is the plaintext. */
2
+ export interface ConnectionDecryptor {
3
+ decrypt(input: {
4
+ keyName: string;
5
+ ciphertext: string;
6
+ aad: string;
7
+ }): Promise<string>;
8
+ }
9
+ /** Encrypts a connection secret: flytedesk ID's side. The result is base64. */
10
+ export interface ConnectionEncryptor {
11
+ encrypt(input: {
12
+ keyName: string;
13
+ plaintext: string;
14
+ aad: string;
15
+ }): Promise<string>;
16
+ }
17
+ export interface ConnectionCipher extends ConnectionDecryptor, ConnectionEncryptor {
18
+ }
19
+ /**
20
+ * The part of a Cloud KMS client (`KeyManagementServiceClient` from `@google-cloud/kms`)
21
+ * the KMS cipher uses. The app constructs the real client with its runtime credentials;
22
+ * app-kit never builds one.
23
+ */
24
+ export interface KmsClient {
25
+ encrypt(request: {
26
+ name: string;
27
+ plaintext: Uint8Array;
28
+ additionalAuthenticatedData: Uint8Array;
29
+ }): Promise<readonly [{
30
+ ciphertext?: Uint8Array | string | null;
31
+ }, ...unknown[]]>;
32
+ decrypt(request: {
33
+ name: string;
34
+ ciphertext: Uint8Array;
35
+ additionalAuthenticatedData: Uint8Array;
36
+ }): Promise<readonly [{
37
+ plaintext?: Uint8Array | string | null;
38
+ }, ...unknown[]]>;
39
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/connections/cipher/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,52 @@
1
+ import type { ConnectionDecryptor } from "./cipher/types.js";
2
+ import { CONNECTION_KINDS, type ConnectionKindRegistry, type ConnectionValues, type PreviousSecret } from "./kinds.js";
3
+ /** How long a read is reused. */
4
+ export declare const CONNECTION_CACHE_TTL_MS = 60000;
5
+ /** How long after it was fetched a value may still be served while flytedesk ID is down. */
6
+ export declare const CONNECTION_STALE_LIMIT_MS: number;
7
+ export interface ConnectionsLogger {
8
+ /** Receives a line naming the connection and the error class, never a value. */
9
+ error(line: string): void;
10
+ }
11
+ export interface ConnectionsClientOptions<R extends ConnectionKindRegistry = typeof CONNECTION_KINDS> {
12
+ /** flytedesk ID's issuer URL (no trailing slash). */
13
+ issuer: string;
14
+ /** The flytedesk ID app id whose connections are read. */
15
+ appId: string;
16
+ /** The app's service token source (`createServiceTokenSource`). */
17
+ tokenSource: {
18
+ accessToken(): Promise<string>;
19
+ };
20
+ /** Decrypts the secrets: from `createConnectionCipher`, or one of the decrypt-only creators. */
21
+ cipher: ConnectionDecryptor;
22
+ /** The kinds the app knows. Default `CONNECTION_KINDS`. */
23
+ kinds?: R;
24
+ /** Default `globalThis.fetch`. */
25
+ fetch?: typeof fetch;
26
+ /** Bounds each request. Default `DEFAULT_IDP_REQUEST_TIMEOUT_MS` (5s). */
27
+ timeoutMs?: number;
28
+ /** Milliseconds since the epoch. Default `Date.now`. */
29
+ clock?: () => number;
30
+ /** Default `console.error`. */
31
+ logger?: ConnectionsLogger;
32
+ }
33
+ export interface ReadOptions {
34
+ /** Skip the cache and never serve a stale value. The fresh value replaces the cached one. */
35
+ fresh?: boolean;
36
+ }
37
+ /** A connection read without a caller-known kind (the test handler's case). */
38
+ export interface UntypedConnection {
39
+ kind: string;
40
+ /** The current version of each secret field, as read. */
41
+ versions: Record<string, number>;
42
+ settings: Record<string, string | number>;
43
+ secrets: Record<string, string>;
44
+ previous: Record<string, PreviousSecret>;
45
+ }
46
+ export interface ConnectionsClient<R extends ConnectionKindRegistry = typeof CONNECTION_KINDS> {
47
+ /** The connection `slug`, which must be a `kind` connection. */
48
+ get<K extends keyof R & string>(slug: string, kind: K, options?: ReadOptions): Promise<ConnectionValues<R[K]>>;
49
+ /** The connection `slug` whatever its kind. */
50
+ read(slug: string, options?: ReadOptions): Promise<UntypedConnection>;
51
+ }
52
+ export declare function createConnectionsClient<R extends ConnectionKindRegistry = typeof CONNECTION_KINDS>(options: ConnectionsClientOptions<R>): ConnectionsClient<R>;
@@ -0,0 +1,227 @@
1
+ /**
2
+ * The client an app's server reads its own connections with: `GET {issuer}/apps/:appId/
3
+ * connections/:slug` as the app's service principal, then each secret decrypted with the
4
+ * app's own KMS key. Pattern: `../auth/people/lookup.ts` (service token, `idpFetch`, the
5
+ * 4xx-vs-outage split). Never imports Fastify.
6
+ *
7
+ * Caching (DEC-346): a read is reused for 60 seconds. When flytedesk ID cannot be reached
8
+ * at refresh time the last value is served for up to 15 minutes after it was fetched, each
9
+ * failed refresh logged; a refusal is never covered by the cache and drops it.
10
+ */
11
+ import { IdpUnavailableError, ServiceTokenRefusedError } from "../auth/errors.js";
12
+ import { DEFAULT_IDP_REQUEST_TIMEOUT_MS, idpFetch } from "../auth/idpFetch.js";
13
+ import { assertBareIssuer, isClientRefusal, parseIdpJson, readIdpAnswer } from "../auth/idpRequest.js";
14
+ import { CONNECTION_ERROR_CODES, connectionAad, connectionReadPath, } from "./contract.js";
15
+ import { ConnectionInvalidError, ConnectionKindMismatchError, ConnectionOutageError, ConnectionRefusedError, } from "./errors.js";
16
+ import { CONNECTION_KINDS } from "./kinds.js";
17
+ /** How long a read is reused. */
18
+ export const CONNECTION_CACHE_TTL_MS = 60_000;
19
+ /** How long after it was fetched a value may still be served while flytedesk ID is down. */
20
+ export const CONNECTION_STALE_LIMIT_MS = 15 * 60_000;
21
+ const REFUSAL_REASONS = {
22
+ [CONNECTION_ERROR_CODES.disabled]: "disabled",
23
+ [CONNECTION_ERROR_CODES.valueNotSet]: "value not set",
24
+ [CONNECTION_ERROR_CODES.noPermission]: "no permission",
25
+ [CONNECTION_ERROR_CODES.unknown]: "unknown",
26
+ };
27
+ /** The contract error code in a refusal's body text, when it carries one. */
28
+ function refusalCodeOf(bodyText) {
29
+ let code;
30
+ try {
31
+ code = JSON.parse(bodyText)?.error;
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ return typeof code === "string" && code in REFUSAL_REASONS ? code : undefined;
37
+ }
38
+ export function createConnectionsClient(options) {
39
+ assertBareIssuer(options.issuer, "connections");
40
+ if (options.appId.length === 0)
41
+ throw new Error("connections: appId is required");
42
+ const kinds = options.kinds ?? CONNECTION_KINDS;
43
+ const clock = options.clock ?? Date.now;
44
+ // eslint-disable-next-line no-console -- the default sink for the failed-refresh error line
45
+ const logger = options.logger ?? { error: (line) => console.error(line) };
46
+ const cache = new Map();
47
+ const inFlight = new Map();
48
+ // AK-74: a fresh read or a refusal starts a new epoch for the slug, and a refresh that began
49
+ // in an earlier epoch never caches its value, so an older read cannot undo either.
50
+ const epochs = new Map();
51
+ const epochOf = (slug) => epochs.get(slug) ?? 0;
52
+ const startNewEpoch = (slug) => {
53
+ epochs.set(slug, epochOf(slug) + 1);
54
+ inFlight.delete(slug); // a later get() starts its own refresh instead of joining the older one
55
+ };
56
+ async function fetchAnswer(slug) {
57
+ let token;
58
+ try {
59
+ token = await options.tokenSource.accessToken();
60
+ }
61
+ catch (err) {
62
+ if (err instanceof ServiceTokenRefusedError)
63
+ throw new ConnectionRefusedError(slug, "no permission", undefined, err);
64
+ throw err;
65
+ }
66
+ const path = connectionReadPath(options.appId, slug);
67
+ const res = await idpFetch(`${options.issuer}${path}`, { headers: { Accept: "application/json", Authorization: `Bearer ${token}` } }, path, options.timeoutMs ?? DEFAULT_IDP_REQUEST_TIMEOUT_MS, options.fetch);
68
+ const text = await readIdpAnswer(res, {
69
+ path,
70
+ refuses: isClientRefusal,
71
+ refusal: (_status, refusalBody) => {
72
+ const code = refusalCodeOf(refusalBody);
73
+ return new ConnectionRefusedError(slug, code ? REFUSAL_REASONS[code] : "unknown", code);
74
+ },
75
+ });
76
+ const body = parseIdpJson(text, path);
77
+ if (!isAnswer(body))
78
+ throw new IdpUnavailableError(`flytedesk-id ${path} answered an unexpected body`);
79
+ return body;
80
+ }
81
+ async function fetchEntry(slug) {
82
+ const answer = await fetchAnswer(slug);
83
+ const spec = kinds[answer.kind];
84
+ if (!spec)
85
+ throw new ConnectionInvalidError(slug, `unknown kind "${answer.kind}"`);
86
+ for (const [name, setting] of Object.entries(spec.settings)) {
87
+ const value = answer.settings[name];
88
+ if (value === undefined && setting.optional)
89
+ continue;
90
+ if (typeof value !== setting.type) {
91
+ throw new ConnectionInvalidError(slug, `setting "${name}" must be a ${setting.type}`);
92
+ }
93
+ }
94
+ const decrypt = async (field, version, ciphertext) => {
95
+ try {
96
+ return await options.cipher.decrypt({
97
+ keyName: answer.keyName,
98
+ ciphertext,
99
+ aad: connectionAad({ appId: options.appId, connectionId: answer.connectionId, field, version }),
100
+ });
101
+ }
102
+ catch (err) {
103
+ throw new ConnectionInvalidError(slug, `secret "${field}" version ${version} could not be decrypted`, err);
104
+ }
105
+ };
106
+ const secrets = {};
107
+ const versions = {};
108
+ const previous = {};
109
+ for (const field of spec.secrets) {
110
+ const stored = answer.secrets[field];
111
+ if (!stored)
112
+ throw new ConnectionInvalidError(slug, `secret "${field}" is missing`);
113
+ secrets[field] = await decrypt(field, stored.version, stored.ciphertext);
114
+ versions[field] = stored.version;
115
+ if (stored.previous) {
116
+ const replacedAt = new Date(stored.previous.replacedAt);
117
+ if (Number.isNaN(replacedAt.getTime())) {
118
+ throw new ConnectionInvalidError(slug, `secret "${field}" has an invalid replacement time`);
119
+ }
120
+ previous[field] = { value: await decrypt(field, stored.previous.version, stored.previous.ciphertext), replacedAt };
121
+ }
122
+ }
123
+ const settings = Object.fromEntries(Object.entries(answer.settings).filter(([name]) => name in spec.settings));
124
+ return { kind: answer.kind, settings, secrets, versions, previous, fetchedAt: clock() };
125
+ }
126
+ /** Fetches and caches; a refusal drops the cached value. */
127
+ async function fetchAndStore(slug) {
128
+ const epoch = epochOf(slug);
129
+ try {
130
+ const entry = await fetchEntry(slug);
131
+ if (epochOf(slug) === epoch)
132
+ cache.set(slug, entry);
133
+ return entry;
134
+ }
135
+ catch (err) {
136
+ if (err instanceof ConnectionRefusedError) {
137
+ startNewEpoch(slug);
138
+ cache.delete(slug);
139
+ }
140
+ throw err;
141
+ }
142
+ }
143
+ function asOutage(slug, err) {
144
+ if (!(err instanceof IdpUnavailableError))
145
+ return err;
146
+ logger.error(`connections: reading "${slug}" failed (${err.name})`);
147
+ return new ConnectionOutageError(slug, err.message, err);
148
+ }
149
+ async function refreshWithFallback(slug) {
150
+ try {
151
+ return await fetchAndStore(slug);
152
+ }
153
+ catch (err) {
154
+ const stale = cache.get(slug);
155
+ const outage = asOutage(slug, err);
156
+ if (outage !== err && stale && clock() - stale.fetchedAt <= CONNECTION_STALE_LIMIT_MS)
157
+ return stale;
158
+ throw outage;
159
+ }
160
+ }
161
+ async function load(slug, fresh) {
162
+ if (fresh) {
163
+ startNewEpoch(slug);
164
+ try {
165
+ return await fetchAndStore(slug);
166
+ }
167
+ catch (err) {
168
+ throw asOutage(slug, err);
169
+ }
170
+ }
171
+ const cached = cache.get(slug);
172
+ if (cached && clock() - cached.fetchedAt < CONNECTION_CACHE_TTL_MS)
173
+ return cached;
174
+ let pending = inFlight.get(slug);
175
+ if (!pending) {
176
+ const refresh = refreshWithFallback(slug).finally(() => {
177
+ if (inFlight.get(slug) === refresh)
178
+ inFlight.delete(slug);
179
+ });
180
+ pending = refresh;
181
+ inFlight.set(slug, refresh);
182
+ }
183
+ return pending;
184
+ }
185
+ function copyOf(entry) {
186
+ return {
187
+ kind: entry.kind,
188
+ settings: { ...entry.settings },
189
+ secrets: { ...entry.secrets },
190
+ versions: { ...entry.versions },
191
+ previous: Object.fromEntries(Object.entries(entry.previous).map(([field, p]) => [field, { value: p.value, replacedAt: new Date(p.replacedAt) }])),
192
+ };
193
+ }
194
+ return {
195
+ async read(slug, readOptions) {
196
+ return copyOf(await load(slug, readOptions?.fresh === true));
197
+ },
198
+ async get(slug, kind, readOptions) {
199
+ const entry = await load(slug, readOptions?.fresh === true);
200
+ if (entry.kind !== kind)
201
+ throw new ConnectionKindMismatchError(slug, kind, entry.kind);
202
+ const { settings, secrets, previous } = copyOf(entry);
203
+ return { settings, secrets, previous };
204
+ },
205
+ };
206
+ }
207
+ function isRecord(value) {
208
+ return typeof value === "object" && value !== null && !Array.isArray(value);
209
+ }
210
+ function isAnswer(body) {
211
+ if (!isRecord(body))
212
+ return false;
213
+ if (typeof body.connectionId !== "string" || typeof body.kind !== "string" || typeof body.keyName !== "string") {
214
+ return false;
215
+ }
216
+ if (!isRecord(body.settings) || !isRecord(body.secrets))
217
+ return false;
218
+ return Object.values(body.secrets).every((s) => isRecord(s) &&
219
+ typeof s.version === "number" &&
220
+ typeof s.ciphertext === "string" &&
221
+ (s.previous === undefined ||
222
+ (isRecord(s.previous) &&
223
+ typeof s.previous.version === "number" &&
224
+ typeof s.previous.ciphertext === "string" &&
225
+ typeof s.previous.replacedAt === "string")));
226
+ }
227
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/connections/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAClF,OAAO,EAAE,8BAA8B,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/E,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEvG,OAAO,EACL,sBAAsB,EACtB,aAAa,EAEb,kBAAkB,GAGnB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,sBAAsB,EACtB,2BAA2B,EAC3B,qBAAqB,EACrB,sBAAsB,GAEvB,MAAM,aAA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E,EAAE,CACJ,QAAQ,CAAC,CAAC,CAAC;QACX,OAAO,CAAC,CAAC,OAAO,KAAK,QAAQ;QAC7B,OAAO,CAAC,CAAC,UAAU,KAAK,QAAQ;QAChC,CAAC,CAAC,CAAC,QAAQ,KAAK,SAAS;YACvB,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC;gBACnB,OAAO,CAAC,CAAC,QAAQ,CAAC,OAAO,KAAK,QAAQ;gBACtC,OAAO,CAAC,CAAC,QAAQ,CAAC,UAAU,KAAK,QAAQ;gBACzC,OAAO,CAAC,CAAC,QAAQ,CAAC,UAAU,KAAK,QAAQ,CAAC,CAAC,CAClD,CAAC;AACJ,CAAC"}
@@ -0,0 +1,63 @@
1
+ /** `GET {issuer}{path}`: one connection of one app. */
2
+ export declare function connectionReadPath(appId: string, slug: string): string;
3
+ /** The `error` of a 4xx refusal's JSON body (`{error: <code>}`). */
4
+ export declare const CONNECTION_ERROR_CODES: {
5
+ readonly disabled: "connection_disabled";
6
+ readonly valueNotSet: "connection_value_not_set";
7
+ readonly noPermission: "connection_no_permission";
8
+ readonly unknown: "connection_not_found";
9
+ };
10
+ export type ConnectionErrorCode = (typeof CONNECTION_ERROR_CODES)[keyof typeof CONNECTION_ERROR_CODES];
11
+ /** One secret field as stored: the key version that encrypted it and the base64 ciphertext. */
12
+ export interface ConnectionSecretWire {
13
+ version: number;
14
+ ciphertext: string;
15
+ /** The earlier version of this field, when it has one. */
16
+ previous?: {
17
+ version: number;
18
+ ciphertext: string;
19
+ /** ISO 8601 time the earlier version was replaced. */
20
+ replacedAt: string;
21
+ };
22
+ }
23
+ /** The read route's 200 answer. */
24
+ export interface ConnectionReadAnswer {
25
+ connectionId: string;
26
+ kind: string;
27
+ settings: Record<string, string | number>;
28
+ /** The Cloud KMS key's resource name (without a version) the secrets were encrypted with. */
29
+ keyName: string;
30
+ secrets: Record<string, ConnectionSecretWire>;
31
+ }
32
+ /** The additional authenticated data a secret field is encrypted under. */
33
+ export declare function connectionAad(parts: {
34
+ appId: string;
35
+ connectionId: string;
36
+ field: string;
37
+ version: number;
38
+ }): string;
39
+ /** The `typ` header of the token flytedesk ID signs to ask an app to test a connection. */
40
+ export declare const CONNECTION_TEST_TOKEN_TYP = "connection-test+jwt";
41
+ /** The algorithm flytedesk ID signs the token with (its provider key). */
42
+ export declare const CONNECTION_TEST_TOKEN_ALG = "RS256";
43
+ /** The value of the token's `kind` claim. */
44
+ export declare const CONNECTION_TEST_KIND = "connection-test";
45
+ /** The token's claim names; `iss` is flytedesk ID's issuer and `aud` the app id. The token
46
+ * names the connection, not a version: the answer reports the versions the app read. */
47
+ export declare const CONNECTION_TEST_CLAIMS: {
48
+ readonly kind: "fd_kind";
49
+ readonly connection: "fd_connection";
50
+ };
51
+ /** The test request: `Authorization: Bearer <connection-test token>` and this JSON body. */
52
+ export interface ConnectionTestRequestBody {
53
+ slug: string;
54
+ }
55
+ /** What a kind's tester reports; `detail` never holds a secret. */
56
+ export interface ConnectionTestResult {
57
+ ok: boolean;
58
+ detail: string;
59
+ }
60
+ /** The test answer: the tester's result and the version of each secret field the app tested. */
61
+ export interface ConnectionTestAnswer extends ConnectionTestResult {
62
+ tested: Record<string, number>;
63
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The wire contract between flytedesk ID and an app's connections client, in one place:
3
+ * the read route's answer, a refusal's error codes, the string that binds a ciphertext to
4
+ * its field, and the connection-test request flytedesk ID sends an app. The client
5
+ * (`./client.ts`), the test handler (`./testHandler.ts`) and flytedesk ID's server all read
6
+ * these names from here, so the sides can never drift apart.
7
+ *
8
+ * Constants, types and two builders; the only import is serviceTokenContract's claim name.
9
+ */
10
+ import { SERVICE_TOKEN_KIND_CLAIM } from "../auth/serviceTokenContract.js";
11
+ /** `GET {issuer}{path}`: one connection of one app. */
12
+ export function connectionReadPath(appId, slug) {
13
+ return `/apps/${encodeURIComponent(appId)}/connections/${encodeURIComponent(slug)}`;
14
+ }
15
+ /** The `error` of a 4xx refusal's JSON body (`{error: <code>}`). */
16
+ export const CONNECTION_ERROR_CODES = {
17
+ disabled: "connection_disabled",
18
+ valueNotSet: "connection_value_not_set",
19
+ noPermission: "connection_no_permission",
20
+ unknown: "connection_not_found",
21
+ };
22
+ /** The additional authenticated data a secret field is encrypted under. */
23
+ export function connectionAad(parts) {
24
+ return `flytedesk-id:connection:${parts.appId}:${parts.connectionId}:${parts.field}:${parts.version}`;
25
+ }
26
+ /** The `typ` header of the token flytedesk ID signs to ask an app to test a connection. */
27
+ export const CONNECTION_TEST_TOKEN_TYP = "connection-test+jwt";
28
+ /** The algorithm flytedesk ID signs the token with (its provider key). */
29
+ export const CONNECTION_TEST_TOKEN_ALG = "RS256";
30
+ /** The value of the token's `kind` claim. */
31
+ export const CONNECTION_TEST_KIND = "connection-test";
32
+ /** The token's claim names; `iss` is flytedesk ID's issuer and `aud` the app id. The token
33
+ * names the connection, not a version: the answer reports the versions the app read. */
34
+ export const CONNECTION_TEST_CLAIMS = {
35
+ kind: SERVICE_TOKEN_KIND_CLAIM,
36
+ connection: "fd_connection",
37
+ };
38
+ //# sourceMappingURL=contract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract.js","sourceRoot":"","sources":["../../src/connections/contract.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAE3E,uDAAuD;AACvD,MAAM,UAAU,kBAAkB,CAAC,KAAa,EAAE,IAAY;IAC5D,OAAO,SAAS,kBAAkB,CAAC,KAAK,CAAC,gBAAgB,kBAAkB,CAAC,IAAI,CAAC,EAAE,CAAC;AACtF,CAAC;AAED,oEAAoE;AACpE,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACpC,QAAQ,EAAE,qBAAqB;IAC/B,WAAW,EAAE,0BAA0B;IACvC,YAAY,EAAE,0BAA0B;IACxC,OAAO,EAAE,sBAAsB;CACvB,CAAC;AA2BX,2EAA2E;AAC3E,MAAM,UAAU,aAAa,CAAC,KAK7B;IACC,OAAO,2BAA2B,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;AACxG,CAAC;AAED,2FAA2F;AAC3F,MAAM,CAAC,MAAM,yBAAyB,GAAG,qBAAqB,CAAC;AAE/D,0EAA0E;AAC1E,MAAM,CAAC,MAAM,yBAAyB,GAAG,OAAO,CAAC;AAEjD,6CAA6C;AAC7C,MAAM,CAAC,MAAM,oBAAoB,GAAG,iBAAiB,CAAC;AAEtD;yFACyF;AACzF,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACpC,IAAI,EAAE,wBAAwB;IAC9B,UAAU,EAAE,eAAe;CACnB,CAAC"}
@@ -0,0 +1,36 @@
1
+ import type { ConnectionErrorCode } from "./contract.js";
2
+ /** Why flytedesk ID refused a read: a contract error code, or `unknown` for any other 4xx. */
3
+ export type ConnectionRefusalCause = "disabled" | "value not set" | "no permission" | "unknown";
4
+ /** Base of every error the connections module raises. Messages name the connection and the
5
+ * cause, never a value. */
6
+ export declare class ConnectionError extends Error {
7
+ readonly cause?: unknown | undefined;
8
+ constructor(message: string, cause?: unknown | undefined);
9
+ }
10
+ /** flytedesk ID refused the read (a 4xx, or a refused service token): retrying will not help. */
11
+ export declare class ConnectionRefusedError extends ConnectionError {
12
+ readonly slug: string;
13
+ readonly reason: ConnectionRefusalCause;
14
+ readonly code: ConnectionErrorCode | undefined;
15
+ constructor(slug: string, reason: ConnectionRefusalCause, code: ConnectionErrorCode | undefined, cause?: unknown);
16
+ }
17
+ /** flytedesk ID could not be reached (or answered 5xx/429/garbage) and no usable value is cached. */
18
+ export declare class ConnectionOutageError extends ConnectionError {
19
+ readonly slug: string;
20
+ constructor(slug: string, detail: string, cause?: unknown);
21
+ }
22
+ /** The connection exists but is not of the kind the caller asked for. */
23
+ export declare class ConnectionKindMismatchError extends ConnectionError {
24
+ readonly slug: string;
25
+ readonly expected: string;
26
+ readonly actual: string;
27
+ constructor(slug: string, expected: string, actual: string);
28
+ }
29
+ /** The answer did not match the kind's declared fields, or a secret could not be decrypted. */
30
+ export declare class ConnectionInvalidError extends ConnectionError {
31
+ readonly slug: string;
32
+ constructor(slug: string, detail: string, cause?: unknown);
33
+ }
34
+ /** A cipher could not encrypt or decrypt a value; the message names the key, never a value. */
35
+ export declare class ConnectionCipherError extends ConnectionError {
36
+ }
@@ -0,0 +1,54 @@
1
+ /** Base of every error the connections module raises. Messages name the connection and the
2
+ * cause, never a value. */
3
+ export class ConnectionError extends Error {
4
+ cause;
5
+ constructor(message, cause) {
6
+ super(message);
7
+ this.cause = cause;
8
+ this.name = new.target.name;
9
+ }
10
+ }
11
+ /** flytedesk ID refused the read (a 4xx, or a refused service token): retrying will not help. */
12
+ export class ConnectionRefusedError extends ConnectionError {
13
+ slug;
14
+ reason;
15
+ code;
16
+ constructor(slug, reason, code, cause) {
17
+ super(`connection "${slug}" cannot be read: ${reason}`, cause);
18
+ this.slug = slug;
19
+ this.reason = reason;
20
+ this.code = code;
21
+ }
22
+ }
23
+ /** flytedesk ID could not be reached (or answered 5xx/429/garbage) and no usable value is cached. */
24
+ export class ConnectionOutageError extends ConnectionError {
25
+ slug;
26
+ constructor(slug, detail, cause) {
27
+ super(`connection "${slug}" cannot be read: flytedesk ID is unavailable (${detail})`, cause);
28
+ this.slug = slug;
29
+ }
30
+ }
31
+ /** The connection exists but is not of the kind the caller asked for. */
32
+ export class ConnectionKindMismatchError extends ConnectionError {
33
+ slug;
34
+ expected;
35
+ actual;
36
+ constructor(slug, expected, actual) {
37
+ super(`connection "${slug}" is a "${actual}" connection, not "${expected}"`);
38
+ this.slug = slug;
39
+ this.expected = expected;
40
+ this.actual = actual;
41
+ }
42
+ }
43
+ /** The answer did not match the kind's declared fields, or a secret could not be decrypted. */
44
+ export class ConnectionInvalidError extends ConnectionError {
45
+ slug;
46
+ constructor(slug, detail, cause) {
47
+ super(`connection "${slug}" is unusable: ${detail}`, cause);
48
+ this.slug = slug;
49
+ }
50
+ }
51
+ /** A cipher could not encrypt or decrypt a value; the message names the key, never a value. */
52
+ export class ConnectionCipherError extends ConnectionError {
53
+ }
54
+ //# sourceMappingURL=errors.js.map