@lepistabioinformatics/mycelium-sdk 2.0.0 → 2.1.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.
@@ -1,4 +1,6 @@
1
+ import { IncomingMessage } from 'node:http';
1
2
  import { z } from 'zod';
3
+ import { KeyObject } from 'node:crypto';
2
4
 
3
5
  declare const KNOWN_KEYS: readonly ["phone_number", "telegram_user", "whatsapp_user", "locale"];
4
6
  type AccountMetaKey = (typeof KNOWN_KEYS)[number] | `custom:${string}`;
@@ -6,15 +8,6 @@ declare const AccountMetaKeySchema: z.ZodEffects<z.ZodString, AccountMetaKey, st
6
8
  declare const ProfileMetaSchema: z.ZodRecord<z.ZodEffects<z.ZodString, AccountMetaKey, string>, z.ZodString>;
7
9
  type ProfileMeta = z.infer<typeof ProfileMetaSchema>;
8
10
 
9
- declare const Permission: {
10
- readonly READ: 0;
11
- readonly WRITE: 1;
12
- };
13
- type Permission = (typeof Permission)[keyof typeof Permission];
14
- declare const PermissionSchema: z.ZodType<Permission>;
15
- declare function permissionToInt(permission: Permission): number;
16
- declare function permissionFromInt(value: number): Permission;
17
-
18
11
  declare const LicensedResourceSchema: z.ZodObject<{
19
12
  accId: z.ZodString;
20
13
  sysAcc: z.ZodBoolean;
@@ -22,7 +15,7 @@ declare const LicensedResourceSchema: z.ZodObject<{
22
15
  accName: z.ZodString;
23
16
  role: z.ZodString;
24
17
  roleId: z.ZodString;
25
- perm: z.ZodType<Permission, z.ZodTypeDef, Permission>;
18
+ perm: z.ZodUnion<[z.ZodLiteral<0>, z.ZodLiteral<1>, z.ZodEffects<z.ZodLiteral<"read">, 0, "read">, z.ZodEffects<z.ZodLiteral<"write">, 1, "write">]>;
26
19
  verified: z.ZodBoolean;
27
20
  permitFlags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
28
21
  denyFlags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
@@ -34,7 +27,7 @@ declare const LicensedResourceSchema: z.ZodObject<{
34
27
  accName: string;
35
28
  role: string;
36
29
  roleId: string;
37
- perm: Permission;
30
+ perm: 0 | 1;
38
31
  permitFlags?: string[] | undefined;
39
32
  denyFlags?: string[] | undefined;
40
33
  }, {
@@ -45,7 +38,7 @@ declare const LicensedResourceSchema: z.ZodObject<{
45
38
  accName: string;
46
39
  role: string;
47
40
  roleId: string;
48
- perm: Permission;
41
+ perm: 0 | 1 | "read" | "write";
49
42
  permitFlags?: string[] | undefined;
50
43
  denyFlags?: string[] | undefined;
51
44
  }>;
@@ -61,7 +54,7 @@ declare const LicensedResourcesSchema: z.ZodEffects<z.ZodDiscriminatedUnion<"kin
61
54
  accName: z.ZodString;
62
55
  role: z.ZodString;
63
56
  roleId: z.ZodString;
64
- perm: z.ZodType<Permission, z.ZodTypeDef, Permission>;
57
+ perm: z.ZodUnion<[z.ZodLiteral<0>, z.ZodLiteral<1>, z.ZodEffects<z.ZodLiteral<"read">, 0, "read">, z.ZodEffects<z.ZodLiteral<"write">, 1, "write">]>;
65
58
  verified: z.ZodBoolean;
66
59
  permitFlags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
67
60
  denyFlags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
@@ -73,7 +66,7 @@ declare const LicensedResourcesSchema: z.ZodEffects<z.ZodDiscriminatedUnion<"kin
73
66
  accName: string;
74
67
  role: string;
75
68
  roleId: string;
76
- perm: Permission;
69
+ perm: 0 | 1;
77
70
  permitFlags?: string[] | undefined;
78
71
  denyFlags?: string[] | undefined;
79
72
  }, {
@@ -84,7 +77,7 @@ declare const LicensedResourcesSchema: z.ZodEffects<z.ZodDiscriminatedUnion<"kin
84
77
  accName: string;
85
78
  role: string;
86
79
  roleId: string;
87
- perm: Permission;
80
+ perm: 0 | 1 | "read" | "write";
88
81
  permitFlags?: string[] | undefined;
89
82
  denyFlags?: string[] | undefined;
90
83
  }>, "many">;
@@ -97,7 +90,7 @@ declare const LicensedResourcesSchema: z.ZodEffects<z.ZodDiscriminatedUnion<"kin
97
90
  accName: string;
98
91
  role: string;
99
92
  roleId: string;
100
- perm: Permission;
93
+ perm: 0 | 1;
101
94
  permitFlags?: string[] | undefined;
102
95
  denyFlags?: string[] | undefined;
103
96
  }[];
@@ -111,7 +104,7 @@ declare const LicensedResourcesSchema: z.ZodEffects<z.ZodDiscriminatedUnion<"kin
111
104
  accName: string;
112
105
  role: string;
113
106
  roleId: string;
114
- perm: Permission;
107
+ perm: 0 | 1 | "read" | "write";
115
108
  permitFlags?: string[] | undefined;
116
109
  denyFlags?: string[] | undefined;
117
110
  }[];
@@ -134,7 +127,7 @@ declare const LicensedResourcesSchema: z.ZodEffects<z.ZodDiscriminatedUnion<"kin
134
127
  accName: string;
135
128
  role: string;
136
129
  roleId: string;
137
- perm: Permission;
130
+ perm: 0 | 1;
138
131
  permitFlags?: string[] | undefined;
139
132
  denyFlags?: string[] | undefined;
140
133
  }[];
@@ -146,6 +139,15 @@ declare const LicensedResourcesSchema: z.ZodEffects<z.ZodDiscriminatedUnion<"kin
146
139
  type LicensedResources = z.infer<typeof LicensedResourcesSchema>;
147
140
  declare function toLicensesVector(lr: LicensedResources | undefined): LicensedResource[];
148
141
 
142
+ declare const Permission: {
143
+ readonly READ: 0;
144
+ readonly WRITE: 1;
145
+ };
146
+ type Permission = (typeof Permission)[keyof typeof Permission];
147
+ declare const PermissionSchema: z.ZodUnion<[z.ZodLiteral<0>, z.ZodLiteral<1>, z.ZodEffects<z.ZodLiteral<"read">, 0, "read">, z.ZodEffects<z.ZodLiteral<"write">, 1, "write">]>;
148
+ declare function permissionToInt(permission: Permission): number;
149
+ declare function permissionFromInt(value: number): Permission;
150
+
149
151
  type RelatedAccounts = {
150
152
  kind: "AllowedAccounts";
151
153
  accounts: string[];
@@ -190,7 +192,7 @@ declare const ProfileSchema: z.ZodObject<{
190
192
  accountWasApproved: z.ZodBoolean;
191
193
  accountWasArchived: z.ZodBoolean;
192
194
  accountWasDeleted: z.ZodBoolean;
193
- verboseStatus: z.ZodOptional<z.ZodEnum<["unverified", "verified", "inactive", "archived", "deleted", "unknown"]>>;
195
+ verboseStatus: z.ZodOptional<z.ZodNullable<z.ZodEnum<["unverified", "verified", "inactive", "archived", "deleted", "unknown"]>>>;
194
196
  licensedResources: z.ZodOptional<z.ZodEffects<z.ZodDiscriminatedUnion<"kind", [z.ZodObject<{
195
197
  kind: z.ZodLiteral<"records">;
196
198
  records: z.ZodArray<z.ZodObject<{
@@ -200,7 +202,7 @@ declare const ProfileSchema: z.ZodObject<{
200
202
  accName: z.ZodString;
201
203
  role: z.ZodString;
202
204
  roleId: z.ZodString;
203
- perm: z.ZodType<Permission, z.ZodTypeDef, Permission>;
205
+ perm: z.ZodUnion<[z.ZodLiteral<0>, z.ZodLiteral<1>, z.ZodEffects<z.ZodLiteral<"read">, 0, "read">, z.ZodEffects<z.ZodLiteral<"write">, 1, "write">]>;
204
206
  verified: z.ZodBoolean;
205
207
  permitFlags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
206
208
  denyFlags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
@@ -212,7 +214,7 @@ declare const ProfileSchema: z.ZodObject<{
212
214
  accName: string;
213
215
  role: string;
214
216
  roleId: string;
215
- perm: Permission;
217
+ perm: 0 | 1;
216
218
  permitFlags?: string[] | undefined;
217
219
  denyFlags?: string[] | undefined;
218
220
  }, {
@@ -223,7 +225,7 @@ declare const ProfileSchema: z.ZodObject<{
223
225
  accName: string;
224
226
  role: string;
225
227
  roleId: string;
226
- perm: Permission;
228
+ perm: 0 | 1 | "read" | "write";
227
229
  permitFlags?: string[] | undefined;
228
230
  denyFlags?: string[] | undefined;
229
231
  }>, "many">;
@@ -236,7 +238,7 @@ declare const ProfileSchema: z.ZodObject<{
236
238
  accName: string;
237
239
  role: string;
238
240
  roleId: string;
239
- perm: Permission;
241
+ perm: 0 | 1;
240
242
  permitFlags?: string[] | undefined;
241
243
  denyFlags?: string[] | undefined;
242
244
  }[];
@@ -250,7 +252,7 @@ declare const ProfileSchema: z.ZodObject<{
250
252
  accName: string;
251
253
  role: string;
252
254
  roleId: string;
253
- perm: Permission;
255
+ perm: 0 | 1 | "read" | "write";
254
256
  permitFlags?: string[] | undefined;
255
257
  denyFlags?: string[] | undefined;
256
258
  }[];
@@ -273,7 +275,7 @@ declare const ProfileSchema: z.ZodObject<{
273
275
  accName: string;
274
276
  role: string;
275
277
  roleId: string;
276
- perm: Permission;
278
+ perm: 0 | 1;
277
279
  permitFlags?: string[] | undefined;
278
280
  denyFlags?: string[] | undefined;
279
281
  }[];
@@ -351,7 +353,7 @@ declare const ProfileSchema: z.ZodObject<{
351
353
  accountWasApproved: boolean;
352
354
  accountWasArchived: boolean;
353
355
  accountWasDeleted: boolean;
354
- verboseStatus?: "unknown" | "unverified" | "verified" | "inactive" | "archived" | "deleted" | undefined;
356
+ verboseStatus?: "unknown" | "unverified" | "verified" | "inactive" | "archived" | "deleted" | null | undefined;
355
357
  licensedResources?: {
356
358
  records: {
357
359
  verified: boolean;
@@ -361,7 +363,7 @@ declare const ProfileSchema: z.ZodObject<{
361
363
  accName: string;
362
364
  role: string;
363
365
  roleId: string;
364
- perm: Permission;
366
+ perm: 0 | 1;
365
367
  permitFlags?: string[] | undefined;
366
368
  denyFlags?: string[] | undefined;
367
369
  }[];
@@ -401,7 +403,7 @@ declare const ProfileSchema: z.ZodObject<{
401
403
  username?: string | undefined;
402
404
  }[] | undefined;
403
405
  isManager?: boolean | undefined;
404
- verboseStatus?: "unknown" | "unverified" | "verified" | "inactive" | "archived" | "deleted" | undefined;
406
+ verboseStatus?: "unknown" | "unverified" | "verified" | "inactive" | "archived" | "deleted" | null | undefined;
405
407
  licensedResources?: unknown;
406
408
  tenantsOwnership?: unknown;
407
409
  meta?: Record<string, string> | undefined;
@@ -460,4 +462,107 @@ declare class Profile {
460
462
  profileRedacted(): string;
461
463
  }
462
464
 
463
- export { type AccountMetaKey as A, type LicensedResource as L, Profile as P, type RelatedAccounts as R, AccountMetaKeySchema as a, LicensedResourceSchema as b, type LicensedResources as c, LicensedResourcesSchema as d, Permission as e, PermissionSchema as f, type ProfileData as g, type ProfileMeta as h, ProfileMetaSchema as i, ProfileSchema as j, permissionToInt as k, licensedResourceFromUrlString as l, permissionFromInt as p, toLicensesVector as t };
465
+ /** A key set read from the gateway, with how long it may be cached. */
466
+ interface FetchedProfileJwks {
467
+ keys: ReadonlyMap<string, KeyObject>;
468
+ maxAgeSeconds: number;
469
+ }
470
+ /** How the key store downloads the JWKS (HTTP in production, fakes in tests). */
471
+ type ProfileJwksFetcher = (url: URL) => Promise<FetchedProfileJwks>;
472
+ declare class ProfileJwksFetchError extends Error {
473
+ constructor(problem: string);
474
+ }
475
+ /**
476
+ * Download and parse the gateway profile JWKS over HTTP.
477
+ *
478
+ * Bounded: 5 s timeout, 64 KiB body, redirects never followed (a redirect
479
+ * could move the trust anchor to another origin). The cache lifetime comes
480
+ * from `Cache-Control: max-age` (see `readJwksCacheMaxAge`).
481
+ */
482
+ declare const fetchProfileJwks: ProfileJwksFetcher;
483
+
484
+ /** Milliseconds clock, injectable for tests. */
485
+ type MonotonicClock = () => number;
486
+ interface CachedProfileKeys {
487
+ keys: ReadonlyMap<string, KeyObject>;
488
+ generation: number;
489
+ }
490
+ /**
491
+ * The gateway public keys cached by a downstream verifier.
492
+ *
493
+ * - Fetched lazily on the first request (default) or before serving
494
+ * (`prefetch`, opt-in). Until a set is downloaded, requests fail closed and
495
+ * the fetch is retried at most every `PROFILE_JWKS_EMPTY_RETRY_SECONDS`, so
496
+ * a service started before the gateway recovers within seconds.
497
+ * - Refreshed when `max-age` expires; a failed refresh keeps the last valid
498
+ * set and logs a warning, so a short gateway outage never drops trusted
499
+ * keys. The set stops being trusted `PROFILE_JWKS_MAX_STALE_SECONDS` after
500
+ * it expired, so a retired key cannot verify forever while refreshes fail.
501
+ * - A request never waits for a refresh another request already started
502
+ * while keys are cached: it verifies with the cached set.
503
+ * - Refetched once when a signature names an unknown `kid`, at most once per
504
+ * cooldown (measured from the end of the last attempt), and single-flight:
505
+ * concurrent requests share one fetch, and waiters that see a newer
506
+ * generation reuse it without fetching again.
507
+ */
508
+ declare class ProfileKeyStore {
509
+ #private;
510
+ constructor(url: URL, fetcher: ProfileJwksFetcher, cooldownSeconds: number, clock?: MonotonicClock);
511
+ get url(): URL;
512
+ /** The trusted keys now, and the generation they belong to. */
513
+ current(): CachedProfileKeys;
514
+ /** Fetch the set now; any failure rejects (startup must abort). */
515
+ prefetch(): Promise<void>;
516
+ /** Refresh when the cached set expired (or was never fetched). */
517
+ refreshIfStale(): Promise<void>;
518
+ /** Refetch after an unknown `kid`; `true` when newer keys are available. */
519
+ refreshAfterUnknownKey(seenGeneration: number): Promise<boolean>;
520
+ }
521
+
522
+ /**
523
+ * Downstream verifier whose trusted keys come from the gateway JWKS.
524
+ *
525
+ * Enabled by `MYCELIUM_JWKS_URL`; the expected audience is mandatory, so a
526
+ * signed pair issued for another service is always refused. Verification is
527
+ * the shared, local contract; only the keys are remote, refreshed as
528
+ * described in `ProfileKeyStore`. Build it with
529
+ * `prepareProfileSignatureVerifier()` (downloads the keys before serving) or
530
+ * `loadProfileSignatureVerifierFromEnv()` (keys fetched on first use).
531
+ */
532
+ declare class JwksProfileSignatureVerifier {
533
+ #private;
534
+ readonly store: ProfileKeyStore;
535
+ readonly toleranceSeconds: number;
536
+ readonly expectedAudience: string;
537
+ constructor(store: ProfileKeyStore, toleranceSeconds: number, expectedAudience: string);
538
+ /** Download the key set before serving; rejects when it cannot. */
539
+ prefetch(): Promise<void>;
540
+ /**
541
+ * Verify the signed profile, refetching the JWKS once on an unknown,
542
+ * canonical `kid`. Rejects with `ProfileSignatureError` like
543
+ * `verifyAndDecodeProfile`.
544
+ */
545
+ verifyAndDecode(profileHeader: string, signatureHeader: string, nowSeconds?: number): Promise<Profile>;
546
+ }
547
+
548
+ declare const SIGNATURE_REJECTION_DETAIL = "Unable to verify Mycelium profile";
549
+ declare const SIGNATURE_INTERNAL_DETAIL = "Unable to check user identity. Please contact administrators";
550
+ /** Log-safe reason only. Result ignored; returned promises are awaited safely. */
551
+ type SignatureRejectionListener = (reason: string) => unknown;
552
+ type SignatureVerificationOutcome = {
553
+ ok: true;
554
+ profile: Profile;
555
+ } | {
556
+ ok: false;
557
+ status: 403 | 500;
558
+ detail: string;
559
+ };
560
+ /**
561
+ * Authenticate and decode the profile carried by a request.
562
+ *
563
+ * Never throws: rejections map to 403, anything unexpected to 500, both with
564
+ * generic details. The caller must not run the handler unless `ok`.
565
+ */
566
+ declare function verifyRequestProfile(message: IncomingMessage, verifier: JwksProfileSignatureVerifier, onRejected?: SignatureRejectionListener): Promise<SignatureVerificationOutcome>;
567
+
568
+ export { type AccountMetaKey as A, type CachedProfileKeys as C, type FetchedProfileJwks as F, JwksProfileSignatureVerifier as J, type LicensedResource as L, type MonotonicClock as M, Profile as P, type RelatedAccounts as R, type SignatureRejectionListener as S, type ProfileJwksFetcher as a, AccountMetaKeySchema as b, LicensedResourceSchema as c, type LicensedResources as d, LicensedResourcesSchema as e, Permission as f, PermissionSchema as g, type ProfileData as h, ProfileJwksFetchError as i, ProfileKeyStore as j, type ProfileMeta as k, ProfileMetaSchema as l, ProfileSchema as m, SIGNATURE_INTERNAL_DETAIL as n, SIGNATURE_REJECTION_DETAIL as o, type SignatureVerificationOutcome as p, fetchProfileJwks as q, licensedResourceFromUrlString as r, permissionFromInt as s, permissionToInt as t, toLicensesVector as u, verifyRequestProfile as v };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lepistabioinformatics/mycelium-sdk",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "Mycelium SDK for Node.js/TypeScript backends — decode the x-mycelium-profile header and enforce tenant/account/role authorization with a fluent, typed API",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -38,6 +38,7 @@
38
38
  "prepublishOnly": "yarn build"
39
39
  },
40
40
  "dependencies": {
41
+ "jose": "^6.2.12",
41
42
  "zod": "^3.24.0"
42
43
  },
43
44
  "peerDependencies": {
@@ -57,7 +58,7 @@
57
58
  "@types/node": "^24.0.0",
58
59
  "@types/supertest": "^6.0.2",
59
60
  "eslint": "^9.15.0",
60
- "fastify": "^4.28.0",
61
+ "fastify": "^5.8.5",
61
62
  "fastify-plugin": "^5.0.1",
62
63
  "express": "^4.21.0",
63
64
  "prettier": "^3.4.0",