@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.
- package/README.md +127 -1
- package/dist/chunk-FQWYV2WC.js +1390 -0
- package/dist/chunk-FQWYV2WC.js.map +1 -0
- package/dist/express/index.cjs +696 -3
- package/dist/express/index.cjs.map +1 -1
- package/dist/express/index.d.cts +21 -4
- package/dist/express/index.d.ts +21 -4
- package/dist/express/index.js +36 -3
- package/dist/express/index.js.map +1 -1
- package/dist/fastify/index.cjs +682 -2
- package/dist/fastify/index.cjs.map +1 -1
- package/dist/fastify/index.d.cts +16 -1
- package/dist/fastify/index.d.ts +16 -1
- package/dist/fastify/index.js +21 -2
- package/dist/fastify/index.js.map +1 -1
- package/dist/index.cjs +737 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +149 -3
- package/dist/index.d.ts +149 -3
- package/dist/index.js +81 -3
- package/dist/{profile-CUKBifyR.d.cts → profileSignatureEnforcement-C-bhVkEp.d.cts} +134 -29
- package/dist/{profile-CUKBifyR.d.ts → profileSignatureEnforcement-C-bhVkEp.d.ts} +134 -29
- package/package.json +3 -2
- package/dist/chunk-VPKHPMDS.js +0 -682
- package/dist/chunk-VPKHPMDS.js.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/settings.ts","../src/models/permission.ts","../src/models/verboseStatus.ts","../src/models/accountMetaKey.ts","../src/models/owner.ts","../src/models/licensedResource.ts","../src/models/licensedResources.ts","../src/models/tenantOwnership.ts","../src/models/tenantsOwnership.ts","../src/models/profile.ts","../src/functions/decodeAndDecompressProfileFromBase64.ts"],"sourcesContent":["export * from \"./errors.js\"\nexport * from \"./settings.js\"\n\nexport * from \"./models/permission.js\"\nexport * from \"./models/verboseStatus.js\"\nexport * from \"./models/accountMetaKey.js\"\nexport * from \"./models/owner.js\"\nexport * from \"./models/licensedResource.js\"\nexport * from \"./models/licensedResources.js\"\nexport * from \"./models/tenantOwnership.js\"\nexport * from \"./models/tenantsOwnership.js\"\nexport * from \"./models/relatedAccounts.js\"\nexport * from \"./models/profile.js\"\n\nexport * from \"./functions/decodeAndDecompressProfileFromBase64.js\"\n","export class MyceliumError extends Error {\n code?: string\n expTrue: boolean\n\n constructor(message: string, code?: string, expTrue = false) {\n super(message)\n this.name = \"MyceliumError\"\n this.code = code\n this.expTrue = expTrue\n }\n}\n\nexport class InsufficientPrivilegesError extends MyceliumError {\n filteringState: string[]\n\n constructor(message: string, filteringState: string[] = []) {\n super(message, \"MYC00019\", true)\n this.name = \"InsufficientPrivilegesError\"\n this.filteringState = filteringState\n }\n}\n\nexport class InsufficientLicensesError extends MyceliumError {\n constructor(\n message: string = \"Insufficient licenses to perform these action\"\n ) {\n super(message, \"MYC00019\", true)\n this.name = \"InsufficientLicensesError\"\n }\n}\n\nexport class ProfileDecodingError extends MyceliumError {\n constructor(message: string) {\n super(message, \"MYC00020\", false)\n this.name = \"ProfileDecodingError\"\n }\n}\n","export const DEFAULT_PROFILE_KEY = \"x-mycelium-profile\"\nexport const DEFAULT_EMAIL_KEY = \"x-mycelium-email\"\nexport const DEFAULT_SCOPE_KEY = \"x-mycelium-scope\"\nexport const DEFAULT_MYCELIUM_ROLE_KEY = \"x-mycelium-role\"\nexport const DEFAULT_REQUEST_ID_KEY = \"x-mycelium-request-id\"\nexport const DEFAULT_CONNECTION_STRING_KEY = \"x-mycelium-connection-string\"\nexport const DEFAULT_TENANT_ID_KEY = \"x-mycelium-tenant-id\"\n","import { z } from \"zod\"\n\nexport const Permission = {\n READ: 0,\n WRITE: 1,\n} as const\n\nexport type Permission = (typeof Permission)[keyof typeof Permission]\n\nexport const PermissionSchema: z.ZodType<Permission> = z.union([\n z.literal(0),\n z.literal(1),\n])\n\nexport function permissionToInt(permission: Permission): number {\n return permission\n}\n\nexport function permissionFromInt(value: number): Permission {\n if (value === Permission.READ || value === Permission.WRITE) {\n return value\n }\n throw new Error(`Invalid permission code: ${value}`)\n}\n","import { z } from \"zod\"\n\nexport const VerboseStatusSchema = z.enum([\n \"unverified\",\n \"verified\",\n \"inactive\",\n \"archived\",\n \"deleted\",\n \"unknown\",\n])\n\nexport type VerboseStatus = z.infer<typeof VerboseStatusSchema>\n","import { z } from \"zod\"\n\nconst KNOWN_KEYS = [\n \"phone_number\",\n \"telegram_user\",\n \"whatsapp_user\",\n \"locale\",\n] as const\n\nexport type AccountMetaKey = (typeof KNOWN_KEYS)[number] | `custom:${string}`\n\nexport const AccountMetaKeySchema = z\n .string()\n .refine(\n (value): value is AccountMetaKey =>\n (KNOWN_KEYS as readonly string[]).includes(value) ||\n value.startsWith(\"custom:\"),\n {\n message:\n \"must be one of phone_number, telegram_user, whatsapp_user, locale, or a custom:<key> string\",\n }\n )\n\nexport const ProfileMetaSchema = z.record(AccountMetaKeySchema, z.string())\n\nexport type ProfileMeta = z.infer<typeof ProfileMetaSchema>\n","import { z } from \"zod\"\n\nexport const OwnerSchema = z.object({\n id: z.string().uuid(),\n email: z.string(),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n username: z.string().optional(),\n isPrincipal: z.boolean(),\n})\n\nexport type Owner = z.infer<typeof OwnerSchema>\n","import { z } from \"zod\"\nimport { PermissionSchema, permissionFromInt } from \"./permission.js\"\n\nexport const LicensedResourceSchema = z.object({\n accId: z.string().uuid(),\n sysAcc: z.boolean(),\n tenantId: z.string().uuid(),\n accName: z.string(),\n role: z.string(),\n roleId: z.string().uuid(),\n perm: PermissionSchema,\n verified: z.boolean(),\n permitFlags: z.array(z.string()).optional(),\n denyFlags: z.array(z.string()).optional(),\n})\n\nexport type LicensedResource = z.infer<typeof LicensedResourceSchema>\n\nexport function licensedResourceFromUrlString(value: string): LicensedResource {\n let url: URL\n try {\n url = new URL(value, \"http://placeholder.local\")\n } catch {\n throw new Error(`Invalid licensed resource URL string: ${value}`)\n }\n\n const segments = url.pathname.split(\"/\").filter(Boolean)\n if (\n segments.length !== 6 ||\n segments[0] !== \"t\" ||\n segments[2] !== \"a\" ||\n segments[4] !== \"r\"\n ) {\n throw new Error(`Invalid path format in licensed resource URL: ${value}`)\n }\n\n const tenantId = segments[1] as string\n const accId = segments[3] as string\n const roleId = segments[5] as string\n\n const pParam = url.searchParams.get(\"p\")\n if (pParam === null) {\n throw new Error(`Parameter 'p' not found in: ${value}`)\n }\n const sepIndex = pParam.lastIndexOf(\":\")\n if (sepIndex === -1) {\n throw new Error(`Invalid 'p' parameter format in: ${value}`)\n }\n const role = pParam.slice(0, sepIndex)\n const perm = permissionFromInt(Number.parseInt(pParam.slice(sepIndex + 1), 10))\n\n const sParam = url.searchParams.get(\"s\")\n const vParam = url.searchParams.get(\"v\")\n const nParam = url.searchParams.get(\"n\")\n if (sParam === null || vParam === null || nParam === null) {\n throw new Error(`Missing 's'/'v'/'n' parameter in: ${value}`)\n }\n if (sParam !== \"0\" && sParam !== \"1\") {\n throw new Error(`Invalid 's' parameter value in: ${value}`)\n }\n if (vParam !== \"0\" && vParam !== \"1\") {\n throw new Error(`Invalid 'v' parameter value in: ${value}`)\n }\n\n const accName = Buffer.from(nParam, \"base64\").toString(\"utf-8\")\n\n const pfParam = url.searchParams.get(\"pf\")\n const dfParam = url.searchParams.get(\"df\")\n\n return LicensedResourceSchema.parse({\n accId,\n sysAcc: sParam === \"1\",\n tenantId,\n accName,\n role,\n roleId,\n perm,\n verified: vParam === \"1\",\n permitFlags: pfParam ? pfParam.split(\",\") : undefined,\n denyFlags: dfParam ? dfParam.split(\",\") : undefined,\n })\n}\n","import { z } from \"zod\"\nimport {\n LicensedResourceSchema,\n licensedResourceFromUrlString,\n type LicensedResource,\n} from \"./licensedResource.js\"\n\nfunction tagRecordsOrUrls(raw: unknown) {\n if (raw && typeof raw === \"object\") {\n const obj = raw as Record<string, unknown>\n const hasRecords = \"records\" in obj\n const hasUrls = \"urls\" in obj\n if (hasRecords && !hasUrls) {\n return { kind: \"records\", records: obj.records }\n }\n if (hasUrls && !hasRecords) {\n return { kind: \"urls\", urls: obj.urls }\n }\n }\n return raw\n}\n\nexport const LicensedResourcesSchema = z.preprocess(\n tagRecordsOrUrls,\n z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"records\"),\n records: z.array(LicensedResourceSchema),\n }),\n z.object({\n kind: z.literal(\"urls\"),\n urls: z.array(z.string()),\n }),\n ])\n)\n\nexport type LicensedResources = z.infer<typeof LicensedResourcesSchema>\n\nexport function toLicensesVector(\n lr: LicensedResources | undefined\n): LicensedResource[] {\n if (!lr) return []\n if (lr.kind === \"records\") return lr.records\n return lr.urls.map(licensedResourceFromUrlString)\n}\n","import { z } from \"zod\"\n\nexport const TenantOwnershipSchema = z.object({\n id: z.string().uuid(),\n name: z.string(),\n since: z.coerce.date(),\n})\n\nexport type TenantOwnership = z.infer<typeof TenantOwnershipSchema>\n\nfunction reinsertUuidHyphens(noHyphens: string): string {\n if (!/^[0-9a-fA-F]{32}$/.test(noHyphens)) {\n throw new Error(`Invalid unhyphenated UUID: ${noHyphens}`)\n }\n return [\n noHyphens.slice(0, 8),\n noHyphens.slice(8, 12),\n noHyphens.slice(12, 16),\n noHyphens.slice(16, 20),\n noHyphens.slice(20, 32),\n ].join(\"-\")\n}\n\nexport function tenantOwnershipFromUrlString(value: string): TenantOwnership {\n let url: URL\n try {\n url = new URL(value, \"http://placeholder.local\")\n } catch {\n throw new Error(`Invalid tenant ownership URL string: ${value}`)\n }\n\n const segments = url.pathname.split(\"/\").filter(Boolean)\n if (segments.length !== 2 || segments[0] !== \"tid\") {\n throw new Error(`Invalid path format in tenant ownership URL: ${value}`)\n }\n\n const id = reinsertUuidHyphens(segments[1] as string)\n\n const since = url.searchParams.get(\"since\")\n const nameEncoded = url.searchParams.get(\"name\")\n if (since === null || nameEncoded === null) {\n throw new Error(`Missing 'since'/'name' parameter in: ${value}`)\n }\n\n const name = Buffer.from(nameEncoded, \"base64\").toString(\"utf-8\")\n\n return TenantOwnershipSchema.parse({ id, name, since })\n}\n","import { z } from \"zod\"\nimport {\n TenantOwnershipSchema,\n tenantOwnershipFromUrlString,\n type TenantOwnership,\n} from \"./tenantOwnership.js\"\n\nfunction tagRecordsOrUrls(raw: unknown) {\n if (raw && typeof raw === \"object\") {\n const obj = raw as Record<string, unknown>\n const hasRecords = \"records\" in obj\n const hasUrls = \"urls\" in obj\n if (hasRecords && !hasUrls) {\n return { kind: \"records\", records: obj.records }\n }\n if (hasUrls && !hasRecords) {\n return { kind: \"urls\", urls: obj.urls }\n }\n }\n return raw\n}\n\nexport const TenantsOwnershipSchema = z.preprocess(\n tagRecordsOrUrls,\n z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"records\"),\n records: z.array(TenantOwnershipSchema),\n }),\n z.object({\n kind: z.literal(\"urls\"),\n urls: z.array(z.string()),\n }),\n ])\n)\n\nexport type TenantsOwnership = z.infer<typeof TenantsOwnershipSchema>\n\nexport function toOwnershipVector(\n to: TenantsOwnership | undefined\n): TenantOwnership[] {\n if (!to) return []\n if (to.kind === \"records\") return to.records\n return to.urls.map(tenantOwnershipFromUrlString)\n}\n","import { z } from \"zod\"\nimport {\n InsufficientLicensesError,\n InsufficientPrivilegesError,\n} from \"../errors.js\"\nimport { ProfileMetaSchema } from \"./accountMetaKey.js\"\nimport type { LicensedResource } from \"./licensedResource.js\"\nimport {\n LicensedResourcesSchema,\n toLicensesVector,\n type LicensedResources,\n} from \"./licensedResources.js\"\nimport { OwnerSchema } from \"./owner.js\"\nimport { Permission, permissionToInt } from \"./permission.js\"\nimport type { RelatedAccounts } from \"./relatedAccounts.js\"\nimport {\n TenantsOwnershipSchema,\n toOwnershipVector,\n} from \"./tenantsOwnership.js\"\nimport { VerboseStatusSchema } from \"./verboseStatus.js\"\n\nexport const ProfileSchema = z.object({\n owners: z.array(OwnerSchema).default([]),\n accId: z.string().uuid(),\n isSubscription: z.boolean(),\n isStaff: z.boolean(),\n isManager: z.boolean().default(false),\n ownerIsActive: z.boolean(),\n accountIsActive: z.boolean(),\n accountWasApproved: z.boolean(),\n accountWasArchived: z.boolean(),\n accountWasDeleted: z.boolean(),\n verboseStatus: VerboseStatusSchema.optional(),\n licensedResources: LicensedResourcesSchema.optional(),\n tenantsOwnership: TenantsOwnershipSchema.optional(),\n meta: ProfileMetaSchema.optional(),\n filteringState: z.array(z.string()).optional(),\n})\n\nexport type ProfileData = z.infer<typeof ProfileSchema>\n\nfunction appendState(\n current: string[] | undefined,\n entry: string\n): string[] {\n const state = current ?? []\n return [...state, `${state.length + 1}:${entry}`]\n}\n\nexport class Profile {\n readonly data: ProfileData\n\n private constructor(data: ProfileData) {\n this.data = data\n }\n\n static fromValidated(data: ProfileData): Profile {\n return new Profile(data)\n }\n\n get accId(): string {\n return this.data.accId\n }\n\n get owners() {\n return this.data.owners\n }\n\n get isStaff(): boolean {\n return this.data.isStaff\n }\n\n get isManager(): boolean {\n return this.data.isManager\n }\n\n get licensedResources(): LicensedResources | undefined {\n return this.data.licensedResources\n }\n\n get tenantsOwnership() {\n return this.data.tenantsOwnership\n }\n\n get filteringState(): string[] | undefined {\n return this.data.filteringState\n }\n\n private withData(partial: Partial<ProfileData>): Profile {\n return new Profile({ ...this.data, ...partial })\n }\n\n private filterLicensedResources(\n predicate: (r: LicensedResource) => boolean\n ): LicensedResources | undefined {\n const records = toLicensesVector(this.data.licensedResources).filter(\n predicate\n )\n return records.length === 0\n ? undefined\n : { kind: \"records\", records }\n }\n\n private withPermission(permission: Permission): Profile {\n if (!this.data.licensedResources) return this\n const licensedResources = this.filterLicensedResources(\n (r) => permissionToInt(r.perm) >= permissionToInt(permission)\n )\n return this.withData({\n licensedResources,\n filteringState: appendState(\n this.data.filteringState,\n `permission:${permissionToInt(permission)}`\n ),\n })\n }\n\n withReadAccess(): Profile {\n return this.withPermission(Permission.READ)\n }\n\n withWriteAccess(): Profile {\n return this.withPermission(Permission.WRITE)\n }\n\n onTenant(tenantId: string): Profile {\n const licensedResources = this.filterLicensedResources(\n (r) => r.tenantId === tenantId\n )\n return this.withData({\n licensedResources,\n filteringState: appendState(\n this.data.filteringState,\n `tenantId:${tenantId}`\n ),\n })\n }\n\n withRoles(roles: string[]): Profile {\n const licensedResources = this.filterLicensedResources((r) =>\n roles.includes(r.role)\n )\n return this.withData({\n licensedResources,\n filteringState: appendState(\n this.data.filteringState,\n `role:${roles.join(\",\")}`\n ),\n })\n }\n\n onAccount(accountId: string): Profile {\n const licensedResources = this.filterLicensedResources(\n (r) => r.accId === accountId\n )\n return this.withData({\n licensedResources,\n filteringState: appendState(\n this.data.filteringState,\n `accountId:${accountId}`\n ),\n })\n }\n\n hasPermitFlags(flags: string[]): Profile {\n const licensedResources = this.filterLicensedResources((r) => {\n if (!r.permitFlags) return false\n return flags.every((f) => r.permitFlags?.includes(f))\n })\n return this.withData({\n licensedResources,\n filteringState: appendState(\n this.data.filteringState,\n `permittedFlags:${flags.join(\",\")}`\n ),\n })\n }\n\n hasNotDenyFlags(flags: string[]): Profile {\n const licensedResources = this.filterLicensedResources((r) => {\n if (!r.denyFlags) return true\n return !flags.some((f) => r.denyFlags?.includes(f))\n })\n return this.withData({\n licensedResources,\n filteringState: appendState(\n this.data.filteringState,\n `deniedFlags:${flags.join(\",\")}`\n ),\n })\n }\n\n onTenantAsManager(tenantId: string, permission: Permission): Profile {\n const profile = this.onTenant(tenantId)\n .withPermission(permission)\n .withRoles([\"tenant-manager\"])\n\n return profile.withData({\n filteringState: appendState(profile.data.filteringState, `isTenantManager:true`),\n })\n }\n\n withSystemAccountsAccess(): Profile {\n const licensedResources = this.filterLicensedResources((r) => r.sysAcc)\n return this.withData({\n licensedResources,\n filteringState: appendState(\n this.data.filteringState,\n `isAccStd:true`\n ),\n })\n }\n\n withTenantOwnershipOrError(tenantId: string): Profile {\n const tenants = toOwnershipVector(this.data.tenantsOwnership)\n if (tenants.some((t) => t.id === tenantId)) {\n return this.withData({\n filteringState: appendState(\n this.data.filteringState,\n `tenantOwnership:${tenantId}`\n ),\n })\n }\n\n throw new InsufficientPrivilegesError(\n `Insufficient privileges to perform these action (no tenant ownership): ${(\n this.data.filteringState ?? []\n ).join(\", \")}`,\n this.data.filteringState\n )\n }\n\n hasAdminPrivileges(): boolean {\n return this.data.isStaff || this.data.isManager\n }\n\n hasAdminPrivilegesOrError(): void {\n if (!this.hasAdminPrivileges()) {\n throw new InsufficientPrivilegesError(\n \"Current account has no administration privileges\",\n this.data.filteringState\n )\n }\n }\n\n getIdsOrError(): string[] {\n const ids = toLicensesVector(this.data.licensedResources).map(\n (r) => r.accId\n )\n\n if (ids.length === 0 && !this.hasAdminPrivileges()) {\n throw new InsufficientPrivilegesError(\n `Insufficient privileges to perform these action (no ids): ${(\n this.data.filteringState ?? []\n ).join(\", \")}`,\n this.data.filteringState\n )\n }\n\n return ids\n }\n\n getTenantWidePermissionOrError(\n tenantId: string,\n permission: Permission\n ): RelatedAccounts {\n if (this.data.isStaff) {\n return { kind: \"HasStaffPrivileges\" }\n }\n if (this.data.isManager) {\n return { kind: \"HasManagerPrivileges\" }\n }\n\n const tenants = toOwnershipVector(this.data.tenantsOwnership)\n if (tenants.some((t) => t.id === tenantId)) {\n return { kind: \"HasTenantWidePrivileges\", tenantId }\n }\n\n try {\n this.onTenantAsManager(tenantId, permission).getIdsOrError()\n return { kind: \"HasTenantWidePrivileges\", tenantId }\n } catch {\n // fall through to error below\n }\n\n throw new InsufficientPrivilegesError(\n `Insufficient privileges to perform these action (no tenant wide permission): ${(\n this.data.filteringState ?? []\n ).join(\", \")}`,\n this.data.filteringState\n )\n }\n\n getRelatedAccountsOrTenantWidePermissionOrError(\n tenantId: string,\n permission: Permission\n ): RelatedAccounts {\n try {\n return this.getTenantWidePermissionOrError(tenantId, permission)\n } catch {\n return this.getRelatedAccountOrError()\n }\n }\n\n getRelatedAccountOrError(): RelatedAccounts {\n if (this.data.isStaff) {\n return { kind: \"HasStaffPrivileges\" }\n }\n if (this.data.isManager) {\n return { kind: \"HasManagerPrivileges\" }\n }\n if (this.data.licensedResources) {\n const records = toLicensesVector(this.data.licensedResources)\n if (records.length === 0) {\n throw new InsufficientLicensesError()\n }\n return {\n kind: \"AllowedAccounts\",\n accounts: records.map((r) => r.accId),\n }\n }\n\n throw new InsufficientPrivilegesError(\n `Insufficient privileges to perform these action (no accounts): ${(\n this.data.filteringState ?? []\n ).join(\", \")}`,\n this.data.filteringState\n )\n }\n\n getOwnersIds(): string[] {\n return this.data.owners.map((o) => o.id)\n }\n\n profileString(): string {\n return `profile/${this.data.accId}`\n }\n\n profileRedacted(): string {\n const redactedEmails = this.data.owners.map((o) => redactEmail(o.email))\n return `profile/${this.data.accId} owners: [${redactedEmails.join(\", \")}]`\n }\n}\n\nfunction redactEmail(email: string): string {\n const [local, domain] = email.split(\"@\")\n if (!domain || !local) return email\n const visible = local.slice(0, 1)\n return `${visible}${\"*\".repeat(Math.max(local.length - 1, 1))}@${domain}`\n}\n","import { zstdCompressSync, zstdDecompressSync } from \"node:zlib\"\nimport { ProfileDecodingError } from \"../errors.js\"\nimport { Profile, ProfileSchema } from \"../models/profile.js\"\n\nexport interface DecodeOptions {\n strict?: boolean\n}\n\nexport function decodeAndDecompressProfileFromBase64(\n input: string | Buffer,\n opts: DecodeOptions = {}\n): Profile {\n const strict = opts.strict ?? true\n\n if (\n (typeof input === \"string\" && input.length === 0) ||\n (Buffer.isBuffer(input) && input.length === 0)\n ) {\n throw new ProfileDecodingError(\"Profile input is empty\")\n }\n\n const inputBytes = Buffer.isBuffer(input)\n ? input\n : Buffer.from(input, \"utf-8\")\n\n const base64Text = inputBytes.toString(\"utf-8\")\n if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64Text) || base64Text.length % 4 !== 0) {\n throw new ProfileDecodingError(\n `Failed to decode base64 profile: not valid base64`\n )\n }\n\n let decoded: Buffer\n try {\n decoded = Buffer.from(base64Text, \"base64\")\n } catch (cause) {\n throw new ProfileDecodingError(`Failed to decode base64 profile: ${cause}`)\n }\n\n let decompressed: Buffer\n try {\n decompressed = zstdDecompressSync(decoded)\n } catch (cause) {\n if (strict) {\n throw new ProfileDecodingError(\n `Failed to decompress zstd profile: ${cause}`\n )\n }\n decompressed = decoded\n }\n\n let profileString: string\n try {\n profileString = decompressed.toString(\"utf-8\")\n } catch (cause) {\n throw new ProfileDecodingError(\n `Failed to convert decompressed profile to string: ${cause}`\n )\n }\n\n let profileJson: unknown\n try {\n profileJson = JSON.parse(profileString)\n } catch (cause) {\n throw new ProfileDecodingError(`Failed to deserialize profile: ${cause}`)\n }\n\n const result = ProfileSchema.safeParse(profileJson)\n if (!result.success) {\n throw new ProfileDecodingError(\n `Failed to deserialize profile: ${formatZodError(result.error)}`\n )\n }\n\n return Profile.fromValidated(result.data)\n}\n\nexport type SafeDecodeResult =\n | { success: true; profile: Profile }\n | { success: false; error: ProfileDecodingError }\n\nexport function safeDecodeAndDecompressProfileFromBase64(\n input: string | Buffer,\n opts: DecodeOptions = {}\n): SafeDecodeResult {\n try {\n const profile = decodeAndDecompressProfileFromBase64(input, opts)\n return { success: true, profile }\n } catch (error) {\n if (error instanceof ProfileDecodingError) {\n return { success: false, error }\n }\n return {\n success: false,\n error: new ProfileDecodingError(String(error)),\n }\n }\n}\n\nexport function compressAndEncodeProfileToBase64(profile: Profile): string {\n const json = JSON.stringify(profile.data)\n const compressed = zstdCompressSync(Buffer.from(json, \"utf-8\"))\n return compressed.toString(\"base64\")\n}\n\nfunction formatZodError(error: {\n issues: { path: (string | number)[]; message: string }[]\n}): string {\n return error.issues\n .map((issue) => {\n const path = issue.path.length > 0 ? issue.path.join(\".\") : \"(root)\"\n return `field '${path}' ${issue.message}`\n })\n .join(\"; \")\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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AAS,OAAO;AACd,UAAM,IAAI;AAAA,MACR,qDAAqD,KAAK;AAAA,IAC5D;AAAA,EACF;AAEA,MAAI;AACJ,MAAI;AACF,kBAAc,KAAK,MAAM,aAAa;AAAA,EACxC,SAAS,OAAO;AACd,UAAM,IAAI,qBAAqB,kCAAkC,KAAK,EAAE;AAAA,EAC1E;AAEA,QAAM,SAAS,cAAc,UAAU,WAAW;AAClD,MAAI,CAAC,OAAO,SAAS;AACnB,UAAM,IAAI;AAAA,MACR,kCAAkC,eAAe,OAAO,KAAK,CAAC;AAAA,IAChE;AAAA,EACF;AAEA,SAAO,QAAQ,cAAc,OAAO,IAAI;AAC1C;AAMO,SAAS,yCACd,OACA,OAAsB,CAAC,GACL;AAClB,MAAI;AACF,UAAM,UAAU,qCAAqC,OAAO,IAAI;AAChE,WAAO,EAAE,SAAS,MAAM,QAAQ;AAAA,EAClC,SAAS,OAAO;AACd,QAAI,iBAAiB,sBAAsB;AACzC,aAAO,EAAE,SAAS,OAAO,MAAM;AAAA,IACjC;AACA,WAAO;AAAA,MACL,SAAS;AAAA,MACT,OAAO,IAAI,qBAAqB,OAAO,KAAK,CAAC;AAAA,IAC/C;AAAA,EACF;AACF;AAEO,SAAS,iCAAiC,SAA0B;AACzE,QAAM,OAAO,KAAK,UAAU,QAAQ,IAAI;AACxC,QAAM,iBAAa,mCAAiB,OAAO,KAAK,MAAM,OAAO,CAAC;AAC9D,SAAO,WAAW,SAAS,QAAQ;AACrC;AAEA,SAAS,eAAe,OAEb;AACT,SAAO,MAAM,OACV,IAAI,CAAC,UAAU;AACd,UAAM,OAAO,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,KAAK,GAAG,IAAI;AAC5D,WAAO,UAAU,IAAI,KAAK,MAAM,OAAO;AAAA,EACzC,CAAC,EACA,KAAK,IAAI;AACd;","names":["import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","tagRecordsOrUrls","import_zod"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/settings.ts","../src/models/permission.ts","../src/models/verboseStatus.ts","../src/models/accountMetaKey.ts","../src/models/owner.ts","../src/models/licensedResource.ts","../src/models/licensedResources.ts","../src/models/tenantOwnership.ts","../src/models/tenantsOwnership.ts","../src/models/profile.ts","../src/functions/decodeAndDecompressProfileFromBase64.ts","../src/functions/verifyProfileSignature.ts","../src/profileSignatureVerifier.ts","../src/jwks/parseProfileJwks.ts","../src/jwks/readJwksCacheMaxAge.ts","../src/jwks/fetchProfileJwks.ts","../src/jwks/readSignatureKeyVersion.ts","../src/jwks/jwksProfileSignatureVerifier.ts","../src/jwks/parseProfileJwksUrl.ts","../src/jwks/profileKeyStore.ts","../src/profileSignatureConfig.ts","../src/profileSignatureEnforcement.ts"],"sourcesContent":["export * from \"./errors.js\"\nexport * from \"./settings.js\"\n\nexport * from \"./models/permission.js\"\nexport * from \"./models/verboseStatus.js\"\nexport * from \"./models/accountMetaKey.js\"\nexport * from \"./models/owner.js\"\nexport * from \"./models/licensedResource.js\"\nexport * from \"./models/licensedResources.js\"\nexport * from \"./models/tenantOwnership.js\"\nexport * from \"./models/tenantsOwnership.js\"\nexport * from \"./models/relatedAccounts.js\"\nexport * from \"./models/profile.js\"\n\nexport * from \"./functions/decodeAndDecompressProfileFromBase64.js\"\nexport * from \"./functions/verifyProfileSignature.js\"\nexport * from \"./profileSignatureVerifier.js\"\nexport * from \"./profileSignatureConfig.js\"\nexport * from \"./jwks/fetchProfileJwks.js\"\nexport * from \"./jwks/jwksProfileSignatureVerifier.js\"\nexport * from \"./jwks/parseProfileJwks.js\"\nexport * from \"./jwks/parseProfileJwksUrl.js\"\nexport * from \"./jwks/profileKeyStore.js\"\nexport * from \"./jwks/readJwksCacheMaxAge.js\"\nexport * from \"./jwks/readSignatureKeyVersion.js\"\nexport {\n SIGNATURE_INTERNAL_DETAIL,\n SIGNATURE_REJECTION_DETAIL,\n verifyRequestProfile,\n type SignatureRejectionListener,\n type SignatureVerificationOutcome,\n} from \"./profileSignatureEnforcement.js\"\n","export class MyceliumError extends Error {\n code?: string\n expTrue: boolean\n\n constructor(message: string, code?: string, expTrue = false) {\n super(message)\n this.name = \"MyceliumError\"\n this.code = code\n this.expTrue = expTrue\n }\n}\n\nexport class InsufficientPrivilegesError extends MyceliumError {\n filteringState: string[]\n\n constructor(message: string, filteringState: string[] = []) {\n super(message, \"MYC00019\", true)\n this.name = \"InsufficientPrivilegesError\"\n this.filteringState = filteringState\n }\n}\n\nexport class InsufficientLicensesError extends MyceliumError {\n constructor(\n message: string = \"Insufficient licenses to perform these action\"\n ) {\n super(message, \"MYC00019\", true)\n this.name = \"InsufficientLicensesError\"\n }\n}\n\nexport class ProfileDecodingError extends MyceliumError {\n constructor(message: string) {\n super(message, \"MYC00020\", false)\n this.name = \"ProfileDecodingError\"\n }\n}\n\nexport const PROFILE_SIGNATURE_INVALID_CODE = \"MYC_PROFILE_SIGNATURE_INVALID\"\nexport const PROFILE_SIGNATURE_CONFIG_INVALID_CODE =\n \"MYC_PROFILE_SIGNATURE_CONFIG_INVALID\"\n\nexport type ProfileSignatureRejectionReason =\n | \"missing_profile\"\n | \"missing_signature\"\n | \"duplicate_header\"\n | \"malformed_signature\"\n | \"unsupported_algorithm\"\n | \"unknown_key\"\n | \"invalid_signature\"\n | \"invalid_claims\"\n | \"timestamp_out_of_tolerance\"\n | \"profile_hash_mismatch\"\n | \"audience_mismatch\"\n | \"invalid_profile\"\n\n/**\n * Invalid verification configuration (`MYCELIUM_JWKS_URL` and related\n * variables) or an unsafe/malformed gateway JWKS. A malformed setting must\n * stop the service instead of silently disabling verification. Messages\n * name variables, never values.\n */\nexport class ProfileSignatureConfigurationError extends MyceliumError {\n constructor(message: string) {\n super(message, PROFILE_SIGNATURE_CONFIG_INVALID_CODE, false)\n this.name = \"ProfileSignatureConfigurationError\"\n }\n}\n\n/**\n * Signature rejected. `reason` is stable and log-safe; HTTP integrations\n * answer with a generic message and never expose it to clients.\n */\nexport class ProfileSignatureError extends MyceliumError {\n readonly reason: ProfileSignatureRejectionReason\n\n constructor(reason: ProfileSignatureRejectionReason) {\n super(`Profile signature rejected: ${reason}`, PROFILE_SIGNATURE_INVALID_CODE, true)\n this.name = \"ProfileSignatureError\"\n this.reason = reason\n }\n}\n","export const DEFAULT_PROFILE_KEY = \"x-mycelium-profile\"\nexport const DEFAULT_EMAIL_KEY = \"x-mycelium-email\"\nexport const DEFAULT_SCOPE_KEY = \"x-mycelium-scope\"\nexport const DEFAULT_MYCELIUM_ROLE_KEY = \"x-mycelium-role\"\nexport const DEFAULT_REQUEST_ID_KEY = \"x-mycelium-request-id\"\nexport const DEFAULT_CONNECTION_STRING_KEY = \"x-mycelium-connection-string\"\nexport const DEFAULT_TENANT_ID_KEY = \"x-mycelium-tenant-id\"\nexport const DEFAULT_PROFILE_SIGNATURE_KEY = \"x-mycelium-profile-signature\"\n/** URL of the gateway profile JWKS; its presence enables verification. */\nexport const PROFILE_JWKS_URL_ENV = \"MYCELIUM_JWKS_URL\"\n/** Development-only switch accepting an `http://` JWKS URL (\"true\"/\"false\"). */\nexport const PROFILE_JWKS_ALLOW_INSECURE_HTTP_ENV =\n \"MYCELIUM_JWKS_ALLOW_INSECURE_HTTP\"\n/** Path where the gateway publishes the profile JWKS. */\nexport const PROFILE_JWKS_PATH = \"/.well-known/mycelium-profile-jwks.json\"\nexport const PROFILE_JWKS_FETCH_TIMEOUT_SECONDS = 5\nexport const PROFILE_JWKS_MAX_BYTES = 64 * 1024\n/** Minimum interval between JWKS requests (unknown `kid`, failed refresh). */\nexport const PROFILE_JWKS_REFETCH_COOLDOWN_SECONDS = 30\n/** Shorter retry interval while no key set was ever downloaded (first use). */\nexport const PROFILE_JWKS_EMPTY_RETRY_SECONDS = 5\nexport const PROFILE_JWKS_DEFAULT_MAX_AGE_SECONDS = 43_200\nexport const PROFILE_JWKS_MIN_MAX_AGE_SECONDS = 60\nexport const PROFILE_JWKS_MAX_MAX_AGE_SECONDS = 86_400\n/** How long an expired key set stays trusted while refreshes fail. */\nexport const PROFILE_JWKS_MAX_STALE_SECONDS = 86_400\nexport const PROFILE_SIGNATURE_TOLERANCE_ENV =\n \"MYC_PROFILE_SIGNATURE_TOLERANCE_SECONDS\"\nexport const PROFILE_SIGNATURE_AUDIENCE_ENV = \"MYC_PROFILE_SIGNATURE_AUDIENCE\"\nexport const DEFAULT_PROFILE_SIGNATURE_TOLERANCE_SECONDS = 60\n/** Largest accepted tolerance: it is the replay window of a signature. */\nexport const MAX_PROFILE_SIGNATURE_TOLERANCE_SECONDS = 300\nexport const MAX_PROFILE_SIGNATURE_BYTES = 4096\n","import { z } from \"zod\"\n\nexport const Permission = {\n READ: 0,\n WRITE: 1,\n} as const\n\nexport type Permission = (typeof Permission)[keyof typeof Permission]\n\nexport const PermissionSchema = z.union([\n z.literal(0),\n z.literal(1),\n // Rust serializes Permission with serde rename_all = camelCase.\n z.literal(\"read\").transform(() => Permission.READ),\n z.literal(\"write\").transform(() => Permission.WRITE),\n])\n\nexport function permissionToInt(permission: Permission): number {\n return permission\n}\n\nexport function permissionFromInt(value: number): Permission {\n if (value === Permission.READ || value === Permission.WRITE) {\n return value\n }\n throw new Error(`Invalid permission code: ${value}`)\n}\n","import { z } from \"zod\"\n\nexport const VerboseStatusSchema = z.enum([\n \"unverified\",\n \"verified\",\n \"inactive\",\n \"archived\",\n \"deleted\",\n \"unknown\",\n])\n\nexport type VerboseStatus = z.infer<typeof VerboseStatusSchema>\n","import { z } from \"zod\"\n\nconst KNOWN_KEYS = [\n \"phone_number\",\n \"telegram_user\",\n \"whatsapp_user\",\n \"locale\",\n] as const\n\nexport type AccountMetaKey = (typeof KNOWN_KEYS)[number] | `custom:${string}`\n\nexport const AccountMetaKeySchema = z\n .string()\n .refine(\n (value): value is AccountMetaKey =>\n (KNOWN_KEYS as readonly string[]).includes(value) ||\n value.startsWith(\"custom:\"),\n {\n message:\n \"must be one of phone_number, telegram_user, whatsapp_user, locale, or a custom:<key> string\",\n }\n )\n\nexport const ProfileMetaSchema = z.record(AccountMetaKeySchema, z.string())\n\nexport type ProfileMeta = z.infer<typeof ProfileMetaSchema>\n","import { z } from \"zod\"\n\nexport const OwnerSchema = z.object({\n id: z.string().uuid(),\n email: z.string(),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n username: z.string().optional(),\n isPrincipal: z.boolean(),\n})\n\nexport type Owner = z.infer<typeof OwnerSchema>\n","import { z } from \"zod\"\nimport { PermissionSchema, permissionFromInt } from \"./permission.js\"\n\nexport const LicensedResourceSchema = z.object({\n accId: z.string().uuid(),\n sysAcc: z.boolean(),\n tenantId: z.string().uuid(),\n accName: z.string(),\n role: z.string(),\n roleId: z.string().uuid(),\n perm: PermissionSchema,\n verified: z.boolean(),\n permitFlags: z.array(z.string()).optional(),\n denyFlags: z.array(z.string()).optional(),\n})\n\nexport type LicensedResource = z.infer<typeof LicensedResourceSchema>\n\nexport function licensedResourceFromUrlString(value: string): LicensedResource {\n let url: URL\n try {\n url = new URL(value, \"http://placeholder.local\")\n } catch {\n throw new Error(`Invalid licensed resource URL string: ${value}`)\n }\n\n const segments = url.pathname.split(\"/\").filter(Boolean)\n if (\n segments.length !== 6 ||\n segments[0] !== \"t\" ||\n segments[2] !== \"a\" ||\n segments[4] !== \"r\"\n ) {\n throw new Error(`Invalid path format in licensed resource URL: ${value}`)\n }\n\n const tenantId = segments[1] as string\n const accId = segments[3] as string\n const roleId = segments[5] as string\n\n const pParam = url.searchParams.get(\"p\")\n if (pParam === null) {\n throw new Error(`Parameter 'p' not found in: ${value}`)\n }\n const sepIndex = pParam.lastIndexOf(\":\")\n if (sepIndex === -1) {\n throw new Error(`Invalid 'p' parameter format in: ${value}`)\n }\n const role = pParam.slice(0, sepIndex)\n const perm = permissionFromInt(Number.parseInt(pParam.slice(sepIndex + 1), 10))\n\n const sParam = url.searchParams.get(\"s\")\n const vParam = url.searchParams.get(\"v\")\n const nParam = url.searchParams.get(\"n\")\n if (sParam === null || vParam === null || nParam === null) {\n throw new Error(`Missing 's'/'v'/'n' parameter in: ${value}`)\n }\n if (sParam !== \"0\" && sParam !== \"1\") {\n throw new Error(`Invalid 's' parameter value in: ${value}`)\n }\n if (vParam !== \"0\" && vParam !== \"1\") {\n throw new Error(`Invalid 'v' parameter value in: ${value}`)\n }\n\n const accName = Buffer.from(nParam, \"base64\").toString(\"utf-8\")\n\n const pfParam = url.searchParams.get(\"pf\")\n const dfParam = url.searchParams.get(\"df\")\n\n return LicensedResourceSchema.parse({\n accId,\n sysAcc: sParam === \"1\",\n tenantId,\n accName,\n role,\n roleId,\n perm,\n verified: vParam === \"1\",\n permitFlags: pfParam ? pfParam.split(\",\") : undefined,\n denyFlags: dfParam ? dfParam.split(\",\") : undefined,\n })\n}\n","import { z } from \"zod\"\nimport {\n LicensedResourceSchema,\n licensedResourceFromUrlString,\n type LicensedResource,\n} from \"./licensedResource.js\"\n\nfunction tagRecordsOrUrls(raw: unknown) {\n if (raw && typeof raw === \"object\") {\n const obj = raw as Record<string, unknown>\n const hasRecords = \"records\" in obj\n const hasUrls = \"urls\" in obj\n if (hasRecords && !hasUrls) {\n return { kind: \"records\", records: obj.records }\n }\n if (hasUrls && !hasRecords) {\n return { kind: \"urls\", urls: obj.urls }\n }\n }\n return raw\n}\n\nexport const LicensedResourcesSchema = z.preprocess(\n tagRecordsOrUrls,\n z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"records\"),\n records: z.array(LicensedResourceSchema),\n }),\n z.object({\n kind: z.literal(\"urls\"),\n urls: z.array(z.string()),\n }),\n ])\n)\n\nexport type LicensedResources = z.infer<typeof LicensedResourcesSchema>\n\nexport function toLicensesVector(\n lr: LicensedResources | undefined\n): LicensedResource[] {\n if (!lr) return []\n if (lr.kind === \"records\") return lr.records\n return lr.urls.map(licensedResourceFromUrlString)\n}\n","import { z } from \"zod\"\n\nexport const TenantOwnershipSchema = z.object({\n id: z.string().uuid(),\n name: z.string(),\n since: z.coerce.date(),\n})\n\nexport type TenantOwnership = z.infer<typeof TenantOwnershipSchema>\n\nfunction reinsertUuidHyphens(noHyphens: string): string {\n if (!/^[0-9a-fA-F]{32}$/.test(noHyphens)) {\n throw new Error(`Invalid unhyphenated UUID: ${noHyphens}`)\n }\n return [\n noHyphens.slice(0, 8),\n noHyphens.slice(8, 12),\n noHyphens.slice(12, 16),\n noHyphens.slice(16, 20),\n noHyphens.slice(20, 32),\n ].join(\"-\")\n}\n\nexport function tenantOwnershipFromUrlString(value: string): TenantOwnership {\n let url: URL\n try {\n url = new URL(value, \"http://placeholder.local\")\n } catch {\n throw new Error(`Invalid tenant ownership URL string: ${value}`)\n }\n\n const segments = url.pathname.split(\"/\").filter(Boolean)\n if (segments.length !== 2 || segments[0] !== \"tid\") {\n throw new Error(`Invalid path format in tenant ownership URL: ${value}`)\n }\n\n const id = reinsertUuidHyphens(segments[1] as string)\n\n const since = url.searchParams.get(\"since\")\n const nameEncoded = url.searchParams.get(\"name\")\n if (since === null || nameEncoded === null) {\n throw new Error(`Missing 'since'/'name' parameter in: ${value}`)\n }\n\n const name = Buffer.from(nameEncoded, \"base64\").toString(\"utf-8\")\n\n return TenantOwnershipSchema.parse({ id, name, since })\n}\n","import { z } from \"zod\"\nimport {\n TenantOwnershipSchema,\n tenantOwnershipFromUrlString,\n type TenantOwnership,\n} from \"./tenantOwnership.js\"\n\nfunction tagRecordsOrUrls(raw: unknown) {\n if (raw && typeof raw === \"object\") {\n const obj = raw as Record<string, unknown>\n const hasRecords = \"records\" in obj\n const hasUrls = \"urls\" in obj\n if (hasRecords && !hasUrls) {\n return { kind: \"records\", records: obj.records }\n }\n if (hasUrls && !hasRecords) {\n return { kind: \"urls\", urls: obj.urls }\n }\n }\n return raw\n}\n\nexport const TenantsOwnershipSchema = z.preprocess(\n tagRecordsOrUrls,\n z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"records\"),\n records: z.array(TenantOwnershipSchema),\n }),\n z.object({\n kind: z.literal(\"urls\"),\n urls: z.array(z.string()),\n }),\n ])\n)\n\nexport type TenantsOwnership = z.infer<typeof TenantsOwnershipSchema>\n\nexport function toOwnershipVector(\n to: TenantsOwnership | undefined\n): TenantOwnership[] {\n if (!to) return []\n if (to.kind === \"records\") return to.records\n return to.urls.map(tenantOwnershipFromUrlString)\n}\n","import { z } from \"zod\"\nimport {\n InsufficientLicensesError,\n InsufficientPrivilegesError,\n} from \"../errors.js\"\nimport { ProfileMetaSchema } from \"./accountMetaKey.js\"\nimport type { LicensedResource } from \"./licensedResource.js\"\nimport {\n LicensedResourcesSchema,\n toLicensesVector,\n type LicensedResources,\n} from \"./licensedResources.js\"\nimport { OwnerSchema } from \"./owner.js\"\nimport { Permission, permissionToInt } from \"./permission.js\"\nimport type { RelatedAccounts } from \"./relatedAccounts.js\"\nimport {\n TenantsOwnershipSchema,\n toOwnershipVector,\n} from \"./tenantsOwnership.js\"\nimport { VerboseStatusSchema } from \"./verboseStatus.js\"\n\nexport const ProfileSchema = z.object({\n owners: z.array(OwnerSchema).default([]),\n accId: z.string().uuid(),\n isSubscription: z.boolean(),\n isStaff: z.boolean(),\n isManager: z.boolean().default(false),\n ownerIsActive: z.boolean(),\n accountIsActive: z.boolean(),\n accountWasApproved: z.boolean(),\n accountWasArchived: z.boolean(),\n accountWasDeleted: z.boolean(),\n verboseStatus: VerboseStatusSchema.nullish(),\n licensedResources: LicensedResourcesSchema.optional(),\n tenantsOwnership: TenantsOwnershipSchema.optional(),\n meta: ProfileMetaSchema.optional(),\n filteringState: z.array(z.string()).optional(),\n})\n\nexport type ProfileData = z.infer<typeof ProfileSchema>\n\nfunction appendState(\n current: string[] | undefined,\n entry: string\n): string[] {\n const state = current ?? []\n return [...state, `${state.length + 1}:${entry}`]\n}\n\nexport class Profile {\n readonly data: ProfileData\n\n private constructor(data: ProfileData) {\n this.data = data\n }\n\n static fromValidated(data: ProfileData): Profile {\n return new Profile(data)\n }\n\n get accId(): string {\n return this.data.accId\n }\n\n get owners() {\n return this.data.owners\n }\n\n get isStaff(): boolean {\n return this.data.isStaff\n }\n\n get isManager(): boolean {\n return this.data.isManager\n }\n\n get licensedResources(): LicensedResources | undefined {\n return this.data.licensedResources\n }\n\n get tenantsOwnership() {\n return this.data.tenantsOwnership\n }\n\n get filteringState(): string[] | undefined {\n return this.data.filteringState\n }\n\n private withData(partial: Partial<ProfileData>): Profile {\n return new Profile({ ...this.data, ...partial })\n }\n\n private filterLicensedResources(\n predicate: (r: LicensedResource) => boolean\n ): LicensedResources | undefined {\n const records = toLicensesVector(this.data.licensedResources).filter(\n predicate\n )\n return records.length === 0\n ? undefined\n : { kind: \"records\", records }\n }\n\n private withPermission(permission: Permission): Profile {\n if (!this.data.licensedResources) return this\n const licensedResources = this.filterLicensedResources(\n (r) => permissionToInt(r.perm) >= permissionToInt(permission)\n )\n return this.withData({\n licensedResources,\n filteringState: appendState(\n this.data.filteringState,\n `permission:${permissionToInt(permission)}`\n ),\n })\n }\n\n withReadAccess(): Profile {\n return this.withPermission(Permission.READ)\n }\n\n withWriteAccess(): Profile {\n return this.withPermission(Permission.WRITE)\n }\n\n onTenant(tenantId: string): Profile {\n const licensedResources = this.filterLicensedResources(\n (r) => r.tenantId === tenantId\n )\n return this.withData({\n licensedResources,\n filteringState: appendState(\n this.data.filteringState,\n `tenantId:${tenantId}`\n ),\n })\n }\n\n withRoles(roles: string[]): Profile {\n const licensedResources = this.filterLicensedResources((r) =>\n roles.includes(r.role)\n )\n return this.withData({\n licensedResources,\n filteringState: appendState(\n this.data.filteringState,\n `role:${roles.join(\",\")}`\n ),\n })\n }\n\n onAccount(accountId: string): Profile {\n const licensedResources = this.filterLicensedResources(\n (r) => r.accId === accountId\n )\n return this.withData({\n licensedResources,\n filteringState: appendState(\n this.data.filteringState,\n `accountId:${accountId}`\n ),\n })\n }\n\n hasPermitFlags(flags: string[]): Profile {\n const licensedResources = this.filterLicensedResources((r) => {\n if (!r.permitFlags) return false\n return flags.every((f) => r.permitFlags?.includes(f))\n })\n return this.withData({\n licensedResources,\n filteringState: appendState(\n this.data.filteringState,\n `permittedFlags:${flags.join(\",\")}`\n ),\n })\n }\n\n hasNotDenyFlags(flags: string[]): Profile {\n const licensedResources = this.filterLicensedResources((r) => {\n if (!r.denyFlags) return true\n return !flags.some((f) => r.denyFlags?.includes(f))\n })\n return this.withData({\n licensedResources,\n filteringState: appendState(\n this.data.filteringState,\n `deniedFlags:${flags.join(\",\")}`\n ),\n })\n }\n\n onTenantAsManager(tenantId: string, permission: Permission): Profile {\n const profile = this.onTenant(tenantId)\n .withPermission(permission)\n .withRoles([\"tenant-manager\"])\n\n return profile.withData({\n filteringState: appendState(profile.data.filteringState, `isTenantManager:true`),\n })\n }\n\n withSystemAccountsAccess(): Profile {\n const licensedResources = this.filterLicensedResources((r) => r.sysAcc)\n return this.withData({\n licensedResources,\n filteringState: appendState(\n this.data.filteringState,\n `isAccStd:true`\n ),\n })\n }\n\n withTenantOwnershipOrError(tenantId: string): Profile {\n const tenants = toOwnershipVector(this.data.tenantsOwnership)\n if (tenants.some((t) => t.id === tenantId)) {\n return this.withData({\n filteringState: appendState(\n this.data.filteringState,\n `tenantOwnership:${tenantId}`\n ),\n })\n }\n\n throw new InsufficientPrivilegesError(\n `Insufficient privileges to perform these action (no tenant ownership): ${(\n this.data.filteringState ?? []\n ).join(\", \")}`,\n this.data.filteringState\n )\n }\n\n hasAdminPrivileges(): boolean {\n return this.data.isStaff || this.data.isManager\n }\n\n hasAdminPrivilegesOrError(): void {\n if (!this.hasAdminPrivileges()) {\n throw new InsufficientPrivilegesError(\n \"Current account has no administration privileges\",\n this.data.filteringState\n )\n }\n }\n\n getIdsOrError(): string[] {\n const ids = toLicensesVector(this.data.licensedResources).map(\n (r) => r.accId\n )\n\n if (ids.length === 0 && !this.hasAdminPrivileges()) {\n throw new InsufficientPrivilegesError(\n `Insufficient privileges to perform these action (no ids): ${(\n this.data.filteringState ?? []\n ).join(\", \")}`,\n this.data.filteringState\n )\n }\n\n return ids\n }\n\n getTenantWidePermissionOrError(\n tenantId: string,\n permission: Permission\n ): RelatedAccounts {\n if (this.data.isStaff) {\n return { kind: \"HasStaffPrivileges\" }\n }\n if (this.data.isManager) {\n return { kind: \"HasManagerPrivileges\" }\n }\n\n const tenants = toOwnershipVector(this.data.tenantsOwnership)\n if (tenants.some((t) => t.id === tenantId)) {\n return { kind: \"HasTenantWidePrivileges\", tenantId }\n }\n\n try {\n this.onTenantAsManager(tenantId, permission).getIdsOrError()\n return { kind: \"HasTenantWidePrivileges\", tenantId }\n } catch {\n // fall through to error below\n }\n\n throw new InsufficientPrivilegesError(\n `Insufficient privileges to perform these action (no tenant wide permission): ${(\n this.data.filteringState ?? []\n ).join(\", \")}`,\n this.data.filteringState\n )\n }\n\n getRelatedAccountsOrTenantWidePermissionOrError(\n tenantId: string,\n permission: Permission\n ): RelatedAccounts {\n try {\n return this.getTenantWidePermissionOrError(tenantId, permission)\n } catch {\n return this.getRelatedAccountOrError()\n }\n }\n\n getRelatedAccountOrError(): RelatedAccounts {\n if (this.data.isStaff) {\n return { kind: \"HasStaffPrivileges\" }\n }\n if (this.data.isManager) {\n return { kind: \"HasManagerPrivileges\" }\n }\n if (this.data.licensedResources) {\n const records = toLicensesVector(this.data.licensedResources)\n if (records.length === 0) {\n throw new InsufficientLicensesError()\n }\n return {\n kind: \"AllowedAccounts\",\n accounts: records.map((r) => r.accId),\n }\n }\n\n throw new InsufficientPrivilegesError(\n `Insufficient privileges to perform these action (no accounts): ${(\n this.data.filteringState ?? []\n ).join(\", \")}`,\n this.data.filteringState\n )\n }\n\n getOwnersIds(): string[] {\n return this.data.owners.map((o) => o.id)\n }\n\n profileString(): string {\n return `profile/${this.data.accId}`\n }\n\n profileRedacted(): string {\n const redactedEmails = this.data.owners.map((o) => redactEmail(o.email))\n return `profile/${this.data.accId} owners: [${redactedEmails.join(\", \")}]`\n }\n}\n\nfunction redactEmail(email: string): string {\n const [local, domain] = email.split(\"@\")\n if (!domain || !local) return email\n const visible = local.slice(0, 1)\n return `${visible}${\"*\".repeat(Math.max(local.length - 1, 1))}@${domain}`\n}\n","import { zstdCompressSync, zstdDecompressSync } from \"node:zlib\"\nimport { ProfileDecodingError } from \"../errors.js\"\nimport { Profile, ProfileSchema } from \"../models/profile.js\"\n\nexport interface DecodeOptions {\n strict?: boolean\n}\n\nexport function decodeAndDecompressProfileFromBase64(\n input: string | Buffer,\n opts: DecodeOptions = {}\n): Profile {\n const strict = opts.strict ?? true\n\n if (\n (typeof input === \"string\" && input.length === 0) ||\n (Buffer.isBuffer(input) && input.length === 0)\n ) {\n throw new ProfileDecodingError(\"Profile input is empty\")\n }\n\n const inputBytes = Buffer.isBuffer(input)\n ? input\n : Buffer.from(input, \"utf-8\")\n\n const base64Text = inputBytes.toString(\"utf-8\")\n if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64Text) || base64Text.length % 4 !== 0) {\n throw new ProfileDecodingError(\n `Failed to decode base64 profile: not valid base64`\n )\n }\n\n let decoded: Buffer\n try {\n decoded = Buffer.from(base64Text, \"base64\")\n } catch (cause) {\n throw new ProfileDecodingError(`Failed to decode base64 profile: ${cause}`)\n }\n\n let decompressed: Buffer\n try {\n decompressed = zstdDecompressSync(decoded)\n } catch (cause) {\n if (strict) {\n throw new ProfileDecodingError(\n `Failed to decompress zstd profile: ${cause}`\n )\n }\n decompressed = decoded\n }\n\n let profileString: string\n try {\n profileString = decompressed.toString(\"utf-8\")\n } catch (cause) {\n throw new ProfileDecodingError(\n `Failed to convert decompressed profile to string: ${cause}`\n )\n }\n\n let profileJson: unknown\n try {\n profileJson = JSON.parse(profileString)\n } catch (cause) {\n throw new ProfileDecodingError(`Failed to deserialize profile: ${cause}`)\n }\n\n const result = ProfileSchema.safeParse(profileJson)\n if (!result.success) {\n throw new ProfileDecodingError(\n `Failed to deserialize profile: ${formatZodError(result.error)}`\n )\n }\n\n return Profile.fromValidated(result.data)\n}\n\nexport type SafeDecodeResult =\n | { success: true; profile: Profile }\n | { success: false; error: ProfileDecodingError }\n\nexport function safeDecodeAndDecompressProfileFromBase64(\n input: string | Buffer,\n opts: DecodeOptions = {}\n): SafeDecodeResult {\n try {\n const profile = decodeAndDecompressProfileFromBase64(input, opts)\n return { success: true, profile }\n } catch (error) {\n if (error instanceof ProfileDecodingError) {\n return { success: false, error }\n }\n return {\n success: false,\n error: new ProfileDecodingError(String(error)),\n }\n }\n}\n\nexport function compressAndEncodeProfileToBase64(profile: Profile): string {\n const json = JSON.stringify(profile.data)\n const compressed = zstdCompressSync(Buffer.from(json, \"utf-8\"))\n return compressed.toString(\"base64\")\n}\n\nfunction formatZodError(error: {\n issues: { path: (string | number)[]; message: string }[]\n}): string {\n return error.issues\n .map((issue) => {\n const path = issue.path.length > 0 ? issue.path.join(\".\") : \"(root)\"\n return `field '${path}' ${issue.message}`\n })\n .join(\"; \")\n}\n","import { createHash, timingSafeEqual, type KeyObject } from \"node:crypto\"\nimport { compactVerify, errors as joseErrors } from \"jose\"\nimport { z } from \"zod\"\nimport {\n ProfileSignatureError,\n type ProfileSignatureRejectionReason,\n} from \"../errors.js\"\nimport type { Profile } from \"../models/profile.js\"\nimport {\n isCanonicalKeyVersion,\n type ProfileSignatureVerifier,\n} from \"../profileSignatureVerifier.js\"\nimport { MAX_PROFILE_SIGNATURE_BYTES } from \"../settings.js\"\nimport { decodeAndDecompressProfileFromBase64 } from \"./decodeAndDecompressProfileFromBase64.js\"\n\n/**\n * Strict, local verification of the downstream profile signature.\n *\n * Contract shared with the gateway and the Python SDK: compact JWS with\n * `alg: EdDSA` and the key version as `kid`; claims `{iat, ph, aud}` where\n * `ph` is the unpadded Base64URL SHA-256 of the exact `x-mycelium-profile`\n * value. Checks run in a fixed precedence so every SDK reports the same\n * `reason`. No network, file or environment access.\n *\n * Always `await` it: an un-awaited call would let the request through.\n */\n\nconst FORBIDDEN_HEADER_MEMBERS = [\"crit\", \"b64\", \"jku\", \"jwk\", \"x5u\", \"x5c\"]\nconst ENCODED_DIGEST_LENGTH = 43\n\nfunction reject(reason: ProfileSignatureRejectionReason): ProfileSignatureError {\n return new ProfileSignatureError(reason)\n}\n\nfunction isCanonicalHash(value: string): boolean {\n if (value.length !== ENCODED_DIGEST_LENGTH) return false\n\n const raw = Buffer.from(value, \"base64url\")\n return raw.length === 32 && raw.toString(\"base64url\") === value\n}\n\nconst claimsSchema = z.object({\n iat: z.number().refine((value) => Number.isSafeInteger(value) && value >= 0),\n ph: z.string().refine(isCanonicalHash),\n aud: z.string().refine((value) => value.trim() !== \"\"),\n})\n\ntype ProfileSignatureClaims = z.infer<typeof claimsSchema>\n\nfunction decodeSegment(segment: string): Record<string, unknown> | undefined {\n try {\n const value: unknown = JSON.parse(\n Buffer.from(segment, \"base64url\").toString(\"utf8\")\n )\n const isObject =\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n return isObject ? (value as Record<string, unknown>) : undefined\n } catch {\n return undefined\n }\n}\n\nfunction splitToken(signatureHeader: string): string[] {\n if (signatureHeader === \"\") throw reject(\"missing_signature\")\n\n const parts = signatureHeader.split(\".\")\n const oversized =\n Buffer.byteLength(signatureHeader, \"utf8\") > MAX_PROFILE_SIGNATURE_BYTES\n if (oversized || parts.length !== 3) throw reject(\"malformed_signature\")\n\n return parts\n}\n\nfunction selectKey(\n header: Record<string, unknown>,\n verifier: ProfileSignatureVerifier\n): KeyObject {\n if (header.alg !== \"EdDSA\") throw reject(\"unsupported_algorithm\")\n\n const hasForbidden = FORBIDDEN_HEADER_MEMBERS.some((member) => member in header)\n if (hasForbidden) throw reject(\"malformed_signature\")\n\n const kid = header.kid\n const key =\n typeof kid === \"string\" && isCanonicalKeyVersion(kid)\n ? verifier.keyFor(kid)\n : undefined\n if (key === undefined) throw reject(\"unknown_key\")\n\n return key\n}\n\nasync function verifyJws(token: string, key: KeyObject): Promise<Uint8Array> {\n try {\n const { payload } = await compactVerify(token, key, {\n algorithms: [\"EdDSA\"],\n })\n return payload\n } catch (error) {\n if (error instanceof joseErrors.JWSSignatureVerificationFailed) {\n throw reject(\"invalid_signature\")\n }\n throw reject(\"malformed_signature\")\n }\n}\n\nfunction parseClaims(payload: Uint8Array): ProfileSignatureClaims {\n let decoded: unknown\n try {\n decoded = JSON.parse(Buffer.from(payload).toString(\"utf8\"))\n } catch {\n throw reject(\"invalid_claims\")\n }\n\n const parsed = claimsSchema.safeParse(decoded)\n if (!parsed.success) throw reject(\"invalid_claims\")\n\n return parsed.data\n}\n\nfunction resolveNow(nowSeconds?: number): number {\n const now = nowSeconds ?? Math.floor(Date.now() / 1000)\n if (!Number.isSafeInteger(now) || now < 0) {\n throw new RangeError(\"Verifier clock is outside the safe integer range\")\n }\n\n return now\n}\n\n/** Unpadded Base64URL SHA-256 of the exact profile header value. */\nexport function profileHeaderHash(profileHeader: string): string {\n return createHash(\"sha256\").update(profileHeader, \"utf8\").digest(\"base64url\")\n}\n\nfunction sameHash(received: string, expected: string): boolean {\n const left = Buffer.from(received, \"utf8\")\n const right = Buffer.from(expected, \"utf8\")\n return left.length === right.length && timingSafeEqual(left, right)\n}\n\nfunction checkClaims(\n claims: ProfileSignatureClaims,\n profileHeader: string,\n verifier: ProfileSignatureVerifier,\n now: number\n): void {\n if (Math.abs(now - claims.iat) > verifier.toleranceSeconds) {\n throw reject(\"timestamp_out_of_tolerance\")\n }\n\n if (!sameHash(claims.ph, profileHeaderHash(profileHeader))) {\n throw reject(\"profile_hash_mismatch\")\n }\n\n const expected = verifier.expectedAudience\n if (expected !== undefined && claims.aud !== expected) {\n throw reject(\"audience_mismatch\")\n }\n}\n\n/**\n * Verify that `signatureHeader` authenticates `profileHeader`.\n *\n * Rejects with `ProfileSignatureError` (stable `reason`) on any failure, and\n * with `RangeError` for an invalid verifier clock (internal error). Does not\n * decode the profile; see `verifyAndDecodeProfile`.\n */\nexport async function verifyProfileSignature(\n profileHeader: string,\n signatureHeader: string,\n verifier: ProfileSignatureVerifier,\n nowSeconds?: number\n): Promise<void> {\n if (profileHeader === \"\") throw reject(\"missing_profile\")\n\n const parts = splitToken(signatureHeader)\n const header = decodeSegment(parts[0] ?? \"\")\n if (header === undefined) throw reject(\"malformed_signature\")\n\n const key = selectKey(header, verifier)\n const payload = await verifyJws(signatureHeader, key)\n const claims = parseClaims(payload)\n checkClaims(claims, profileHeader, verifier, resolveNow(nowSeconds))\n}\n\n/** Verify the signature, then decode the profile (`invalid_profile`). */\nexport async function verifyAndDecodeProfile(\n profileHeader: string,\n signatureHeader: string,\n verifier: ProfileSignatureVerifier,\n nowSeconds?: number\n): Promise<Profile> {\n await verifyProfileSignature(profileHeader, signatureHeader, verifier, nowSeconds)\n\n try {\n return decodeAndDecompressProfileFromBase64(profileHeader)\n } catch {\n throw reject(\"invalid_profile\")\n }\n}\n","import type { KeyObject } from \"node:crypto\"\n\nconst CANONICAL_POSITIVE_INTEGER = /^[1-9][0-9]*$/\nconst MAX_KEY_VERSION = 4_294_967_295\n\n/**\n * One verification pass: the trusted Ed25519 keys at an instant, by `kid`,\n * and the rules. Immutable; the key map is private.\n *\n * The JWKS-backed verifier builds one per request from its cached keys; the\n * contract tests build one directly. The audience is optional here so the\n * shared vectors can exercise both cases; a configured service always has\n * one (see `JwksProfileSignatureVerifier`).\n */\nexport class ProfileSignatureVerifier {\n readonly #keys: ReadonlyMap<string, KeyObject>\n readonly toleranceSeconds: number\n readonly expectedAudience: string | undefined\n\n constructor(\n keys: ReadonlyMap<string, KeyObject>,\n toleranceSeconds: number,\n expectedAudience?: string\n ) {\n this.#keys = new Map(keys)\n this.toleranceSeconds = toleranceSeconds\n this.expectedAudience = expectedAudience\n Object.freeze(this)\n }\n\n keyFor(kid: string): KeyObject | undefined {\n return this.#keys.get(kid)\n }\n\n get keyVersions(): string[] {\n return [...this.#keys.keys()].sort()\n }\n}\n\n/** Canonical decimal key version (`kid`): 1..4294967295, no leading zeros. */\nexport function isCanonicalKeyVersion(raw: string): boolean {\n return CANONICAL_POSITIVE_INTEGER.test(raw) && Number(raw) <= MAX_KEY_VERSION\n}\n","import { createPublicKey, type KeyObject } from \"node:crypto\"\nimport { ProfileSignatureConfigurationError } from \"../errors.js\"\nimport { isCanonicalKeyVersion } from \"../profileSignatureVerifier.js\"\n\nconst JWKS = \"profile JWKS\"\nconst BASE64URL = /^[A-Za-z0-9_-]+$/\nconst ED25519_PUBLIC_KEY_BYTES = 32\n\ntype JsonObject = Record<string, unknown>\n\nfunction invalid(problem: string): ProfileSignatureConfigurationError {\n return new ProfileSignatureConfigurationError(`${JWKS} ${problem}`)\n}\n\nfunction isObject(value: unknown): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\nfunction expectMember(\n jwk: JsonObject,\n name: string,\n expected: string,\n required: boolean\n): void {\n if (!(name in jwk) && !required) return\n if (jwk[name] !== expected) {\n throw invalid(`entry member ${name} must be ${expected}`)\n }\n}\n\nfunction readKid(jwk: JsonObject): string {\n const kid = jwk.kid\n if (typeof kid !== \"string\" || !isCanonicalKeyVersion(kid)) {\n throw invalid(\"entry kid must be a canonical positive integer\")\n }\n return kid\n}\n\nfunction readX(jwk: JsonObject): string {\n const x = jwk.x\n const isKey =\n typeof x === \"string\" &&\n BASE64URL.test(x) &&\n Buffer.from(x, \"base64url\").length === ED25519_PUBLIC_KEY_BYTES &&\n Buffer.from(x, \"base64url\").toString(\"base64url\") === x\n if (!isKey) throw invalid(\"entry x must be a 32-byte Base64URL key\")\n return x as string\n}\n\nfunction importEntry(entry: unknown): [string, KeyObject] {\n if (!isObject(entry)) throw invalid(\"entry is not a JSON object\")\n if (\"d\" in entry) throw invalid(\"entry carries private key material (d)\")\n\n expectMember(entry, \"kty\", \"OKP\", true)\n expectMember(entry, \"crv\", \"Ed25519\", true)\n expectMember(entry, \"use\", \"sig\", false)\n expectMember(entry, \"alg\", \"EdDSA\", false)\n\n const kid = readKid(entry)\n const x = readX(entry)\n try {\n const key = createPublicKey({\n key: { kty: \"OKP\", crv: \"Ed25519\", x },\n format: \"jwk\",\n })\n return [kid, key]\n } catch {\n throw invalid(\"entry x is not an Ed25519 key\")\n }\n}\n\n/**\n * Parse the gateway profile JWKS (`{\"keys\": [...]}`) into keys by `kid`.\n *\n * Strict and all-or-nothing: one unsafe entry (private member `d`, other key\n * type or curve, wrong length, non-canonical or duplicated `kid`, `use` other\n * than `sig`, `alg` other than `EdDSA`) refuses the whole document, so the\n * verifier keeps its last valid set. Unknown members are ignored (RFC 7517).\n * Throws `ProfileSignatureConfigurationError`.\n */\nexport function parseProfileJwks(document: string): Map<string, KeyObject> {\n let parsed: unknown\n try {\n parsed = JSON.parse(document)\n } catch {\n throw invalid(\"is not JSON\")\n }\n\n const entries = isObject(parsed) ? parsed.keys : undefined\n if (!Array.isArray(entries) || entries.length === 0) {\n throw invalid(\"has no keys array\")\n }\n\n const keys = new Map<string, KeyObject>()\n for (const entry of entries) {\n const [kid, key] = importEntry(entry)\n if (keys.has(kid)) throw invalid(\"has a duplicated kid\")\n keys.set(kid, key)\n }\n return keys\n}\n","import {\n PROFILE_JWKS_DEFAULT_MAX_AGE_SECONDS,\n PROFILE_JWKS_MAX_MAX_AGE_SECONDS,\n PROFILE_JWKS_MIN_MAX_AGE_SECONDS,\n} from \"../settings.js\"\n\n// Same grammar as Rust `u64::from_str`: optional \"+\", decimal digits.\nconst UNSIGNED_INTEGER = /^\\+?[0-9]+$/\nconst U64_MAX = 18_446_744_073_709_551_615n\n\nfunction readMaxAgeDirective(directive: string): number | undefined {\n const separator = directive.indexOf(\"=\")\n if (separator < 0) return undefined\n\n const name = directive.slice(0, separator).trim().toLowerCase()\n const value = directive.slice(separator + 1).trim()\n if (name !== \"max-age\" || !UNSIGNED_INTEGER.test(value)) return undefined\n\n const seconds = BigInt(value)\n if (seconds > U64_MAX) return undefined\n return seconds > BigInt(PROFILE_JWKS_MAX_MAX_AGE_SECONDS)\n ? PROFILE_JWKS_MAX_MAX_AGE_SECONDS\n : Number(seconds)\n}\n\n/**\n * How long a fetched profile JWKS may be cached, in seconds.\n *\n * Reads the `max-age` directive of a `Cache-Control` value and clamps it to\n * 60..86400; 43200 (12 h) when the header or directive is absent or\n * unreadable. Same rule as the gateway and every SDK (`jwks-vectors.json`).\n */\nexport function readJwksCacheMaxAge(\n cacheControl: string | null | undefined\n): number {\n let announced: number | undefined\n for (const directive of (cacheControl ?? \"\").split(\",\")) {\n announced = readMaxAgeDirective(directive)\n if (announced !== undefined) break\n }\n\n const seconds = announced ?? PROFILE_JWKS_DEFAULT_MAX_AGE_SECONDS\n return Math.min(\n Math.max(seconds, PROFILE_JWKS_MIN_MAX_AGE_SECONDS),\n PROFILE_JWKS_MAX_MAX_AGE_SECONDS\n )\n}\n","import type { KeyObject } from \"node:crypto\"\nimport {\n PROFILE_JWKS_FETCH_TIMEOUT_SECONDS,\n PROFILE_JWKS_MAX_BYTES,\n} from \"../settings.js\"\nimport { parseProfileJwks } from \"./parseProfileJwks.js\"\nimport { readJwksCacheMaxAge } from \"./readJwksCacheMaxAge.js\"\n\n/** A key set read from the gateway, with how long it may be cached. */\nexport interface FetchedProfileJwks {\n keys: ReadonlyMap<string, KeyObject>\n maxAgeSeconds: number\n}\n\n/** How the key store downloads the JWKS (HTTP in production, fakes in tests). */\nexport type ProfileJwksFetcher = (url: URL) => Promise<FetchedProfileJwks>\n\nexport class ProfileJwksFetchError extends Error {\n constructor(problem: string) {\n super(`profile_jwks_fetch_failed: ${problem}`)\n this.name = \"ProfileJwksFetchError\"\n }\n}\n\nasync function readBounded(response: Response): Promise<string> {\n const declared = Number(response.headers.get(\"content-length\") ?? \"0\")\n if (declared > PROFILE_JWKS_MAX_BYTES) {\n throw new ProfileJwksFetchError(\"body exceeds the size limit\")\n }\n\n const chunks: Uint8Array[] = []\n let total = 0\n for await (const chunk of response.body ?? []) {\n total += chunk.byteLength\n if (total > PROFILE_JWKS_MAX_BYTES) {\n throw new ProfileJwksFetchError(\"body exceeds the size limit\")\n }\n chunks.push(chunk)\n }\n return Buffer.concat(chunks).toString(\"utf8\")\n}\n\nasync function download(url: URL): Promise<Response> {\n try {\n return await fetch(url, {\n method: \"GET\",\n headers: { accept: \"application/json\" },\n redirect: \"manual\",\n signal: AbortSignal.timeout(PROFILE_JWKS_FETCH_TIMEOUT_SECONDS * 1000),\n })\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error)\n throw new ProfileJwksFetchError(`request failed: ${detail}`)\n }\n}\n\n/**\n * Download and parse the gateway profile JWKS over HTTP.\n *\n * Bounded: 5 s timeout, 64 KiB body, redirects never followed (a redirect\n * could move the trust anchor to another origin). The cache lifetime comes\n * from `Cache-Control: max-age` (see `readJwksCacheMaxAge`).\n */\nexport const fetchProfileJwks: ProfileJwksFetcher = async (url) => {\n const response = await download(url)\n if (response.status < 200 || response.status > 299) {\n await response.body?.cancel()\n throw new ProfileJwksFetchError(`status ${response.status}`)\n }\n\n const maxAgeSeconds = readJwksCacheMaxAge(response.headers.get(\"cache-control\"))\n let body: string\n try {\n body = await readBounded(response)\n } catch (error) {\n await response.body?.cancel().catch(() => undefined)\n if (error instanceof ProfileJwksFetchError) throw error\n throw new ProfileJwksFetchError(\"body unreadable\")\n }\n\n return { keys: parseProfileJwks(body), maxAgeSeconds }\n}\n","import { isCanonicalKeyVersion } from \"../profileSignatureVerifier.js\"\n\n/**\n * The canonical key version named by a signature's protected header.\n *\n * Used only to decide whether an `unknown_key` rejection deserves a JWKS\n * refetch: a missing or non-canonical `kid` never triggers network work.\n */\nexport function readSignatureKeyVersion(\n signatureHeader: string\n): string | undefined {\n const protectedHeader = signatureHeader.split(\".\")[0] ?? \"\"\n try {\n const header: unknown = JSON.parse(\n Buffer.from(protectedHeader, \"base64url\").toString(\"utf8\")\n )\n const kid =\n typeof header === \"object\" && header !== null\n ? (header as Record<string, unknown>).kid\n : undefined\n return typeof kid === \"string\" && isCanonicalKeyVersion(kid)\n ? kid\n : undefined\n } catch {\n return undefined\n }\n}\n","import { ProfileSignatureError } from \"../errors.js\"\nimport { verifyAndDecodeProfile } from \"../functions/verifyProfileSignature.js\"\nimport type { Profile } from \"../models/profile.js\"\nimport { ProfileSignatureVerifier } from \"../profileSignatureVerifier.js\"\nimport type { ProfileKeyStore } from \"./profileKeyStore.js\"\nimport { readSignatureKeyVersion } from \"./readSignatureKeyVersion.js\"\n\n/**\n * Downstream verifier whose trusted keys come from the gateway JWKS.\n *\n * Enabled by `MYCELIUM_JWKS_URL`; the expected audience is mandatory, so a\n * signed pair issued for another service is always refused. Verification is\n * the shared, local contract; only the keys are remote, refreshed as\n * described in `ProfileKeyStore`. Build it with\n * `prepareProfileSignatureVerifier()` (downloads the keys before serving) or\n * `loadProfileSignatureVerifierFromEnv()` (keys fetched on first use).\n */\nexport class JwksProfileSignatureVerifier {\n readonly store: ProfileKeyStore\n readonly toleranceSeconds: number\n readonly expectedAudience: string\n\n constructor(\n store: ProfileKeyStore,\n toleranceSeconds: number,\n expectedAudience: string\n ) {\n this.store = store\n this.toleranceSeconds = toleranceSeconds\n this.expectedAudience = expectedAudience\n Object.freeze(this)\n }\n\n /** Download the key set before serving; rejects when it cannot. */\n prefetch(): Promise<void> {\n return this.store.prefetch()\n }\n\n /**\n * Verify the signed profile, refetching the JWKS once on an unknown,\n * canonical `kid`. Rejects with `ProfileSignatureError` like\n * `verifyAndDecodeProfile`.\n */\n async verifyAndDecode(\n profileHeader: string,\n signatureHeader: string,\n nowSeconds?: number\n ): Promise<Profile> {\n await this.store.refreshIfStale()\n const { generation } = this.store.current()\n\n try {\n return await this.#verifyWithCurrentKeys(profileHeader, signatureHeader, nowSeconds)\n } catch (error) {\n const deservesRefetch =\n error instanceof ProfileSignatureError &&\n error.reason === \"unknown_key\" &&\n readSignatureKeyVersion(signatureHeader) !== undefined\n if (!deservesRefetch) throw error\n if (!(await this.store.refreshAfterUnknownKey(generation))) throw error\n }\n\n return this.#verifyWithCurrentKeys(profileHeader, signatureHeader, nowSeconds)\n }\n\n #verifyWithCurrentKeys(\n profileHeader: string,\n signatureHeader: string,\n nowSeconds?: number\n ): Promise<Profile> {\n const verifier = new ProfileSignatureVerifier(\n this.store.current().keys,\n this.toleranceSeconds,\n this.expectedAudience\n )\n return verifyAndDecodeProfile(profileHeader, signatureHeader, verifier, nowSeconds)\n }\n}\n","import { ProfileSignatureConfigurationError } from \"../errors.js\"\nimport { PROFILE_JWKS_PATH, PROFILE_JWKS_URL_ENV } from \"../settings.js\"\n\nfunction invalid(problem: string): ProfileSignatureConfigurationError {\n return new ProfileSignatureConfigurationError(\n `${PROFILE_JWKS_URL_ENV} ${problem}`\n )\n}\n\n/** The configured value, with `https://` when it names no scheme. */\nfunction withDefaultScheme(configured: string): string {\n if (configured.includes(\"://\")) return configured\n if (configured === \"\" || configured.startsWith(\"/\")) {\n throw invalid(\"is not an absolute URL\")\n }\n return `https://${configured}`\n}\n\nfunction checkScheme(url: URL, allowInsecureHttp: boolean): void {\n if (url.protocol === \"https:\") return\n if (url.protocol === \"http:\" && allowInsecureHttp) {\n console.warn(\n `[mycelium-sdk] ${PROFILE_JWKS_URL_ENV} uses plain HTTP; development only`\n )\n return\n }\n throw invalid(\"must use https\")\n}\n\n/** The complete endpoint as is, or the gateway base plus the JWKS path. */\nfunction withJwksPath(url: URL): URL {\n if (url.pathname.endsWith(PROFILE_JWKS_PATH)) return url\n\n // `href` keeps an empty `?` or `#`, which `search` and `hash` hide.\n if (/[?#]/.test(url.href)) {\n throw invalid(\"must not carry a query or fragment\")\n }\n\n try {\n return new URL(`${url.href.replace(/\\/+$/, \"\")}${PROFILE_JWKS_PATH}`)\n } catch {\n throw invalid(\"is not an absolute URL\")\n }\n}\n\n/**\n * Validate where the gateway profile JWKS is fetched from.\n *\n * The location comes only from the service configuration, never from a\n * request: following a URL found in the message being verified would let an\n * attacker choose the keys. `https:` is required; `http:` only with the\n * explicit development switch (a warning is logged).\n *\n * Two forms are accepted: the complete endpoint, ending in\n * `PROFILE_JWKS_PATH`, used as is; or the gateway base\n * (`mycelium.example.com`, `https://host/prefix`), to which\n * `PROFILE_JWKS_PATH` is appended. Without a scheme, `https://` is assumed.\n */\nexport function parseProfileJwksUrl(\n raw: string,\n allowInsecureHttp: boolean\n): URL {\n let url: URL\n try {\n url = new URL(withDefaultScheme(raw.trim()))\n } catch (error) {\n if (error instanceof ProfileSignatureConfigurationError) throw error\n throw invalid(\"is not an absolute URL\")\n }\n\n if (url.username !== \"\" || url.password !== \"\") {\n throw invalid(\"must not carry credentials\")\n }\n\n checkScheme(url, allowInsecureHttp)\n return withJwksPath(url)\n}\n","import type { KeyObject } from \"node:crypto\"\nimport type { ProfileJwksFetcher } from \"./fetchProfileJwks.js\"\nimport {\n PROFILE_JWKS_EMPTY_RETRY_SECONDS,\n PROFILE_JWKS_MAX_STALE_SECONDS,\n} from \"../settings.js\"\n\n/** Milliseconds clock, injectable for tests. */\nexport type MonotonicClock = () => number\n\nconst systemClock: MonotonicClock = () => performance.now()\n\nexport interface CachedProfileKeys {\n keys: ReadonlyMap<string, KeyObject>\n generation: number\n}\n\n/**\n * The gateway public keys cached by a downstream verifier.\n *\n * - Fetched lazily on the first request (default) or before serving\n * (`prefetch`, opt-in). Until a set is downloaded, requests fail closed and\n * the fetch is retried at most every `PROFILE_JWKS_EMPTY_RETRY_SECONDS`, so\n * a service started before the gateway recovers within seconds.\n * - Refreshed when `max-age` expires; a failed refresh keeps the last valid\n * set and logs a warning, so a short gateway outage never drops trusted\n * keys. The set stops being trusted `PROFILE_JWKS_MAX_STALE_SECONDS` after\n * it expired, so a retired key cannot verify forever while refreshes fail.\n * - A request never waits for a refresh another request already started\n * while keys are cached: it verifies with the cached set.\n * - Refetched once when a signature names an unknown `kid`, at most once per\n * cooldown (measured from the end of the last attempt), and single-flight:\n * concurrent requests share one fetch, and waiters that see a newer\n * generation reuse it without fetching again.\n */\nexport class ProfileKeyStore {\n readonly #url: URL\n readonly #fetcher: ProfileJwksFetcher\n readonly #cooldownMs: number\n readonly #clock: MonotonicClock\n #keys: ReadonlyMap<string, KeyObject> = new Map()\n #generation = 0\n #freshUntil: number | undefined\n #lastAttempt: number | undefined\n #inFlight: Promise<boolean> | undefined\n\n constructor(\n url: URL,\n fetcher: ProfileJwksFetcher,\n cooldownSeconds: number,\n clock: MonotonicClock = systemClock\n ) {\n this.#url = url\n this.#fetcher = fetcher\n this.#cooldownMs = cooldownSeconds * 1000\n this.#clock = clock\n }\n\n get url(): URL {\n return new URL(this.#url)\n }\n\n /** The trusted keys now, and the generation they belong to. */\n current(): CachedProfileKeys {\n return { keys: this.#trustedKeys(), generation: this.#generation }\n }\n\n /** The cached keys, or none once they outlived the maximum staleness. */\n #trustedKeys(): ReadonlyMap<string, KeyObject> {\n const outlived =\n this.#freshUntil !== undefined &&\n this.#clock() >= this.#freshUntil + PROFILE_JWKS_MAX_STALE_SECONDS * 1000\n return outlived ? new Map() : this.#keys\n }\n\n /** Fetch the set now; any failure rejects (startup must abort). */\n async prefetch(): Promise<void> {\n await this.#inFlight?.catch(() => undefined)\n const fetching = this.#fetchAndStore()\n this.#inFlight = fetching.then(\n () => true,\n () => false\n )\n try {\n await fetching\n } finally {\n this.#inFlight = undefined\n }\n }\n\n /** Refresh when the cached set expired (or was never fetched). */\n async refreshIfStale(): Promise<void> {\n const stale =\n this.#freshUntil === undefined || this.#clock() >= this.#freshUntil\n if (!stale) return\n if (this.#generation > 0 && this.#inFlight !== undefined) return\n await this.#refreshFrom(this.#generation)\n }\n\n /** Refetch after an unknown `kid`; `true` when newer keys are available. */\n refreshAfterUnknownKey(seenGeneration: number): Promise<boolean> {\n return this.#refreshFrom(seenGeneration)\n }\n\n async #refreshFrom(seenGeneration: number): Promise<boolean> {\n while (this.#inFlight !== undefined) {\n await this.#inFlight.catch(() => undefined)\n }\n\n if (this.#generation !== seenGeneration) return true\n const coolingDown =\n this.#lastAttempt !== undefined &&\n this.#clock() - this.#lastAttempt < this.#retryIntervalMs()\n if (coolingDown) return false\n\n this.#inFlight = this.#fetchAndStore().then(\n () => true,\n (error: unknown) => {\n logRefreshFailure(error)\n return false\n }\n )\n try {\n return await this.#inFlight\n } finally {\n this.#inFlight = undefined\n }\n }\n\n /** The cooldown, shortened while no key set was ever stored. */\n #retryIntervalMs(): number {\n if (this.#generation > 0) return this.#cooldownMs\n return Math.min(this.#cooldownMs, PROFILE_JWKS_EMPTY_RETRY_SECONDS * 1000)\n }\n\n async #fetchAndStore(): Promise<void> {\n let fetched\n try {\n fetched = await this.#fetcher(new URL(this.#url))\n } finally {\n this.#lastAttempt = this.#clock()\n }\n\n this.#keys = new Map(fetched.keys)\n this.#generation += 1\n this.#freshUntil = this.#clock() + fetched.maxAgeSeconds * 1000\n }\n}\n\nfunction logRefreshFailure(error: unknown): void {\n const reason = error instanceof Error ? error.message : String(error)\n console.warn(\n `[mycelium-sdk] profile_signature.jwks outcome=refresh_failed reason=${reason}; keeping the last valid profile JWKS`\n )\n}\n","import { ProfileSignatureConfigurationError } from \"./errors.js\"\nimport {\n fetchProfileJwks,\n type ProfileJwksFetcher,\n} from \"./jwks/fetchProfileJwks.js\"\nimport { JwksProfileSignatureVerifier } from \"./jwks/jwksProfileSignatureVerifier.js\"\nimport { parseProfileJwksUrl } from \"./jwks/parseProfileJwksUrl.js\"\nimport { ProfileKeyStore } from \"./jwks/profileKeyStore.js\"\nimport {\n DEFAULT_PROFILE_SIGNATURE_TOLERANCE_SECONDS,\n MAX_PROFILE_SIGNATURE_TOLERANCE_SECONDS,\n PROFILE_JWKS_ALLOW_INSECURE_HTTP_ENV,\n PROFILE_JWKS_REFETCH_COOLDOWN_SECONDS,\n PROFILE_JWKS_URL_ENV,\n PROFILE_SIGNATURE_AUDIENCE_ENV,\n PROFILE_SIGNATURE_TOLERANCE_ENV,\n} from \"./settings.js\"\n\nconst CANONICAL_POSITIVE_INTEGER = /^[1-9][0-9]*$/\n\nexport type EnvironmentSource = Readonly<Record<string, string | undefined>>\n\nfunction parseTolerance(env: EnvironmentSource): number {\n const raw = env[PROFILE_SIGNATURE_TOLERANCE_ENV]\n if (raw === undefined) return DEFAULT_PROFILE_SIGNATURE_TOLERANCE_SECONDS\n\n const trimmed = raw.trim()\n const value = Number(trimmed)\n if (\n !CANONICAL_POSITIVE_INTEGER.test(trimmed) ||\n !(value <= MAX_PROFILE_SIGNATURE_TOLERANCE_SECONDS)\n ) {\n throw new ProfileSignatureConfigurationError(\n `${PROFILE_SIGNATURE_TOLERANCE_ENV} must be an integer between 1 and ${MAX_PROFILE_SIGNATURE_TOLERANCE_SECONDS}`\n )\n }\n\n return value\n}\n\nfunction parseAudience(env: EnvironmentSource): string | undefined {\n const raw = env[PROFILE_SIGNATURE_AUDIENCE_ENV]\n if (raw === undefined) return undefined\n\n if (raw.trim() === \"\") {\n throw new ProfileSignatureConfigurationError(\n `${PROFILE_SIGNATURE_AUDIENCE_ENV} must not be empty`\n )\n }\n\n return raw\n}\n\nfunction parseInsecureSwitch(env: EnvironmentSource): boolean {\n const raw = env[PROFILE_JWKS_ALLOW_INSECURE_HTTP_ENV]?.trim()\n if (raw === undefined || raw === \"false\") return false\n if (raw === \"true\") return true\n\n throw new ProfileSignatureConfigurationError(\n `${PROFILE_JWKS_ALLOW_INSECURE_HTTP_ENV} must be true or false`\n )\n}\n\n/**\n * Build the verifier from an environment snapshot (default `process.env`).\n *\n * Returns `undefined` when `MYCELIUM_JWKS_URL` is absent (verification\n * disabled, legacy behavior). With the URL set, `MYC_PROFILE_SIGNATURE_AUDIENCE`\n * is required. Every present setting is validated even when disabled; an\n * invalid one throws `ProfileSignatureConfigurationError`, never \"disabled\".\n *\n * Synchronous and network-free: the keys are fetched on first use. Prefer\n * `prepareProfileSignatureVerifier()` at startup to download them before\n * serving.\n */\nexport function loadProfileSignatureVerifierFromEnv(\n env: EnvironmentSource = process.env,\n fetcher: ProfileJwksFetcher = fetchProfileJwks\n): JwksProfileSignatureVerifier | undefined {\n const toleranceSeconds = parseTolerance(env)\n const audience = parseAudience(env)\n const allowInsecureHttp = parseInsecureSwitch(env)\n\n const rawUrl = env[PROFILE_JWKS_URL_ENV]\n if (rawUrl === undefined) return undefined\n\n const url = parseProfileJwksUrl(rawUrl, allowInsecureHttp)\n if (audience === undefined) {\n throw new ProfileSignatureConfigurationError(\n `${PROFILE_SIGNATURE_AUDIENCE_ENV} is required when ${PROFILE_JWKS_URL_ENV} is set`\n )\n }\n\n const store = new ProfileKeyStore(\n url,\n fetcher,\n PROFILE_JWKS_REFETCH_COOLDOWN_SECONDS\n )\n return new JwksProfileSignatureVerifier(store, toleranceSeconds, audience)\n}\n\n/**\n * Opt-in: read the settings and download the gateway JWKS before serving.\n *\n * Rejects on invalid settings or when the keys cannot be fetched. Without\n * it, the Express and Fastify integrations download the keys on the first\n * signed request, so the service does not depend on the gateway to start.\n * Resolves `undefined` when verification is disabled.\n */\nexport async function prepareProfileSignatureVerifier(\n env: EnvironmentSource = process.env,\n fetcher: ProfileJwksFetcher = fetchProfileJwks\n): Promise<JwksProfileSignatureVerifier | undefined> {\n const verifier = loadProfileSignatureVerifierFromEnv(env, fetcher)\n await verifier?.prefetch()\n return verifier\n}\n","import type { IncomingMessage } from \"node:http\"\nimport { ProfileSignatureError } from \"./errors.js\"\nimport type { JwksProfileSignatureVerifier } from \"./jwks/jwksProfileSignatureVerifier.js\"\nimport type { Profile } from \"./models/profile.js\"\nimport { loadProfileSignatureVerifierFromEnv } from \"./profileSignatureConfig.js\"\nimport {\n DEFAULT_PROFILE_KEY,\n DEFAULT_PROFILE_SIGNATURE_KEY,\n} from \"./settings.js\"\n\nexport const SIGNATURE_REJECTION_DETAIL = \"Unable to verify Mycelium profile\"\nexport const SIGNATURE_INTERNAL_DETAIL =\n \"Unable to check user identity. Please contact administrators\"\n\n/** Log-safe reason only. Result ignored; returned promises are awaited safely. */\nexport type SignatureRejectionListener = (reason: string) => unknown\n\nasync function reportRejection(\n listener: SignatureRejectionListener | undefined,\n reason: string\n): Promise<boolean> {\n try {\n await listener?.(reason)\n return true\n } catch {\n return false\n }\n}\n\nexport type SignatureVerificationOutcome =\n | { ok: true; profile: Profile }\n | { ok: false; status: 403 | 500; detail: string }\n\nfunction singleValue(\n values: string[] | undefined,\n missingReason: \"missing_profile\" | \"missing_signature\"\n): string {\n if (values !== undefined && values.length > 1) {\n throw new ProfileSignatureError(\"duplicate_header\")\n }\n\n const value = values?.[0]\n if (value === undefined || value === \"\") {\n throw new ProfileSignatureError(missingReason)\n }\n\n return value\n}\n\n/**\n * Every value of a header, as received.\n *\n * `IncomingMessage.headers` joins repeated custom headers with \", \", which\n * would hide a duplicate; `headersDistinct` keeps each occurrence. Request\n * shims that lack it (for example Fastify's `inject`) fall back to\n * `rawHeaders`, then to `headers`.\n */\nfunction receivedValues(\n message: IncomingMessage,\n name: string\n): string[] | undefined {\n const distinct = (message.headersDistinct as\n | NodeJS.Dict<string[]>\n | undefined)?.[name]\n if (distinct !== undefined) return distinct\n\n const raw: unknown = message.rawHeaders\n if (Array.isArray(raw) && raw.length > 0) {\n const values = raw.filter(\n (_value, index) =>\n index % 2 === 1 && String(raw[index - 1]).toLowerCase() === name\n ) as string[]\n return values.length === 0 ? undefined : values\n }\n\n const value = message.headers[name]\n if (value === undefined) return undefined\n return Array.isArray(value) ? value : [value]\n}\n\nfunction distinctValues(\n message: IncomingMessage,\n name: string\n): string[] | undefined {\n // Neither Base64 nor a compact JWS contains \",\": a comma can only come\n // from repeated headers joined by the runtime or a proxy.\n return receivedValues(message, name)?.flatMap((value) =>\n value.split(\",\").map((part) => part.trim())\n )\n}\n\n/**\n * Authenticate and decode the profile carried by a request.\n *\n * Never throws: rejections map to 403, anything unexpected to 500, both with\n * generic details. The caller must not run the handler unless `ok`.\n */\nexport async function verifyRequestProfile(\n message: IncomingMessage,\n verifier: JwksProfileSignatureVerifier,\n onRejected?: SignatureRejectionListener\n): Promise<SignatureVerificationOutcome> {\n try {\n const profileHeader = singleValue(\n distinctValues(message, DEFAULT_PROFILE_KEY),\n \"missing_profile\"\n )\n const signatureHeader = singleValue(\n distinctValues(message, DEFAULT_PROFILE_SIGNATURE_KEY),\n \"missing_signature\"\n )\n const profile = await verifier.verifyAndDecode(\n profileHeader,\n signatureHeader\n )\n return { ok: true, profile }\n } catch (error) {\n if (error instanceof ProfileSignatureError) {\n if (!(await reportRejection(onRejected, error.reason))) {\n return { ok: false, status: 500, detail: SIGNATURE_INTERNAL_DETAIL }\n }\n return { ok: false, status: 403, detail: SIGNATURE_REJECTION_DETAIL }\n }\n await reportRejection(onRejected, \"internal_error\")\n return { ok: false, status: 500, detail: SIGNATURE_INTERNAL_DETAIL }\n }\n}\n\nlet unverifiedSignatureWarned = false\n\n/**\n * Log once per process that a signed profile arrived while verification is\n * off. The usual cause is a service that forgot `MYCELIUM_JWKS_URL`: the\n * profile is still trusted as received, exactly as before.\n */\nexport function warnWhenSignatureIsIgnored(message: IncomingMessage): void {\n if (unverifiedSignatureWarned) return\n if (message.headers[DEFAULT_PROFILE_SIGNATURE_KEY] === undefined) return\n\n unverifiedSignatureWarned = true\n console.warn(\n \"[mycelium-sdk] profile_signature.verify outcome=skipped: received a signed profile but MYCELIUM_JWKS_URL is not set; the signature is not verified\"\n )\n}\n\n/** Test-only: allow the one-time warning to be observed again. */\nexport function resetSignatureIgnoredWarning(): void {\n unverifiedSignatureWarned = false\n}\n\nlet sharedVerifier: JwksProfileSignatureVerifier | undefined\n\n/**\n * The verifier configured by `process.env`, one per process: every Express\n * factory call and the Fastify plugin share its key cache, fetches and\n * cooldowns. The environment is read on each call until verification is\n * enabled (invalid settings throw, \"disabled\" is never remembered); from then\n * on the same verifier is returned.\n */\nexport function sharedProfileSignatureVerifier():\n | JwksProfileSignatureVerifier\n | undefined {\n sharedVerifier ??= loadProfileSignatureVerifierFromEnv()\n return sharedVerifier\n}\n\n/** Test-only: forget the shared verifier so the environment is read again. */\nexport function resetSharedProfileSignatureVerifier(): void {\n sharedVerifier = undefined\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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,MAAI,UAAU,OAAW,QAAO;AAChC,SAAO,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;AAC9C;AAEA,SAAS,eACP,SACA,MACsB;AAGtB,SAAO,eAAe,SAAS,IAAI,GAAG;AAAA,IAAQ,CAAC,UAC7C,MAAM,MAAM,GAAG,EAAE,IAAI,CAAC,SAAS,KAAK,KAAK,CAAC;AAAA,EAC5C;AACF;AAQA,eAAsB,qBACpB,SACA,UACA,YACuC;AACvC,MAAI;AACF,UAAM,gBAAgB;AAAA,MACpB,eAAe,SAAS,mBAAmB;AAAA,MAC3C;AAAA,IACF;AACA,UAAM,kBAAkB;AAAA,MACtB,eAAe,SAAS,6BAA6B;AAAA,MACrD;AAAA,IACF;AACA,UAAM,UAAU,MAAM,SAAS;AAAA,MAC7B;AAAA,MACA;AAAA,IACF;AACA,WAAO,EAAE,IAAI,MAAM,QAAQ;AAAA,EAC7B,SAAS,OAAO;AACd,QAAI,iBAAiB,uBAAuB;AAC1C,UAAI,CAAE,MAAM,gBAAgB,YAAY,MAAM,MAAM,GAAI;AACtD,eAAO,EAAE,IAAI,OAAO,QAAQ,KAAK,QAAQ,0BAA0B;AAAA,MACrE;AACA,aAAO,EAAE,IAAI,OAAO,QAAQ,KAAK,QAAQ,2BAA2B;AAAA,IACtE;AACA,UAAM,gBAAgB,YAAY,gBAAgB;AAClD,WAAO,EAAE,IAAI,OAAO,QAAQ,KAAK,QAAQ,0BAA0B;AAAA,EACrE;AACF;","names":["import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","tagRecordsOrUrls","import_zod","import_zod","isObject","joseErrors","import_node_crypto","invalid","CANONICAL_POSITIVE_INTEGER"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import { P as Profile } from './
|
|
2
|
-
export { A as AccountMetaKey,
|
|
1
|
+
import { P as Profile, a as ProfileJwksFetcher, J as JwksProfileSignatureVerifier } from './profileSignatureEnforcement-C-bhVkEp.cjs';
|
|
2
|
+
export { A as AccountMetaKey, b as AccountMetaKeySchema, C as CachedProfileKeys, F as FetchedProfileJwks, L as LicensedResource, c as LicensedResourceSchema, d as LicensedResources, e as LicensedResourcesSchema, M as MonotonicClock, f as Permission, g as PermissionSchema, h as ProfileData, i as ProfileJwksFetchError, j as ProfileKeyStore, k as ProfileMeta, l as ProfileMetaSchema, m as ProfileSchema, R as RelatedAccounts, n as SIGNATURE_INTERNAL_DETAIL, o as SIGNATURE_REJECTION_DETAIL, S as SignatureRejectionListener, p as SignatureVerificationOutcome, q as fetchProfileJwks, r as licensedResourceFromUrlString, s as permissionFromInt, t as permissionToInt, u as toLicensesVector, v as verifyRequestProfile } from './profileSignatureEnforcement-C-bhVkEp.cjs';
|
|
3
3
|
import { z } from 'zod';
|
|
4
|
+
import { KeyObject } from 'node:crypto';
|
|
5
|
+
import 'node:http';
|
|
4
6
|
|
|
5
7
|
declare class MyceliumError extends Error {
|
|
6
8
|
code?: string;
|
|
@@ -17,6 +19,26 @@ declare class InsufficientLicensesError extends MyceliumError {
|
|
|
17
19
|
declare class ProfileDecodingError extends MyceliumError {
|
|
18
20
|
constructor(message: string);
|
|
19
21
|
}
|
|
22
|
+
declare const PROFILE_SIGNATURE_INVALID_CODE = "MYC_PROFILE_SIGNATURE_INVALID";
|
|
23
|
+
declare const PROFILE_SIGNATURE_CONFIG_INVALID_CODE = "MYC_PROFILE_SIGNATURE_CONFIG_INVALID";
|
|
24
|
+
type ProfileSignatureRejectionReason = "missing_profile" | "missing_signature" | "duplicate_header" | "malformed_signature" | "unsupported_algorithm" | "unknown_key" | "invalid_signature" | "invalid_claims" | "timestamp_out_of_tolerance" | "profile_hash_mismatch" | "audience_mismatch" | "invalid_profile";
|
|
25
|
+
/**
|
|
26
|
+
* Invalid verification configuration (`MYCELIUM_JWKS_URL` and related
|
|
27
|
+
* variables) or an unsafe/malformed gateway JWKS. A malformed setting must
|
|
28
|
+
* stop the service instead of silently disabling verification. Messages
|
|
29
|
+
* name variables, never values.
|
|
30
|
+
*/
|
|
31
|
+
declare class ProfileSignatureConfigurationError extends MyceliumError {
|
|
32
|
+
constructor(message: string);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Signature rejected. `reason` is stable and log-safe; HTTP integrations
|
|
36
|
+
* answer with a generic message and never expose it to clients.
|
|
37
|
+
*/
|
|
38
|
+
declare class ProfileSignatureError extends MyceliumError {
|
|
39
|
+
readonly reason: ProfileSignatureRejectionReason;
|
|
40
|
+
constructor(reason: ProfileSignatureRejectionReason);
|
|
41
|
+
}
|
|
20
42
|
|
|
21
43
|
declare const DEFAULT_PROFILE_KEY = "x-mycelium-profile";
|
|
22
44
|
declare const DEFAULT_EMAIL_KEY = "x-mycelium-email";
|
|
@@ -25,6 +47,30 @@ declare const DEFAULT_MYCELIUM_ROLE_KEY = "x-mycelium-role";
|
|
|
25
47
|
declare const DEFAULT_REQUEST_ID_KEY = "x-mycelium-request-id";
|
|
26
48
|
declare const DEFAULT_CONNECTION_STRING_KEY = "x-mycelium-connection-string";
|
|
27
49
|
declare const DEFAULT_TENANT_ID_KEY = "x-mycelium-tenant-id";
|
|
50
|
+
declare const DEFAULT_PROFILE_SIGNATURE_KEY = "x-mycelium-profile-signature";
|
|
51
|
+
/** URL of the gateway profile JWKS; its presence enables verification. */
|
|
52
|
+
declare const PROFILE_JWKS_URL_ENV = "MYCELIUM_JWKS_URL";
|
|
53
|
+
/** Development-only switch accepting an `http://` JWKS URL ("true"/"false"). */
|
|
54
|
+
declare const PROFILE_JWKS_ALLOW_INSECURE_HTTP_ENV = "MYCELIUM_JWKS_ALLOW_INSECURE_HTTP";
|
|
55
|
+
/** Path where the gateway publishes the profile JWKS. */
|
|
56
|
+
declare const PROFILE_JWKS_PATH = "/.well-known/mycelium-profile-jwks.json";
|
|
57
|
+
declare const PROFILE_JWKS_FETCH_TIMEOUT_SECONDS = 5;
|
|
58
|
+
declare const PROFILE_JWKS_MAX_BYTES: number;
|
|
59
|
+
/** Minimum interval between JWKS requests (unknown `kid`, failed refresh). */
|
|
60
|
+
declare const PROFILE_JWKS_REFETCH_COOLDOWN_SECONDS = 30;
|
|
61
|
+
/** Shorter retry interval while no key set was ever downloaded (first use). */
|
|
62
|
+
declare const PROFILE_JWKS_EMPTY_RETRY_SECONDS = 5;
|
|
63
|
+
declare const PROFILE_JWKS_DEFAULT_MAX_AGE_SECONDS = 43200;
|
|
64
|
+
declare const PROFILE_JWKS_MIN_MAX_AGE_SECONDS = 60;
|
|
65
|
+
declare const PROFILE_JWKS_MAX_MAX_AGE_SECONDS = 86400;
|
|
66
|
+
/** How long an expired key set stays trusted while refreshes fail. */
|
|
67
|
+
declare const PROFILE_JWKS_MAX_STALE_SECONDS = 86400;
|
|
68
|
+
declare const PROFILE_SIGNATURE_TOLERANCE_ENV = "MYC_PROFILE_SIGNATURE_TOLERANCE_SECONDS";
|
|
69
|
+
declare const PROFILE_SIGNATURE_AUDIENCE_ENV = "MYC_PROFILE_SIGNATURE_AUDIENCE";
|
|
70
|
+
declare const DEFAULT_PROFILE_SIGNATURE_TOLERANCE_SECONDS = 60;
|
|
71
|
+
/** Largest accepted tolerance: it is the replay window of a signature. */
|
|
72
|
+
declare const MAX_PROFILE_SIGNATURE_TOLERANCE_SECONDS = 300;
|
|
73
|
+
declare const MAX_PROFILE_SIGNATURE_BYTES = 4096;
|
|
28
74
|
|
|
29
75
|
declare const VerboseStatusSchema: z.ZodEnum<["unverified", "verified", "inactive", "archived", "deleted", "unknown"]>;
|
|
30
76
|
type VerboseStatus = z.infer<typeof VerboseStatusSchema>;
|
|
@@ -135,4 +181,104 @@ type SafeDecodeResult = {
|
|
|
135
181
|
declare function safeDecodeAndDecompressProfileFromBase64(input: string | Buffer, opts?: DecodeOptions): SafeDecodeResult;
|
|
136
182
|
declare function compressAndEncodeProfileToBase64(profile: Profile): string;
|
|
137
183
|
|
|
138
|
-
|
|
184
|
+
/**
|
|
185
|
+
* One verification pass: the trusted Ed25519 keys at an instant, by `kid`,
|
|
186
|
+
* and the rules. Immutable; the key map is private.
|
|
187
|
+
*
|
|
188
|
+
* The JWKS-backed verifier builds one per request from its cached keys; the
|
|
189
|
+
* contract tests build one directly. The audience is optional here so the
|
|
190
|
+
* shared vectors can exercise both cases; a configured service always has
|
|
191
|
+
* one (see `JwksProfileSignatureVerifier`).
|
|
192
|
+
*/
|
|
193
|
+
declare class ProfileSignatureVerifier {
|
|
194
|
+
#private;
|
|
195
|
+
readonly toleranceSeconds: number;
|
|
196
|
+
readonly expectedAudience: string | undefined;
|
|
197
|
+
constructor(keys: ReadonlyMap<string, KeyObject>, toleranceSeconds: number, expectedAudience?: string);
|
|
198
|
+
keyFor(kid: string): KeyObject | undefined;
|
|
199
|
+
get keyVersions(): string[];
|
|
200
|
+
}
|
|
201
|
+
/** Canonical decimal key version (`kid`): 1..4294967295, no leading zeros. */
|
|
202
|
+
declare function isCanonicalKeyVersion(raw: string): boolean;
|
|
203
|
+
|
|
204
|
+
/** Unpadded Base64URL SHA-256 of the exact profile header value. */
|
|
205
|
+
declare function profileHeaderHash(profileHeader: string): string;
|
|
206
|
+
/**
|
|
207
|
+
* Verify that `signatureHeader` authenticates `profileHeader`.
|
|
208
|
+
*
|
|
209
|
+
* Rejects with `ProfileSignatureError` (stable `reason`) on any failure, and
|
|
210
|
+
* with `RangeError` for an invalid verifier clock (internal error). Does not
|
|
211
|
+
* decode the profile; see `verifyAndDecodeProfile`.
|
|
212
|
+
*/
|
|
213
|
+
declare function verifyProfileSignature(profileHeader: string, signatureHeader: string, verifier: ProfileSignatureVerifier, nowSeconds?: number): Promise<void>;
|
|
214
|
+
/** Verify the signature, then decode the profile (`invalid_profile`). */
|
|
215
|
+
declare function verifyAndDecodeProfile(profileHeader: string, signatureHeader: string, verifier: ProfileSignatureVerifier, nowSeconds?: number): Promise<Profile>;
|
|
216
|
+
|
|
217
|
+
type EnvironmentSource = Readonly<Record<string, string | undefined>>;
|
|
218
|
+
/**
|
|
219
|
+
* Build the verifier from an environment snapshot (default `process.env`).
|
|
220
|
+
*
|
|
221
|
+
* Returns `undefined` when `MYCELIUM_JWKS_URL` is absent (verification
|
|
222
|
+
* disabled, legacy behavior). With the URL set, `MYC_PROFILE_SIGNATURE_AUDIENCE`
|
|
223
|
+
* is required. Every present setting is validated even when disabled; an
|
|
224
|
+
* invalid one throws `ProfileSignatureConfigurationError`, never "disabled".
|
|
225
|
+
*
|
|
226
|
+
* Synchronous and network-free: the keys are fetched on first use. Prefer
|
|
227
|
+
* `prepareProfileSignatureVerifier()` at startup to download them before
|
|
228
|
+
* serving.
|
|
229
|
+
*/
|
|
230
|
+
declare function loadProfileSignatureVerifierFromEnv(env?: EnvironmentSource, fetcher?: ProfileJwksFetcher): JwksProfileSignatureVerifier | undefined;
|
|
231
|
+
/**
|
|
232
|
+
* Opt-in: read the settings and download the gateway JWKS before serving.
|
|
233
|
+
*
|
|
234
|
+
* Rejects on invalid settings or when the keys cannot be fetched. Without
|
|
235
|
+
* it, the Express and Fastify integrations download the keys on the first
|
|
236
|
+
* signed request, so the service does not depend on the gateway to start.
|
|
237
|
+
* Resolves `undefined` when verification is disabled.
|
|
238
|
+
*/
|
|
239
|
+
declare function prepareProfileSignatureVerifier(env?: EnvironmentSource, fetcher?: ProfileJwksFetcher): Promise<JwksProfileSignatureVerifier | undefined>;
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Parse the gateway profile JWKS (`{"keys": [...]}`) into keys by `kid`.
|
|
243
|
+
*
|
|
244
|
+
* Strict and all-or-nothing: one unsafe entry (private member `d`, other key
|
|
245
|
+
* type or curve, wrong length, non-canonical or duplicated `kid`, `use` other
|
|
246
|
+
* than `sig`, `alg` other than `EdDSA`) refuses the whole document, so the
|
|
247
|
+
* verifier keeps its last valid set. Unknown members are ignored (RFC 7517).
|
|
248
|
+
* Throws `ProfileSignatureConfigurationError`.
|
|
249
|
+
*/
|
|
250
|
+
declare function parseProfileJwks(document: string): Map<string, KeyObject>;
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Validate where the gateway profile JWKS is fetched from.
|
|
254
|
+
*
|
|
255
|
+
* The location comes only from the service configuration, never from a
|
|
256
|
+
* request: following a URL found in the message being verified would let an
|
|
257
|
+
* attacker choose the keys. `https:` is required; `http:` only with the
|
|
258
|
+
* explicit development switch (a warning is logged).
|
|
259
|
+
*
|
|
260
|
+
* Two forms are accepted: the complete endpoint, ending in
|
|
261
|
+
* `PROFILE_JWKS_PATH`, used as is; or the gateway base
|
|
262
|
+
* (`mycelium.example.com`, `https://host/prefix`), to which
|
|
263
|
+
* `PROFILE_JWKS_PATH` is appended. Without a scheme, `https://` is assumed.
|
|
264
|
+
*/
|
|
265
|
+
declare function parseProfileJwksUrl(raw: string, allowInsecureHttp: boolean): URL;
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* How long a fetched profile JWKS may be cached, in seconds.
|
|
269
|
+
*
|
|
270
|
+
* Reads the `max-age` directive of a `Cache-Control` value and clamps it to
|
|
271
|
+
* 60..86400; 43200 (12 h) when the header or directive is absent or
|
|
272
|
+
* unreadable. Same rule as the gateway and every SDK (`jwks-vectors.json`).
|
|
273
|
+
*/
|
|
274
|
+
declare function readJwksCacheMaxAge(cacheControl: string | null | undefined): number;
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* The canonical key version named by a signature's protected header.
|
|
278
|
+
*
|
|
279
|
+
* Used only to decide whether an `unknown_key` rejection deserves a JWKS
|
|
280
|
+
* refetch: a missing or non-canonical `kid` never triggers network work.
|
|
281
|
+
*/
|
|
282
|
+
declare function readSignatureKeyVersion(signatureHeader: string): string | undefined;
|
|
283
|
+
|
|
284
|
+
export { DEFAULT_CONNECTION_STRING_KEY, DEFAULT_EMAIL_KEY, DEFAULT_MYCELIUM_ROLE_KEY, DEFAULT_PROFILE_KEY, DEFAULT_PROFILE_SIGNATURE_KEY, DEFAULT_PROFILE_SIGNATURE_TOLERANCE_SECONDS, DEFAULT_REQUEST_ID_KEY, DEFAULT_SCOPE_KEY, DEFAULT_TENANT_ID_KEY, type DecodeOptions, type EnvironmentSource, InsufficientLicensesError, InsufficientPrivilegesError, JwksProfileSignatureVerifier, MAX_PROFILE_SIGNATURE_BYTES, MAX_PROFILE_SIGNATURE_TOLERANCE_SECONDS, MyceliumError, type Owner, OwnerSchema, PROFILE_JWKS_ALLOW_INSECURE_HTTP_ENV, PROFILE_JWKS_DEFAULT_MAX_AGE_SECONDS, PROFILE_JWKS_EMPTY_RETRY_SECONDS, PROFILE_JWKS_FETCH_TIMEOUT_SECONDS, PROFILE_JWKS_MAX_BYTES, PROFILE_JWKS_MAX_MAX_AGE_SECONDS, PROFILE_JWKS_MAX_STALE_SECONDS, PROFILE_JWKS_MIN_MAX_AGE_SECONDS, PROFILE_JWKS_PATH, PROFILE_JWKS_REFETCH_COOLDOWN_SECONDS, PROFILE_JWKS_URL_ENV, PROFILE_SIGNATURE_AUDIENCE_ENV, PROFILE_SIGNATURE_CONFIG_INVALID_CODE, PROFILE_SIGNATURE_INVALID_CODE, PROFILE_SIGNATURE_TOLERANCE_ENV, Profile, ProfileDecodingError, ProfileJwksFetcher, ProfileSignatureConfigurationError, ProfileSignatureError, type ProfileSignatureRejectionReason, ProfileSignatureVerifier, type SafeDecodeResult, type TenantOwnership, TenantOwnershipSchema, type TenantsOwnership, TenantsOwnershipSchema, type VerboseStatus, VerboseStatusSchema, compressAndEncodeProfileToBase64, decodeAndDecompressProfileFromBase64, isCanonicalKeyVersion, loadProfileSignatureVerifierFromEnv, parseProfileJwks, parseProfileJwksUrl, prepareProfileSignatureVerifier, profileHeaderHash, readJwksCacheMaxAge, readSignatureKeyVersion, safeDecodeAndDecompressProfileFromBase64, tenantOwnershipFromUrlString, toOwnershipVector, verifyAndDecodeProfile, verifyProfileSignature };
|