@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.
@@ -0,0 +1,1390 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __commonJS = (cb, mod) => function __require() {
8
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
+ // If the importer is in node compatibility mode or this is not an ESM
20
+ // file that has been converted to a CommonJS file using a Babel-
21
+ // compatible transform (i.e. "__esModule" has not been set), then set
22
+ // "default" to the CommonJS "module.exports" for node compatibility.
23
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
+ mod
25
+ ));
26
+
27
+ // src/errors.ts
28
+ var MyceliumError = class extends Error {
29
+ code;
30
+ expTrue;
31
+ constructor(message, code, expTrue = false) {
32
+ super(message);
33
+ this.name = "MyceliumError";
34
+ this.code = code;
35
+ this.expTrue = expTrue;
36
+ }
37
+ };
38
+ var InsufficientPrivilegesError = class extends MyceliumError {
39
+ filteringState;
40
+ constructor(message, filteringState = []) {
41
+ super(message, "MYC00019", true);
42
+ this.name = "InsufficientPrivilegesError";
43
+ this.filteringState = filteringState;
44
+ }
45
+ };
46
+ var InsufficientLicensesError = class extends MyceliumError {
47
+ constructor(message = "Insufficient licenses to perform these action") {
48
+ super(message, "MYC00019", true);
49
+ this.name = "InsufficientLicensesError";
50
+ }
51
+ };
52
+ var ProfileDecodingError = class extends MyceliumError {
53
+ constructor(message) {
54
+ super(message, "MYC00020", false);
55
+ this.name = "ProfileDecodingError";
56
+ }
57
+ };
58
+ var PROFILE_SIGNATURE_INVALID_CODE = "MYC_PROFILE_SIGNATURE_INVALID";
59
+ var PROFILE_SIGNATURE_CONFIG_INVALID_CODE = "MYC_PROFILE_SIGNATURE_CONFIG_INVALID";
60
+ var ProfileSignatureConfigurationError = class extends MyceliumError {
61
+ constructor(message) {
62
+ super(message, PROFILE_SIGNATURE_CONFIG_INVALID_CODE, false);
63
+ this.name = "ProfileSignatureConfigurationError";
64
+ }
65
+ };
66
+ var ProfileSignatureError = class extends MyceliumError {
67
+ reason;
68
+ constructor(reason) {
69
+ super(`Profile signature rejected: ${reason}`, PROFILE_SIGNATURE_INVALID_CODE, true);
70
+ this.name = "ProfileSignatureError";
71
+ this.reason = reason;
72
+ }
73
+ };
74
+
75
+ // src/settings.ts
76
+ var DEFAULT_PROFILE_KEY = "x-mycelium-profile";
77
+ var DEFAULT_EMAIL_KEY = "x-mycelium-email";
78
+ var DEFAULT_SCOPE_KEY = "x-mycelium-scope";
79
+ var DEFAULT_MYCELIUM_ROLE_KEY = "x-mycelium-role";
80
+ var DEFAULT_REQUEST_ID_KEY = "x-mycelium-request-id";
81
+ var DEFAULT_CONNECTION_STRING_KEY = "x-mycelium-connection-string";
82
+ var DEFAULT_TENANT_ID_KEY = "x-mycelium-tenant-id";
83
+ var DEFAULT_PROFILE_SIGNATURE_KEY = "x-mycelium-profile-signature";
84
+ var PROFILE_JWKS_URL_ENV = "MYCELIUM_JWKS_URL";
85
+ var PROFILE_JWKS_ALLOW_INSECURE_HTTP_ENV = "MYCELIUM_JWKS_ALLOW_INSECURE_HTTP";
86
+ var PROFILE_JWKS_PATH = "/.well-known/mycelium-profile-jwks.json";
87
+ var PROFILE_JWKS_FETCH_TIMEOUT_SECONDS = 5;
88
+ var PROFILE_JWKS_MAX_BYTES = 64 * 1024;
89
+ var PROFILE_JWKS_REFETCH_COOLDOWN_SECONDS = 30;
90
+ var PROFILE_JWKS_EMPTY_RETRY_SECONDS = 5;
91
+ var PROFILE_JWKS_DEFAULT_MAX_AGE_SECONDS = 43200;
92
+ var PROFILE_JWKS_MIN_MAX_AGE_SECONDS = 60;
93
+ var PROFILE_JWKS_MAX_MAX_AGE_SECONDS = 86400;
94
+ var PROFILE_JWKS_MAX_STALE_SECONDS = 86400;
95
+ var PROFILE_SIGNATURE_TOLERANCE_ENV = "MYC_PROFILE_SIGNATURE_TOLERANCE_SECONDS";
96
+ var PROFILE_SIGNATURE_AUDIENCE_ENV = "MYC_PROFILE_SIGNATURE_AUDIENCE";
97
+ var DEFAULT_PROFILE_SIGNATURE_TOLERANCE_SECONDS = 60;
98
+ var MAX_PROFILE_SIGNATURE_TOLERANCE_SECONDS = 300;
99
+ var MAX_PROFILE_SIGNATURE_BYTES = 4096;
100
+
101
+ // src/models/permission.ts
102
+ import { z } from "zod";
103
+ var Permission = {
104
+ READ: 0,
105
+ WRITE: 1
106
+ };
107
+ var PermissionSchema = z.union([
108
+ z.literal(0),
109
+ z.literal(1),
110
+ // Rust serializes Permission with serde rename_all = camelCase.
111
+ z.literal("read").transform(() => Permission.READ),
112
+ z.literal("write").transform(() => Permission.WRITE)
113
+ ]);
114
+ function permissionToInt(permission) {
115
+ return permission;
116
+ }
117
+ function permissionFromInt(value) {
118
+ if (value === Permission.READ || value === Permission.WRITE) {
119
+ return value;
120
+ }
121
+ throw new Error(`Invalid permission code: ${value}`);
122
+ }
123
+
124
+ // src/models/verboseStatus.ts
125
+ import { z as z2 } from "zod";
126
+ var VerboseStatusSchema = z2.enum([
127
+ "unverified",
128
+ "verified",
129
+ "inactive",
130
+ "archived",
131
+ "deleted",
132
+ "unknown"
133
+ ]);
134
+
135
+ // src/models/accountMetaKey.ts
136
+ import { z as z3 } from "zod";
137
+ var KNOWN_KEYS = [
138
+ "phone_number",
139
+ "telegram_user",
140
+ "whatsapp_user",
141
+ "locale"
142
+ ];
143
+ var AccountMetaKeySchema = z3.string().refine(
144
+ (value) => KNOWN_KEYS.includes(value) || value.startsWith("custom:"),
145
+ {
146
+ message: "must be one of phone_number, telegram_user, whatsapp_user, locale, or a custom:<key> string"
147
+ }
148
+ );
149
+ var ProfileMetaSchema = z3.record(AccountMetaKeySchema, z3.string());
150
+
151
+ // src/models/owner.ts
152
+ import { z as z4 } from "zod";
153
+ var OwnerSchema = z4.object({
154
+ id: z4.string().uuid(),
155
+ email: z4.string(),
156
+ firstName: z4.string().optional(),
157
+ lastName: z4.string().optional(),
158
+ username: z4.string().optional(),
159
+ isPrincipal: z4.boolean()
160
+ });
161
+
162
+ // src/models/licensedResource.ts
163
+ import { z as z5 } from "zod";
164
+ var LicensedResourceSchema = z5.object({
165
+ accId: z5.string().uuid(),
166
+ sysAcc: z5.boolean(),
167
+ tenantId: z5.string().uuid(),
168
+ accName: z5.string(),
169
+ role: z5.string(),
170
+ roleId: z5.string().uuid(),
171
+ perm: PermissionSchema,
172
+ verified: z5.boolean(),
173
+ permitFlags: z5.array(z5.string()).optional(),
174
+ denyFlags: z5.array(z5.string()).optional()
175
+ });
176
+ function licensedResourceFromUrlString(value) {
177
+ let url;
178
+ try {
179
+ url = new URL(value, "http://placeholder.local");
180
+ } catch {
181
+ throw new Error(`Invalid licensed resource URL string: ${value}`);
182
+ }
183
+ const segments = url.pathname.split("/").filter(Boolean);
184
+ if (segments.length !== 6 || segments[0] !== "t" || segments[2] !== "a" || segments[4] !== "r") {
185
+ throw new Error(`Invalid path format in licensed resource URL: ${value}`);
186
+ }
187
+ const tenantId = segments[1];
188
+ const accId = segments[3];
189
+ const roleId = segments[5];
190
+ const pParam = url.searchParams.get("p");
191
+ if (pParam === null) {
192
+ throw new Error(`Parameter 'p' not found in: ${value}`);
193
+ }
194
+ const sepIndex = pParam.lastIndexOf(":");
195
+ if (sepIndex === -1) {
196
+ throw new Error(`Invalid 'p' parameter format in: ${value}`);
197
+ }
198
+ const role = pParam.slice(0, sepIndex);
199
+ const perm = permissionFromInt(Number.parseInt(pParam.slice(sepIndex + 1), 10));
200
+ const sParam = url.searchParams.get("s");
201
+ const vParam = url.searchParams.get("v");
202
+ const nParam = url.searchParams.get("n");
203
+ if (sParam === null || vParam === null || nParam === null) {
204
+ throw new Error(`Missing 's'/'v'/'n' parameter in: ${value}`);
205
+ }
206
+ if (sParam !== "0" && sParam !== "1") {
207
+ throw new Error(`Invalid 's' parameter value in: ${value}`);
208
+ }
209
+ if (vParam !== "0" && vParam !== "1") {
210
+ throw new Error(`Invalid 'v' parameter value in: ${value}`);
211
+ }
212
+ const accName = Buffer.from(nParam, "base64").toString("utf-8");
213
+ const pfParam = url.searchParams.get("pf");
214
+ const dfParam = url.searchParams.get("df");
215
+ return LicensedResourceSchema.parse({
216
+ accId,
217
+ sysAcc: sParam === "1",
218
+ tenantId,
219
+ accName,
220
+ role,
221
+ roleId,
222
+ perm,
223
+ verified: vParam === "1",
224
+ permitFlags: pfParam ? pfParam.split(",") : void 0,
225
+ denyFlags: dfParam ? dfParam.split(",") : void 0
226
+ });
227
+ }
228
+
229
+ // src/models/licensedResources.ts
230
+ import { z as z6 } from "zod";
231
+ function tagRecordsOrUrls(raw) {
232
+ if (raw && typeof raw === "object") {
233
+ const obj = raw;
234
+ const hasRecords = "records" in obj;
235
+ const hasUrls = "urls" in obj;
236
+ if (hasRecords && !hasUrls) {
237
+ return { kind: "records", records: obj.records };
238
+ }
239
+ if (hasUrls && !hasRecords) {
240
+ return { kind: "urls", urls: obj.urls };
241
+ }
242
+ }
243
+ return raw;
244
+ }
245
+ var LicensedResourcesSchema = z6.preprocess(
246
+ tagRecordsOrUrls,
247
+ z6.discriminatedUnion("kind", [
248
+ z6.object({
249
+ kind: z6.literal("records"),
250
+ records: z6.array(LicensedResourceSchema)
251
+ }),
252
+ z6.object({
253
+ kind: z6.literal("urls"),
254
+ urls: z6.array(z6.string())
255
+ })
256
+ ])
257
+ );
258
+ function toLicensesVector(lr) {
259
+ if (!lr) return [];
260
+ if (lr.kind === "records") return lr.records;
261
+ return lr.urls.map(licensedResourceFromUrlString);
262
+ }
263
+
264
+ // src/models/tenantOwnership.ts
265
+ import { z as z7 } from "zod";
266
+ var TenantOwnershipSchema = z7.object({
267
+ id: z7.string().uuid(),
268
+ name: z7.string(),
269
+ since: z7.coerce.date()
270
+ });
271
+ function reinsertUuidHyphens(noHyphens) {
272
+ if (!/^[0-9a-fA-F]{32}$/.test(noHyphens)) {
273
+ throw new Error(`Invalid unhyphenated UUID: ${noHyphens}`);
274
+ }
275
+ return [
276
+ noHyphens.slice(0, 8),
277
+ noHyphens.slice(8, 12),
278
+ noHyphens.slice(12, 16),
279
+ noHyphens.slice(16, 20),
280
+ noHyphens.slice(20, 32)
281
+ ].join("-");
282
+ }
283
+ function tenantOwnershipFromUrlString(value) {
284
+ let url;
285
+ try {
286
+ url = new URL(value, "http://placeholder.local");
287
+ } catch {
288
+ throw new Error(`Invalid tenant ownership URL string: ${value}`);
289
+ }
290
+ const segments = url.pathname.split("/").filter(Boolean);
291
+ if (segments.length !== 2 || segments[0] !== "tid") {
292
+ throw new Error(`Invalid path format in tenant ownership URL: ${value}`);
293
+ }
294
+ const id = reinsertUuidHyphens(segments[1]);
295
+ const since = url.searchParams.get("since");
296
+ const nameEncoded = url.searchParams.get("name");
297
+ if (since === null || nameEncoded === null) {
298
+ throw new Error(`Missing 'since'/'name' parameter in: ${value}`);
299
+ }
300
+ const name = Buffer.from(nameEncoded, "base64").toString("utf-8");
301
+ return TenantOwnershipSchema.parse({ id, name, since });
302
+ }
303
+
304
+ // src/models/tenantsOwnership.ts
305
+ import { z as z8 } from "zod";
306
+ function tagRecordsOrUrls2(raw) {
307
+ if (raw && typeof raw === "object") {
308
+ const obj = raw;
309
+ const hasRecords = "records" in obj;
310
+ const hasUrls = "urls" in obj;
311
+ if (hasRecords && !hasUrls) {
312
+ return { kind: "records", records: obj.records };
313
+ }
314
+ if (hasUrls && !hasRecords) {
315
+ return { kind: "urls", urls: obj.urls };
316
+ }
317
+ }
318
+ return raw;
319
+ }
320
+ var TenantsOwnershipSchema = z8.preprocess(
321
+ tagRecordsOrUrls2,
322
+ z8.discriminatedUnion("kind", [
323
+ z8.object({
324
+ kind: z8.literal("records"),
325
+ records: z8.array(TenantOwnershipSchema)
326
+ }),
327
+ z8.object({
328
+ kind: z8.literal("urls"),
329
+ urls: z8.array(z8.string())
330
+ })
331
+ ])
332
+ );
333
+ function toOwnershipVector(to) {
334
+ if (!to) return [];
335
+ if (to.kind === "records") return to.records;
336
+ return to.urls.map(tenantOwnershipFromUrlString);
337
+ }
338
+
339
+ // src/models/profile.ts
340
+ import { z as z9 } from "zod";
341
+ var ProfileSchema = z9.object({
342
+ owners: z9.array(OwnerSchema).default([]),
343
+ accId: z9.string().uuid(),
344
+ isSubscription: z9.boolean(),
345
+ isStaff: z9.boolean(),
346
+ isManager: z9.boolean().default(false),
347
+ ownerIsActive: z9.boolean(),
348
+ accountIsActive: z9.boolean(),
349
+ accountWasApproved: z9.boolean(),
350
+ accountWasArchived: z9.boolean(),
351
+ accountWasDeleted: z9.boolean(),
352
+ verboseStatus: VerboseStatusSchema.nullish(),
353
+ licensedResources: LicensedResourcesSchema.optional(),
354
+ tenantsOwnership: TenantsOwnershipSchema.optional(),
355
+ meta: ProfileMetaSchema.optional(),
356
+ filteringState: z9.array(z9.string()).optional()
357
+ });
358
+ function appendState(current, entry) {
359
+ const state = current ?? [];
360
+ return [...state, `${state.length + 1}:${entry}`];
361
+ }
362
+ var Profile = class _Profile {
363
+ data;
364
+ constructor(data) {
365
+ this.data = data;
366
+ }
367
+ static fromValidated(data) {
368
+ return new _Profile(data);
369
+ }
370
+ get accId() {
371
+ return this.data.accId;
372
+ }
373
+ get owners() {
374
+ return this.data.owners;
375
+ }
376
+ get isStaff() {
377
+ return this.data.isStaff;
378
+ }
379
+ get isManager() {
380
+ return this.data.isManager;
381
+ }
382
+ get licensedResources() {
383
+ return this.data.licensedResources;
384
+ }
385
+ get tenantsOwnership() {
386
+ return this.data.tenantsOwnership;
387
+ }
388
+ get filteringState() {
389
+ return this.data.filteringState;
390
+ }
391
+ withData(partial) {
392
+ return new _Profile({ ...this.data, ...partial });
393
+ }
394
+ filterLicensedResources(predicate) {
395
+ const records = toLicensesVector(this.data.licensedResources).filter(
396
+ predicate
397
+ );
398
+ return records.length === 0 ? void 0 : { kind: "records", records };
399
+ }
400
+ withPermission(permission) {
401
+ if (!this.data.licensedResources) return this;
402
+ const licensedResources = this.filterLicensedResources(
403
+ (r) => permissionToInt(r.perm) >= permissionToInt(permission)
404
+ );
405
+ return this.withData({
406
+ licensedResources,
407
+ filteringState: appendState(
408
+ this.data.filteringState,
409
+ `permission:${permissionToInt(permission)}`
410
+ )
411
+ });
412
+ }
413
+ withReadAccess() {
414
+ return this.withPermission(Permission.READ);
415
+ }
416
+ withWriteAccess() {
417
+ return this.withPermission(Permission.WRITE);
418
+ }
419
+ onTenant(tenantId) {
420
+ const licensedResources = this.filterLicensedResources(
421
+ (r) => r.tenantId === tenantId
422
+ );
423
+ return this.withData({
424
+ licensedResources,
425
+ filteringState: appendState(
426
+ this.data.filteringState,
427
+ `tenantId:${tenantId}`
428
+ )
429
+ });
430
+ }
431
+ withRoles(roles) {
432
+ const licensedResources = this.filterLicensedResources(
433
+ (r) => roles.includes(r.role)
434
+ );
435
+ return this.withData({
436
+ licensedResources,
437
+ filteringState: appendState(
438
+ this.data.filteringState,
439
+ `role:${roles.join(",")}`
440
+ )
441
+ });
442
+ }
443
+ onAccount(accountId) {
444
+ const licensedResources = this.filterLicensedResources(
445
+ (r) => r.accId === accountId
446
+ );
447
+ return this.withData({
448
+ licensedResources,
449
+ filteringState: appendState(
450
+ this.data.filteringState,
451
+ `accountId:${accountId}`
452
+ )
453
+ });
454
+ }
455
+ hasPermitFlags(flags) {
456
+ const licensedResources = this.filterLicensedResources((r) => {
457
+ if (!r.permitFlags) return false;
458
+ return flags.every((f) => r.permitFlags?.includes(f));
459
+ });
460
+ return this.withData({
461
+ licensedResources,
462
+ filteringState: appendState(
463
+ this.data.filteringState,
464
+ `permittedFlags:${flags.join(",")}`
465
+ )
466
+ });
467
+ }
468
+ hasNotDenyFlags(flags) {
469
+ const licensedResources = this.filterLicensedResources((r) => {
470
+ if (!r.denyFlags) return true;
471
+ return !flags.some((f) => r.denyFlags?.includes(f));
472
+ });
473
+ return this.withData({
474
+ licensedResources,
475
+ filteringState: appendState(
476
+ this.data.filteringState,
477
+ `deniedFlags:${flags.join(",")}`
478
+ )
479
+ });
480
+ }
481
+ onTenantAsManager(tenantId, permission) {
482
+ const profile = this.onTenant(tenantId).withPermission(permission).withRoles(["tenant-manager"]);
483
+ return profile.withData({
484
+ filteringState: appendState(profile.data.filteringState, `isTenantManager:true`)
485
+ });
486
+ }
487
+ withSystemAccountsAccess() {
488
+ const licensedResources = this.filterLicensedResources((r) => r.sysAcc);
489
+ return this.withData({
490
+ licensedResources,
491
+ filteringState: appendState(
492
+ this.data.filteringState,
493
+ `isAccStd:true`
494
+ )
495
+ });
496
+ }
497
+ withTenantOwnershipOrError(tenantId) {
498
+ const tenants = toOwnershipVector(this.data.tenantsOwnership);
499
+ if (tenants.some((t) => t.id === tenantId)) {
500
+ return this.withData({
501
+ filteringState: appendState(
502
+ this.data.filteringState,
503
+ `tenantOwnership:${tenantId}`
504
+ )
505
+ });
506
+ }
507
+ throw new InsufficientPrivilegesError(
508
+ `Insufficient privileges to perform these action (no tenant ownership): ${(this.data.filteringState ?? []).join(", ")}`,
509
+ this.data.filteringState
510
+ );
511
+ }
512
+ hasAdminPrivileges() {
513
+ return this.data.isStaff || this.data.isManager;
514
+ }
515
+ hasAdminPrivilegesOrError() {
516
+ if (!this.hasAdminPrivileges()) {
517
+ throw new InsufficientPrivilegesError(
518
+ "Current account has no administration privileges",
519
+ this.data.filteringState
520
+ );
521
+ }
522
+ }
523
+ getIdsOrError() {
524
+ const ids = toLicensesVector(this.data.licensedResources).map(
525
+ (r) => r.accId
526
+ );
527
+ if (ids.length === 0 && !this.hasAdminPrivileges()) {
528
+ throw new InsufficientPrivilegesError(
529
+ `Insufficient privileges to perform these action (no ids): ${(this.data.filteringState ?? []).join(", ")}`,
530
+ this.data.filteringState
531
+ );
532
+ }
533
+ return ids;
534
+ }
535
+ getTenantWidePermissionOrError(tenantId, permission) {
536
+ if (this.data.isStaff) {
537
+ return { kind: "HasStaffPrivileges" };
538
+ }
539
+ if (this.data.isManager) {
540
+ return { kind: "HasManagerPrivileges" };
541
+ }
542
+ const tenants = toOwnershipVector(this.data.tenantsOwnership);
543
+ if (tenants.some((t) => t.id === tenantId)) {
544
+ return { kind: "HasTenantWidePrivileges", tenantId };
545
+ }
546
+ try {
547
+ this.onTenantAsManager(tenantId, permission).getIdsOrError();
548
+ return { kind: "HasTenantWidePrivileges", tenantId };
549
+ } catch {
550
+ }
551
+ throw new InsufficientPrivilegesError(
552
+ `Insufficient privileges to perform these action (no tenant wide permission): ${(this.data.filteringState ?? []).join(", ")}`,
553
+ this.data.filteringState
554
+ );
555
+ }
556
+ getRelatedAccountsOrTenantWidePermissionOrError(tenantId, permission) {
557
+ try {
558
+ return this.getTenantWidePermissionOrError(tenantId, permission);
559
+ } catch {
560
+ return this.getRelatedAccountOrError();
561
+ }
562
+ }
563
+ getRelatedAccountOrError() {
564
+ if (this.data.isStaff) {
565
+ return { kind: "HasStaffPrivileges" };
566
+ }
567
+ if (this.data.isManager) {
568
+ return { kind: "HasManagerPrivileges" };
569
+ }
570
+ if (this.data.licensedResources) {
571
+ const records = toLicensesVector(this.data.licensedResources);
572
+ if (records.length === 0) {
573
+ throw new InsufficientLicensesError();
574
+ }
575
+ return {
576
+ kind: "AllowedAccounts",
577
+ accounts: records.map((r) => r.accId)
578
+ };
579
+ }
580
+ throw new InsufficientPrivilegesError(
581
+ `Insufficient privileges to perform these action (no accounts): ${(this.data.filteringState ?? []).join(", ")}`,
582
+ this.data.filteringState
583
+ );
584
+ }
585
+ getOwnersIds() {
586
+ return this.data.owners.map((o) => o.id);
587
+ }
588
+ profileString() {
589
+ return `profile/${this.data.accId}`;
590
+ }
591
+ profileRedacted() {
592
+ const redactedEmails = this.data.owners.map((o) => redactEmail(o.email));
593
+ return `profile/${this.data.accId} owners: [${redactedEmails.join(", ")}]`;
594
+ }
595
+ };
596
+ function redactEmail(email) {
597
+ const [local, domain] = email.split("@");
598
+ if (!domain || !local) return email;
599
+ const visible = local.slice(0, 1);
600
+ return `${visible}${"*".repeat(Math.max(local.length - 1, 1))}@${domain}`;
601
+ }
602
+
603
+ // src/functions/decodeAndDecompressProfileFromBase64.ts
604
+ import { zstdCompressSync, zstdDecompressSync } from "zlib";
605
+ function decodeAndDecompressProfileFromBase64(input, opts = {}) {
606
+ const strict = opts.strict ?? true;
607
+ if (typeof input === "string" && input.length === 0 || Buffer.isBuffer(input) && input.length === 0) {
608
+ throw new ProfileDecodingError("Profile input is empty");
609
+ }
610
+ const inputBytes = Buffer.isBuffer(input) ? input : Buffer.from(input, "utf-8");
611
+ const base64Text = inputBytes.toString("utf-8");
612
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64Text) || base64Text.length % 4 !== 0) {
613
+ throw new ProfileDecodingError(
614
+ `Failed to decode base64 profile: not valid base64`
615
+ );
616
+ }
617
+ let decoded;
618
+ try {
619
+ decoded = Buffer.from(base64Text, "base64");
620
+ } catch (cause) {
621
+ throw new ProfileDecodingError(`Failed to decode base64 profile: ${cause}`);
622
+ }
623
+ let decompressed;
624
+ try {
625
+ decompressed = zstdDecompressSync(decoded);
626
+ } catch (cause) {
627
+ if (strict) {
628
+ throw new ProfileDecodingError(
629
+ `Failed to decompress zstd profile: ${cause}`
630
+ );
631
+ }
632
+ decompressed = decoded;
633
+ }
634
+ let profileString;
635
+ try {
636
+ profileString = decompressed.toString("utf-8");
637
+ } catch (cause) {
638
+ throw new ProfileDecodingError(
639
+ `Failed to convert decompressed profile to string: ${cause}`
640
+ );
641
+ }
642
+ let profileJson;
643
+ try {
644
+ profileJson = JSON.parse(profileString);
645
+ } catch (cause) {
646
+ throw new ProfileDecodingError(`Failed to deserialize profile: ${cause}`);
647
+ }
648
+ const result = ProfileSchema.safeParse(profileJson);
649
+ if (!result.success) {
650
+ throw new ProfileDecodingError(
651
+ `Failed to deserialize profile: ${formatZodError(result.error)}`
652
+ );
653
+ }
654
+ return Profile.fromValidated(result.data);
655
+ }
656
+ function safeDecodeAndDecompressProfileFromBase64(input, opts = {}) {
657
+ try {
658
+ const profile = decodeAndDecompressProfileFromBase64(input, opts);
659
+ return { success: true, profile };
660
+ } catch (error) {
661
+ if (error instanceof ProfileDecodingError) {
662
+ return { success: false, error };
663
+ }
664
+ return {
665
+ success: false,
666
+ error: new ProfileDecodingError(String(error))
667
+ };
668
+ }
669
+ }
670
+ function compressAndEncodeProfileToBase64(profile) {
671
+ const json = JSON.stringify(profile.data);
672
+ const compressed = zstdCompressSync(Buffer.from(json, "utf-8"));
673
+ return compressed.toString("base64");
674
+ }
675
+ function formatZodError(error) {
676
+ return error.issues.map((issue) => {
677
+ const path = issue.path.length > 0 ? issue.path.join(".") : "(root)";
678
+ return `field '${path}' ${issue.message}`;
679
+ }).join("; ");
680
+ }
681
+
682
+ // src/profileSignatureVerifier.ts
683
+ var CANONICAL_POSITIVE_INTEGER = /^[1-9][0-9]*$/;
684
+ var MAX_KEY_VERSION = 4294967295;
685
+ var ProfileSignatureVerifier = class {
686
+ #keys;
687
+ toleranceSeconds;
688
+ expectedAudience;
689
+ constructor(keys, toleranceSeconds, expectedAudience) {
690
+ this.#keys = new Map(keys);
691
+ this.toleranceSeconds = toleranceSeconds;
692
+ this.expectedAudience = expectedAudience;
693
+ Object.freeze(this);
694
+ }
695
+ keyFor(kid) {
696
+ return this.#keys.get(kid);
697
+ }
698
+ get keyVersions() {
699
+ return [...this.#keys.keys()].sort();
700
+ }
701
+ };
702
+ function isCanonicalKeyVersion(raw) {
703
+ return CANONICAL_POSITIVE_INTEGER.test(raw) && Number(raw) <= MAX_KEY_VERSION;
704
+ }
705
+
706
+ // src/functions/verifyProfileSignature.ts
707
+ import { createHash, timingSafeEqual } from "crypto";
708
+ import { compactVerify, errors as joseErrors } from "jose";
709
+ import { z as z10 } from "zod";
710
+ var FORBIDDEN_HEADER_MEMBERS = ["crit", "b64", "jku", "jwk", "x5u", "x5c"];
711
+ var ENCODED_DIGEST_LENGTH = 43;
712
+ function reject(reason) {
713
+ return new ProfileSignatureError(reason);
714
+ }
715
+ function isCanonicalHash(value) {
716
+ if (value.length !== ENCODED_DIGEST_LENGTH) return false;
717
+ const raw = Buffer.from(value, "base64url");
718
+ return raw.length === 32 && raw.toString("base64url") === value;
719
+ }
720
+ var claimsSchema = z10.object({
721
+ iat: z10.number().refine((value) => Number.isSafeInteger(value) && value >= 0),
722
+ ph: z10.string().refine(isCanonicalHash),
723
+ aud: z10.string().refine((value) => value.trim() !== "")
724
+ });
725
+ function decodeSegment(segment) {
726
+ try {
727
+ const value = JSON.parse(
728
+ Buffer.from(segment, "base64url").toString("utf8")
729
+ );
730
+ const isObject2 = typeof value === "object" && value !== null && !Array.isArray(value);
731
+ return isObject2 ? value : void 0;
732
+ } catch {
733
+ return void 0;
734
+ }
735
+ }
736
+ function splitToken(signatureHeader) {
737
+ if (signatureHeader === "") throw reject("missing_signature");
738
+ const parts = signatureHeader.split(".");
739
+ const oversized = Buffer.byteLength(signatureHeader, "utf8") > MAX_PROFILE_SIGNATURE_BYTES;
740
+ if (oversized || parts.length !== 3) throw reject("malformed_signature");
741
+ return parts;
742
+ }
743
+ function selectKey(header, verifier) {
744
+ if (header.alg !== "EdDSA") throw reject("unsupported_algorithm");
745
+ const hasForbidden = FORBIDDEN_HEADER_MEMBERS.some((member) => member in header);
746
+ if (hasForbidden) throw reject("malformed_signature");
747
+ const kid = header.kid;
748
+ const key = typeof kid === "string" && isCanonicalKeyVersion(kid) ? verifier.keyFor(kid) : void 0;
749
+ if (key === void 0) throw reject("unknown_key");
750
+ return key;
751
+ }
752
+ async function verifyJws(token, key) {
753
+ try {
754
+ const { payload } = await compactVerify(token, key, {
755
+ algorithms: ["EdDSA"]
756
+ });
757
+ return payload;
758
+ } catch (error) {
759
+ if (error instanceof joseErrors.JWSSignatureVerificationFailed) {
760
+ throw reject("invalid_signature");
761
+ }
762
+ throw reject("malformed_signature");
763
+ }
764
+ }
765
+ function parseClaims(payload) {
766
+ let decoded;
767
+ try {
768
+ decoded = JSON.parse(Buffer.from(payload).toString("utf8"));
769
+ } catch {
770
+ throw reject("invalid_claims");
771
+ }
772
+ const parsed = claimsSchema.safeParse(decoded);
773
+ if (!parsed.success) throw reject("invalid_claims");
774
+ return parsed.data;
775
+ }
776
+ function resolveNow(nowSeconds) {
777
+ const now = nowSeconds ?? Math.floor(Date.now() / 1e3);
778
+ if (!Number.isSafeInteger(now) || now < 0) {
779
+ throw new RangeError("Verifier clock is outside the safe integer range");
780
+ }
781
+ return now;
782
+ }
783
+ function profileHeaderHash(profileHeader) {
784
+ return createHash("sha256").update(profileHeader, "utf8").digest("base64url");
785
+ }
786
+ function sameHash(received, expected) {
787
+ const left = Buffer.from(received, "utf8");
788
+ const right = Buffer.from(expected, "utf8");
789
+ return left.length === right.length && timingSafeEqual(left, right);
790
+ }
791
+ function checkClaims(claims, profileHeader, verifier, now) {
792
+ if (Math.abs(now - claims.iat) > verifier.toleranceSeconds) {
793
+ throw reject("timestamp_out_of_tolerance");
794
+ }
795
+ if (!sameHash(claims.ph, profileHeaderHash(profileHeader))) {
796
+ throw reject("profile_hash_mismatch");
797
+ }
798
+ const expected = verifier.expectedAudience;
799
+ if (expected !== void 0 && claims.aud !== expected) {
800
+ throw reject("audience_mismatch");
801
+ }
802
+ }
803
+ async function verifyProfileSignature(profileHeader, signatureHeader, verifier, nowSeconds) {
804
+ if (profileHeader === "") throw reject("missing_profile");
805
+ const parts = splitToken(signatureHeader);
806
+ const header = decodeSegment(parts[0] ?? "");
807
+ if (header === void 0) throw reject("malformed_signature");
808
+ const key = selectKey(header, verifier);
809
+ const payload = await verifyJws(signatureHeader, key);
810
+ const claims = parseClaims(payload);
811
+ checkClaims(claims, profileHeader, verifier, resolveNow(nowSeconds));
812
+ }
813
+ async function verifyAndDecodeProfile(profileHeader, signatureHeader, verifier, nowSeconds) {
814
+ await verifyProfileSignature(profileHeader, signatureHeader, verifier, nowSeconds);
815
+ try {
816
+ return decodeAndDecompressProfileFromBase64(profileHeader);
817
+ } catch {
818
+ throw reject("invalid_profile");
819
+ }
820
+ }
821
+
822
+ // src/jwks/parseProfileJwks.ts
823
+ import { createPublicKey } from "crypto";
824
+ var JWKS = "profile JWKS";
825
+ var BASE64URL = /^[A-Za-z0-9_-]+$/;
826
+ var ED25519_PUBLIC_KEY_BYTES = 32;
827
+ function invalid(problem) {
828
+ return new ProfileSignatureConfigurationError(`${JWKS} ${problem}`);
829
+ }
830
+ function isObject(value) {
831
+ return typeof value === "object" && value !== null && !Array.isArray(value);
832
+ }
833
+ function expectMember(jwk, name, expected, required) {
834
+ if (!(name in jwk) && !required) return;
835
+ if (jwk[name] !== expected) {
836
+ throw invalid(`entry member ${name} must be ${expected}`);
837
+ }
838
+ }
839
+ function readKid(jwk) {
840
+ const kid = jwk.kid;
841
+ if (typeof kid !== "string" || !isCanonicalKeyVersion(kid)) {
842
+ throw invalid("entry kid must be a canonical positive integer");
843
+ }
844
+ return kid;
845
+ }
846
+ function readX(jwk) {
847
+ const x = jwk.x;
848
+ const isKey = typeof x === "string" && BASE64URL.test(x) && Buffer.from(x, "base64url").length === ED25519_PUBLIC_KEY_BYTES && Buffer.from(x, "base64url").toString("base64url") === x;
849
+ if (!isKey) throw invalid("entry x must be a 32-byte Base64URL key");
850
+ return x;
851
+ }
852
+ function importEntry(entry) {
853
+ if (!isObject(entry)) throw invalid("entry is not a JSON object");
854
+ if ("d" in entry) throw invalid("entry carries private key material (d)");
855
+ expectMember(entry, "kty", "OKP", true);
856
+ expectMember(entry, "crv", "Ed25519", true);
857
+ expectMember(entry, "use", "sig", false);
858
+ expectMember(entry, "alg", "EdDSA", false);
859
+ const kid = readKid(entry);
860
+ const x = readX(entry);
861
+ try {
862
+ const key = createPublicKey({
863
+ key: { kty: "OKP", crv: "Ed25519", x },
864
+ format: "jwk"
865
+ });
866
+ return [kid, key];
867
+ } catch {
868
+ throw invalid("entry x is not an Ed25519 key");
869
+ }
870
+ }
871
+ function parseProfileJwks(document) {
872
+ let parsed;
873
+ try {
874
+ parsed = JSON.parse(document);
875
+ } catch {
876
+ throw invalid("is not JSON");
877
+ }
878
+ const entries = isObject(parsed) ? parsed.keys : void 0;
879
+ if (!Array.isArray(entries) || entries.length === 0) {
880
+ throw invalid("has no keys array");
881
+ }
882
+ const keys = /* @__PURE__ */ new Map();
883
+ for (const entry of entries) {
884
+ const [kid, key] = importEntry(entry);
885
+ if (keys.has(kid)) throw invalid("has a duplicated kid");
886
+ keys.set(kid, key);
887
+ }
888
+ return keys;
889
+ }
890
+
891
+ // src/jwks/readJwksCacheMaxAge.ts
892
+ var UNSIGNED_INTEGER = /^\+?[0-9]+$/;
893
+ var U64_MAX = 18446744073709551615n;
894
+ function readMaxAgeDirective(directive) {
895
+ const separator = directive.indexOf("=");
896
+ if (separator < 0) return void 0;
897
+ const name = directive.slice(0, separator).trim().toLowerCase();
898
+ const value = directive.slice(separator + 1).trim();
899
+ if (name !== "max-age" || !UNSIGNED_INTEGER.test(value)) return void 0;
900
+ const seconds = BigInt(value);
901
+ if (seconds > U64_MAX) return void 0;
902
+ return seconds > BigInt(PROFILE_JWKS_MAX_MAX_AGE_SECONDS) ? PROFILE_JWKS_MAX_MAX_AGE_SECONDS : Number(seconds);
903
+ }
904
+ function readJwksCacheMaxAge(cacheControl) {
905
+ let announced;
906
+ for (const directive of (cacheControl ?? "").split(",")) {
907
+ announced = readMaxAgeDirective(directive);
908
+ if (announced !== void 0) break;
909
+ }
910
+ const seconds = announced ?? PROFILE_JWKS_DEFAULT_MAX_AGE_SECONDS;
911
+ return Math.min(
912
+ Math.max(seconds, PROFILE_JWKS_MIN_MAX_AGE_SECONDS),
913
+ PROFILE_JWKS_MAX_MAX_AGE_SECONDS
914
+ );
915
+ }
916
+
917
+ // src/jwks/fetchProfileJwks.ts
918
+ var ProfileJwksFetchError = class extends Error {
919
+ constructor(problem) {
920
+ super(`profile_jwks_fetch_failed: ${problem}`);
921
+ this.name = "ProfileJwksFetchError";
922
+ }
923
+ };
924
+ async function readBounded(response) {
925
+ const declared = Number(response.headers.get("content-length") ?? "0");
926
+ if (declared > PROFILE_JWKS_MAX_BYTES) {
927
+ throw new ProfileJwksFetchError("body exceeds the size limit");
928
+ }
929
+ const chunks = [];
930
+ let total = 0;
931
+ for await (const chunk of response.body ?? []) {
932
+ total += chunk.byteLength;
933
+ if (total > PROFILE_JWKS_MAX_BYTES) {
934
+ throw new ProfileJwksFetchError("body exceeds the size limit");
935
+ }
936
+ chunks.push(chunk);
937
+ }
938
+ return Buffer.concat(chunks).toString("utf8");
939
+ }
940
+ async function download(url) {
941
+ try {
942
+ return await fetch(url, {
943
+ method: "GET",
944
+ headers: { accept: "application/json" },
945
+ redirect: "manual",
946
+ signal: AbortSignal.timeout(PROFILE_JWKS_FETCH_TIMEOUT_SECONDS * 1e3)
947
+ });
948
+ } catch (error) {
949
+ const detail = error instanceof Error ? error.message : String(error);
950
+ throw new ProfileJwksFetchError(`request failed: ${detail}`);
951
+ }
952
+ }
953
+ var fetchProfileJwks = async (url) => {
954
+ const response = await download(url);
955
+ if (response.status < 200 || response.status > 299) {
956
+ await response.body?.cancel();
957
+ throw new ProfileJwksFetchError(`status ${response.status}`);
958
+ }
959
+ const maxAgeSeconds = readJwksCacheMaxAge(response.headers.get("cache-control"));
960
+ let body;
961
+ try {
962
+ body = await readBounded(response);
963
+ } catch (error) {
964
+ await response.body?.cancel().catch(() => void 0);
965
+ if (error instanceof ProfileJwksFetchError) throw error;
966
+ throw new ProfileJwksFetchError("body unreadable");
967
+ }
968
+ return { keys: parseProfileJwks(body), maxAgeSeconds };
969
+ };
970
+
971
+ // src/jwks/readSignatureKeyVersion.ts
972
+ function readSignatureKeyVersion(signatureHeader) {
973
+ const protectedHeader = signatureHeader.split(".")[0] ?? "";
974
+ try {
975
+ const header = JSON.parse(
976
+ Buffer.from(protectedHeader, "base64url").toString("utf8")
977
+ );
978
+ const kid = typeof header === "object" && header !== null ? header.kid : void 0;
979
+ return typeof kid === "string" && isCanonicalKeyVersion(kid) ? kid : void 0;
980
+ } catch {
981
+ return void 0;
982
+ }
983
+ }
984
+
985
+ // src/jwks/jwksProfileSignatureVerifier.ts
986
+ var JwksProfileSignatureVerifier = class {
987
+ store;
988
+ toleranceSeconds;
989
+ expectedAudience;
990
+ constructor(store, toleranceSeconds, expectedAudience) {
991
+ this.store = store;
992
+ this.toleranceSeconds = toleranceSeconds;
993
+ this.expectedAudience = expectedAudience;
994
+ Object.freeze(this);
995
+ }
996
+ /** Download the key set before serving; rejects when it cannot. */
997
+ prefetch() {
998
+ return this.store.prefetch();
999
+ }
1000
+ /**
1001
+ * Verify the signed profile, refetching the JWKS once on an unknown,
1002
+ * canonical `kid`. Rejects with `ProfileSignatureError` like
1003
+ * `verifyAndDecodeProfile`.
1004
+ */
1005
+ async verifyAndDecode(profileHeader, signatureHeader, nowSeconds) {
1006
+ await this.store.refreshIfStale();
1007
+ const { generation } = this.store.current();
1008
+ try {
1009
+ return await this.#verifyWithCurrentKeys(profileHeader, signatureHeader, nowSeconds);
1010
+ } catch (error) {
1011
+ const deservesRefetch = error instanceof ProfileSignatureError && error.reason === "unknown_key" && readSignatureKeyVersion(signatureHeader) !== void 0;
1012
+ if (!deservesRefetch) throw error;
1013
+ if (!await this.store.refreshAfterUnknownKey(generation)) throw error;
1014
+ }
1015
+ return this.#verifyWithCurrentKeys(profileHeader, signatureHeader, nowSeconds);
1016
+ }
1017
+ #verifyWithCurrentKeys(profileHeader, signatureHeader, nowSeconds) {
1018
+ const verifier = new ProfileSignatureVerifier(
1019
+ this.store.current().keys,
1020
+ this.toleranceSeconds,
1021
+ this.expectedAudience
1022
+ );
1023
+ return verifyAndDecodeProfile(profileHeader, signatureHeader, verifier, nowSeconds);
1024
+ }
1025
+ };
1026
+
1027
+ // src/jwks/parseProfileJwksUrl.ts
1028
+ function invalid2(problem) {
1029
+ return new ProfileSignatureConfigurationError(
1030
+ `${PROFILE_JWKS_URL_ENV} ${problem}`
1031
+ );
1032
+ }
1033
+ function withDefaultScheme(configured) {
1034
+ if (configured.includes("://")) return configured;
1035
+ if (configured === "" || configured.startsWith("/")) {
1036
+ throw invalid2("is not an absolute URL");
1037
+ }
1038
+ return `https://${configured}`;
1039
+ }
1040
+ function checkScheme(url, allowInsecureHttp) {
1041
+ if (url.protocol === "https:") return;
1042
+ if (url.protocol === "http:" && allowInsecureHttp) {
1043
+ console.warn(
1044
+ `[mycelium-sdk] ${PROFILE_JWKS_URL_ENV} uses plain HTTP; development only`
1045
+ );
1046
+ return;
1047
+ }
1048
+ throw invalid2("must use https");
1049
+ }
1050
+ function withJwksPath(url) {
1051
+ if (url.pathname.endsWith(PROFILE_JWKS_PATH)) return url;
1052
+ if (/[?#]/.test(url.href)) {
1053
+ throw invalid2("must not carry a query or fragment");
1054
+ }
1055
+ try {
1056
+ return new URL(`${url.href.replace(/\/+$/, "")}${PROFILE_JWKS_PATH}`);
1057
+ } catch {
1058
+ throw invalid2("is not an absolute URL");
1059
+ }
1060
+ }
1061
+ function parseProfileJwksUrl(raw, allowInsecureHttp) {
1062
+ let url;
1063
+ try {
1064
+ url = new URL(withDefaultScheme(raw.trim()));
1065
+ } catch (error) {
1066
+ if (error instanceof ProfileSignatureConfigurationError) throw error;
1067
+ throw invalid2("is not an absolute URL");
1068
+ }
1069
+ if (url.username !== "" || url.password !== "") {
1070
+ throw invalid2("must not carry credentials");
1071
+ }
1072
+ checkScheme(url, allowInsecureHttp);
1073
+ return withJwksPath(url);
1074
+ }
1075
+
1076
+ // src/jwks/profileKeyStore.ts
1077
+ var systemClock = () => performance.now();
1078
+ var ProfileKeyStore = class {
1079
+ #url;
1080
+ #fetcher;
1081
+ #cooldownMs;
1082
+ #clock;
1083
+ #keys = /* @__PURE__ */ new Map();
1084
+ #generation = 0;
1085
+ #freshUntil;
1086
+ #lastAttempt;
1087
+ #inFlight;
1088
+ constructor(url, fetcher, cooldownSeconds, clock = systemClock) {
1089
+ this.#url = url;
1090
+ this.#fetcher = fetcher;
1091
+ this.#cooldownMs = cooldownSeconds * 1e3;
1092
+ this.#clock = clock;
1093
+ }
1094
+ get url() {
1095
+ return new URL(this.#url);
1096
+ }
1097
+ /** The trusted keys now, and the generation they belong to. */
1098
+ current() {
1099
+ return { keys: this.#trustedKeys(), generation: this.#generation };
1100
+ }
1101
+ /** The cached keys, or none once they outlived the maximum staleness. */
1102
+ #trustedKeys() {
1103
+ const outlived = this.#freshUntil !== void 0 && this.#clock() >= this.#freshUntil + PROFILE_JWKS_MAX_STALE_SECONDS * 1e3;
1104
+ return outlived ? /* @__PURE__ */ new Map() : this.#keys;
1105
+ }
1106
+ /** Fetch the set now; any failure rejects (startup must abort). */
1107
+ async prefetch() {
1108
+ await this.#inFlight?.catch(() => void 0);
1109
+ const fetching = this.#fetchAndStore();
1110
+ this.#inFlight = fetching.then(
1111
+ () => true,
1112
+ () => false
1113
+ );
1114
+ try {
1115
+ await fetching;
1116
+ } finally {
1117
+ this.#inFlight = void 0;
1118
+ }
1119
+ }
1120
+ /** Refresh when the cached set expired (or was never fetched). */
1121
+ async refreshIfStale() {
1122
+ const stale = this.#freshUntil === void 0 || this.#clock() >= this.#freshUntil;
1123
+ if (!stale) return;
1124
+ if (this.#generation > 0 && this.#inFlight !== void 0) return;
1125
+ await this.#refreshFrom(this.#generation);
1126
+ }
1127
+ /** Refetch after an unknown `kid`; `true` when newer keys are available. */
1128
+ refreshAfterUnknownKey(seenGeneration) {
1129
+ return this.#refreshFrom(seenGeneration);
1130
+ }
1131
+ async #refreshFrom(seenGeneration) {
1132
+ while (this.#inFlight !== void 0) {
1133
+ await this.#inFlight.catch(() => void 0);
1134
+ }
1135
+ if (this.#generation !== seenGeneration) return true;
1136
+ const coolingDown = this.#lastAttempt !== void 0 && this.#clock() - this.#lastAttempt < this.#retryIntervalMs();
1137
+ if (coolingDown) return false;
1138
+ this.#inFlight = this.#fetchAndStore().then(
1139
+ () => true,
1140
+ (error) => {
1141
+ logRefreshFailure(error);
1142
+ return false;
1143
+ }
1144
+ );
1145
+ try {
1146
+ return await this.#inFlight;
1147
+ } finally {
1148
+ this.#inFlight = void 0;
1149
+ }
1150
+ }
1151
+ /** The cooldown, shortened while no key set was ever stored. */
1152
+ #retryIntervalMs() {
1153
+ if (this.#generation > 0) return this.#cooldownMs;
1154
+ return Math.min(this.#cooldownMs, PROFILE_JWKS_EMPTY_RETRY_SECONDS * 1e3);
1155
+ }
1156
+ async #fetchAndStore() {
1157
+ let fetched;
1158
+ try {
1159
+ fetched = await this.#fetcher(new URL(this.#url));
1160
+ } finally {
1161
+ this.#lastAttempt = this.#clock();
1162
+ }
1163
+ this.#keys = new Map(fetched.keys);
1164
+ this.#generation += 1;
1165
+ this.#freshUntil = this.#clock() + fetched.maxAgeSeconds * 1e3;
1166
+ }
1167
+ };
1168
+ function logRefreshFailure(error) {
1169
+ const reason = error instanceof Error ? error.message : String(error);
1170
+ console.warn(
1171
+ `[mycelium-sdk] profile_signature.jwks outcome=refresh_failed reason=${reason}; keeping the last valid profile JWKS`
1172
+ );
1173
+ }
1174
+
1175
+ // src/profileSignatureConfig.ts
1176
+ var CANONICAL_POSITIVE_INTEGER2 = /^[1-9][0-9]*$/;
1177
+ function parseTolerance(env) {
1178
+ const raw = env[PROFILE_SIGNATURE_TOLERANCE_ENV];
1179
+ if (raw === void 0) return DEFAULT_PROFILE_SIGNATURE_TOLERANCE_SECONDS;
1180
+ const trimmed = raw.trim();
1181
+ const value = Number(trimmed);
1182
+ if (!CANONICAL_POSITIVE_INTEGER2.test(trimmed) || !(value <= MAX_PROFILE_SIGNATURE_TOLERANCE_SECONDS)) {
1183
+ throw new ProfileSignatureConfigurationError(
1184
+ `${PROFILE_SIGNATURE_TOLERANCE_ENV} must be an integer between 1 and ${MAX_PROFILE_SIGNATURE_TOLERANCE_SECONDS}`
1185
+ );
1186
+ }
1187
+ return value;
1188
+ }
1189
+ function parseAudience(env) {
1190
+ const raw = env[PROFILE_SIGNATURE_AUDIENCE_ENV];
1191
+ if (raw === void 0) return void 0;
1192
+ if (raw.trim() === "") {
1193
+ throw new ProfileSignatureConfigurationError(
1194
+ `${PROFILE_SIGNATURE_AUDIENCE_ENV} must not be empty`
1195
+ );
1196
+ }
1197
+ return raw;
1198
+ }
1199
+ function parseInsecureSwitch(env) {
1200
+ const raw = env[PROFILE_JWKS_ALLOW_INSECURE_HTTP_ENV]?.trim();
1201
+ if (raw === void 0 || raw === "false") return false;
1202
+ if (raw === "true") return true;
1203
+ throw new ProfileSignatureConfigurationError(
1204
+ `${PROFILE_JWKS_ALLOW_INSECURE_HTTP_ENV} must be true or false`
1205
+ );
1206
+ }
1207
+ function loadProfileSignatureVerifierFromEnv(env = process.env, fetcher = fetchProfileJwks) {
1208
+ const toleranceSeconds = parseTolerance(env);
1209
+ const audience = parseAudience(env);
1210
+ const allowInsecureHttp = parseInsecureSwitch(env);
1211
+ const rawUrl = env[PROFILE_JWKS_URL_ENV];
1212
+ if (rawUrl === void 0) return void 0;
1213
+ const url = parseProfileJwksUrl(rawUrl, allowInsecureHttp);
1214
+ if (audience === void 0) {
1215
+ throw new ProfileSignatureConfigurationError(
1216
+ `${PROFILE_SIGNATURE_AUDIENCE_ENV} is required when ${PROFILE_JWKS_URL_ENV} is set`
1217
+ );
1218
+ }
1219
+ const store = new ProfileKeyStore(
1220
+ url,
1221
+ fetcher,
1222
+ PROFILE_JWKS_REFETCH_COOLDOWN_SECONDS
1223
+ );
1224
+ return new JwksProfileSignatureVerifier(store, toleranceSeconds, audience);
1225
+ }
1226
+ async function prepareProfileSignatureVerifier(env = process.env, fetcher = fetchProfileJwks) {
1227
+ const verifier = loadProfileSignatureVerifierFromEnv(env, fetcher);
1228
+ await verifier?.prefetch();
1229
+ return verifier;
1230
+ }
1231
+
1232
+ // src/profileSignatureEnforcement.ts
1233
+ var SIGNATURE_REJECTION_DETAIL = "Unable to verify Mycelium profile";
1234
+ var SIGNATURE_INTERNAL_DETAIL = "Unable to check user identity. Please contact administrators";
1235
+ async function reportRejection(listener, reason) {
1236
+ try {
1237
+ await listener?.(reason);
1238
+ return true;
1239
+ } catch {
1240
+ return false;
1241
+ }
1242
+ }
1243
+ function singleValue(values, missingReason) {
1244
+ if (values !== void 0 && values.length > 1) {
1245
+ throw new ProfileSignatureError("duplicate_header");
1246
+ }
1247
+ const value = values?.[0];
1248
+ if (value === void 0 || value === "") {
1249
+ throw new ProfileSignatureError(missingReason);
1250
+ }
1251
+ return value;
1252
+ }
1253
+ function receivedValues(message, name) {
1254
+ const distinct = message.headersDistinct?.[name];
1255
+ if (distinct !== void 0) return distinct;
1256
+ const raw = message.rawHeaders;
1257
+ if (Array.isArray(raw) && raw.length > 0) {
1258
+ const values = raw.filter(
1259
+ (_value, index) => index % 2 === 1 && String(raw[index - 1]).toLowerCase() === name
1260
+ );
1261
+ return values.length === 0 ? void 0 : values;
1262
+ }
1263
+ const value = message.headers[name];
1264
+ if (value === void 0) return void 0;
1265
+ return Array.isArray(value) ? value : [value];
1266
+ }
1267
+ function distinctValues(message, name) {
1268
+ return receivedValues(message, name)?.flatMap(
1269
+ (value) => value.split(",").map((part) => part.trim())
1270
+ );
1271
+ }
1272
+ async function verifyRequestProfile(message, verifier, onRejected) {
1273
+ try {
1274
+ const profileHeader = singleValue(
1275
+ distinctValues(message, DEFAULT_PROFILE_KEY),
1276
+ "missing_profile"
1277
+ );
1278
+ const signatureHeader = singleValue(
1279
+ distinctValues(message, DEFAULT_PROFILE_SIGNATURE_KEY),
1280
+ "missing_signature"
1281
+ );
1282
+ const profile = await verifier.verifyAndDecode(
1283
+ profileHeader,
1284
+ signatureHeader
1285
+ );
1286
+ return { ok: true, profile };
1287
+ } catch (error) {
1288
+ if (error instanceof ProfileSignatureError) {
1289
+ if (!await reportRejection(onRejected, error.reason)) {
1290
+ return { ok: false, status: 500, detail: SIGNATURE_INTERNAL_DETAIL };
1291
+ }
1292
+ return { ok: false, status: 403, detail: SIGNATURE_REJECTION_DETAIL };
1293
+ }
1294
+ await reportRejection(onRejected, "internal_error");
1295
+ return { ok: false, status: 500, detail: SIGNATURE_INTERNAL_DETAIL };
1296
+ }
1297
+ }
1298
+ var unverifiedSignatureWarned = false;
1299
+ function warnWhenSignatureIsIgnored(message) {
1300
+ if (unverifiedSignatureWarned) return;
1301
+ if (message.headers[DEFAULT_PROFILE_SIGNATURE_KEY] === void 0) return;
1302
+ unverifiedSignatureWarned = true;
1303
+ console.warn(
1304
+ "[mycelium-sdk] profile_signature.verify outcome=skipped: received a signed profile but MYCELIUM_JWKS_URL is not set; the signature is not verified"
1305
+ );
1306
+ }
1307
+ var sharedVerifier;
1308
+ function sharedProfileSignatureVerifier() {
1309
+ sharedVerifier ??= loadProfileSignatureVerifierFromEnv();
1310
+ return sharedVerifier;
1311
+ }
1312
+
1313
+ export {
1314
+ __commonJS,
1315
+ __toESM,
1316
+ MyceliumError,
1317
+ InsufficientPrivilegesError,
1318
+ InsufficientLicensesError,
1319
+ ProfileDecodingError,
1320
+ PROFILE_SIGNATURE_INVALID_CODE,
1321
+ PROFILE_SIGNATURE_CONFIG_INVALID_CODE,
1322
+ ProfileSignatureConfigurationError,
1323
+ ProfileSignatureError,
1324
+ DEFAULT_PROFILE_KEY,
1325
+ DEFAULT_EMAIL_KEY,
1326
+ DEFAULT_SCOPE_KEY,
1327
+ DEFAULT_MYCELIUM_ROLE_KEY,
1328
+ DEFAULT_REQUEST_ID_KEY,
1329
+ DEFAULT_CONNECTION_STRING_KEY,
1330
+ DEFAULT_TENANT_ID_KEY,
1331
+ DEFAULT_PROFILE_SIGNATURE_KEY,
1332
+ PROFILE_JWKS_URL_ENV,
1333
+ PROFILE_JWKS_ALLOW_INSECURE_HTTP_ENV,
1334
+ PROFILE_JWKS_PATH,
1335
+ PROFILE_JWKS_FETCH_TIMEOUT_SECONDS,
1336
+ PROFILE_JWKS_MAX_BYTES,
1337
+ PROFILE_JWKS_REFETCH_COOLDOWN_SECONDS,
1338
+ PROFILE_JWKS_EMPTY_RETRY_SECONDS,
1339
+ PROFILE_JWKS_DEFAULT_MAX_AGE_SECONDS,
1340
+ PROFILE_JWKS_MIN_MAX_AGE_SECONDS,
1341
+ PROFILE_JWKS_MAX_MAX_AGE_SECONDS,
1342
+ PROFILE_JWKS_MAX_STALE_SECONDS,
1343
+ PROFILE_SIGNATURE_TOLERANCE_ENV,
1344
+ PROFILE_SIGNATURE_AUDIENCE_ENV,
1345
+ DEFAULT_PROFILE_SIGNATURE_TOLERANCE_SECONDS,
1346
+ MAX_PROFILE_SIGNATURE_TOLERANCE_SECONDS,
1347
+ MAX_PROFILE_SIGNATURE_BYTES,
1348
+ Permission,
1349
+ PermissionSchema,
1350
+ permissionToInt,
1351
+ permissionFromInt,
1352
+ VerboseStatusSchema,
1353
+ AccountMetaKeySchema,
1354
+ ProfileMetaSchema,
1355
+ OwnerSchema,
1356
+ LicensedResourceSchema,
1357
+ licensedResourceFromUrlString,
1358
+ LicensedResourcesSchema,
1359
+ toLicensesVector,
1360
+ TenantOwnershipSchema,
1361
+ tenantOwnershipFromUrlString,
1362
+ TenantsOwnershipSchema,
1363
+ toOwnershipVector,
1364
+ ProfileSchema,
1365
+ Profile,
1366
+ decodeAndDecompressProfileFromBase64,
1367
+ safeDecodeAndDecompressProfileFromBase64,
1368
+ compressAndEncodeProfileToBase64,
1369
+ ProfileSignatureVerifier,
1370
+ isCanonicalKeyVersion,
1371
+ profileHeaderHash,
1372
+ verifyProfileSignature,
1373
+ verifyAndDecodeProfile,
1374
+ parseProfileJwks,
1375
+ readJwksCacheMaxAge,
1376
+ ProfileJwksFetchError,
1377
+ fetchProfileJwks,
1378
+ readSignatureKeyVersion,
1379
+ JwksProfileSignatureVerifier,
1380
+ parseProfileJwksUrl,
1381
+ ProfileKeyStore,
1382
+ loadProfileSignatureVerifierFromEnv,
1383
+ prepareProfileSignatureVerifier,
1384
+ SIGNATURE_REJECTION_DETAIL,
1385
+ SIGNATURE_INTERNAL_DETAIL,
1386
+ verifyRequestProfile,
1387
+ warnWhenSignatureIsIgnored,
1388
+ sharedProfileSignatureVerifier
1389
+ };
1390
+ //# sourceMappingURL=chunk-FQWYV2WC.js.map