@lepistabioinformatics/mycelium-sdk 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../node_modules/fastify-plugin/lib/getPluginName.js","../../node_modules/fastify-plugin/lib/toCamelCase.js","../../node_modules/fastify-plugin/plugin.js","../../src/fastify/index.ts","../../src/functions/decodeAndDecompressProfileFromBase64.ts","../../src/errors.ts","../../src/models/profile.ts","../../src/models/accountMetaKey.ts","../../src/models/licensedResources.ts","../../src/models/licensedResource.ts","../../src/models/permission.ts","../../src/models/owner.ts","../../src/models/tenantsOwnership.ts","../../src/models/tenantOwnership.ts","../../src/models/verboseStatus.ts","../../src/settings.ts"],"sourcesContent":["'use strict'\n\nconst fpStackTracePattern = /at\\s(?:.*\\.)?plugin\\s.*\\n\\s*(.*)/\nconst fileNamePattern = /(\\w*(\\.\\w*)*)\\..*/\n\nmodule.exports = function getPluginName (fn) {\n if (fn.name.length > 0) return fn.name\n\n const stackTraceLimit = Error.stackTraceLimit\n Error.stackTraceLimit = 10\n try {\n throw new Error('anonymous function')\n } catch (e) {\n Error.stackTraceLimit = stackTraceLimit\n return extractPluginName(e.stack)\n }\n}\n\nfunction extractPluginName (stack) {\n const m = stack.match(fpStackTracePattern)\n\n // get last section of path and match for filename\n return m ? m[1].split(/[/\\\\]/).slice(-1)[0].match(fileNamePattern)[1] : 'anonymous'\n}\nmodule.exports.extractPluginName = extractPluginName\n","'use strict'\n\nmodule.exports = function toCamelCase (name) {\n if (name[0] === '@') {\n name = name.slice(1).replace('/', '-')\n }\n return name.replace(/-(.)/g, function (match, g1) {\n return g1.toUpperCase()\n })\n}\n","'use strict'\n\nconst getPluginName = require('./lib/getPluginName')\nconst toCamelCase = require('./lib/toCamelCase')\n\nlet count = 0\n\nfunction plugin (fn, options = {}) {\n let autoName = false\n\n if (fn.default !== undefined) {\n // Support for 'export default' behaviour in transpiled ECMAScript module\n fn = fn.default\n }\n\n if (typeof fn !== 'function') {\n throw new TypeError(\n `fastify-plugin expects a function, instead got a '${typeof fn}'`\n )\n }\n\n if (typeof options === 'string') {\n options = {\n fastify: options\n }\n }\n\n if (\n typeof options !== 'object' ||\n Array.isArray(options) ||\n options === null\n ) {\n throw new TypeError('The options object should be an object')\n }\n\n if (options.fastify !== undefined && typeof options.fastify !== 'string') {\n throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof options.fastify}'`)\n }\n\n if (!options.name) {\n autoName = true\n options.name = getPluginName(fn) + '-auto-' + count++\n }\n\n fn[Symbol.for('skip-override')] = options.encapsulate !== true\n fn[Symbol.for('fastify.display-name')] = options.name\n fn[Symbol.for('plugin-meta')] = options\n\n // Faux modules support\n if (!fn.default) {\n fn.default = fn\n }\n\n // TypeScript support for named imports\n // See https://github.com/fastify/fastify/issues/2404 for more details\n // The type definitions would have to be update to match this.\n const camelCase = toCamelCase(options.name)\n if (!autoName && !fn[camelCase]) {\n fn[camelCase] = fn\n }\n\n return fn\n}\n\nmodule.exports = plugin\nmodule.exports.default = plugin\nmodule.exports.fastifyPlugin = plugin\n","import type { FastifyPluginAsync, FastifyRequest } from \"fastify\"\nimport fp from \"fastify-plugin\"\nimport {\n decodeAndDecompressProfileFromBase64,\n} from \"../functions/decodeAndDecompressProfileFromBase64.js\"\nimport type { Profile } from \"../models/profile.js\"\nimport { DEFAULT_PROFILE_KEY } from \"../settings.js\"\n\ndeclare module \"fastify\" {\n interface FastifyRequest {\n profile?: Profile\n }\n}\n\nexport interface FastifyProfilePluginOptions {\n environment?: string\n}\n\nfunction resolveEnvironment(opts?: FastifyProfilePluginOptions): string {\n return opts?.environment ?? process.env.NODE_ENV ?? \"development\"\n}\n\nfunction extractHeaderValue(req: FastifyRequest): string | undefined {\n const value = req.headers[DEFAULT_PROFILE_KEY]\n if (Array.isArray(value)) return value[0]\n return value\n}\n\nconst fastifyProfilePluginImpl: FastifyPluginAsync<\n FastifyProfilePluginOptions\n> = async (fastify, opts) => {\n fastify.decorateRequest(\"profile\", undefined)\n\n fastify.addHook(\"onRequest\", async (request, reply) => {\n try {\n const isDev = resolveEnvironment(opts) === \"development\"\n const headerValue = extractHeaderValue(request)\n\n if (headerValue === undefined) {\n if (isDev) {\n request.profile = undefined\n return\n }\n await reply.status(403).send({\n detail: `Required header '${DEFAULT_PROFILE_KEY}' missing in production environment.`,\n })\n return\n }\n\n try {\n request.profile = decodeAndDecompressProfileFromBase64(headerValue)\n } catch (_error) {\n if (isDev) {\n request.profile = undefined\n return\n }\n await reply.status(401).send({\n detail:\n \"Unable to check user identity. Please contact administrators\",\n })\n }\n } catch (error) {\n await reply.status(500).send({\n detail: `Internal server error: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n })\n}\n\nexport const fastifyProfilePlugin = fp(fastifyProfilePluginImpl, {\n name: \"mycelium-profile-plugin\",\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","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","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 { 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\"\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\"\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\"\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 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 {\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\"\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\"\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","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 D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M,OAAO,GAAG,EAAE,KAAK;AAAA,QAC3B,QAAQ,0BAA0B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,MAC1F,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;AAEO,IAAM,2BAAuB,sBAAAC,SAAG,0BAA0B;AAAA,EAC/D,MAAM;AACR,CAAC;","names":["exports","module","exports","module","exports","module","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","tagRecordsOrUrls","import_zod","fp"]}
@@ -0,0 +1,15 @@
1
+ import { FastifyPluginAsync } from 'fastify';
2
+ import { P as Profile } from '../profile-CUKBifyR.cjs';
3
+ import 'zod';
4
+
5
+ declare module "fastify" {
6
+ interface FastifyRequest {
7
+ profile?: Profile;
8
+ }
9
+ }
10
+ interface FastifyProfilePluginOptions {
11
+ environment?: string;
12
+ }
13
+ declare const fastifyProfilePlugin: FastifyPluginAsync<FastifyProfilePluginOptions>;
14
+
15
+ export { type FastifyProfilePluginOptions, fastifyProfilePlugin };
@@ -0,0 +1,15 @@
1
+ import { FastifyPluginAsync } from 'fastify';
2
+ import { P as Profile } from '../profile-CUKBifyR.js';
3
+ import 'zod';
4
+
5
+ declare module "fastify" {
6
+ interface FastifyRequest {
7
+ profile?: Profile;
8
+ }
9
+ }
10
+ interface FastifyProfilePluginOptions {
11
+ environment?: string;
12
+ }
13
+ declare const fastifyProfilePlugin: FastifyPluginAsync<FastifyProfilePluginOptions>;
14
+
15
+ export { type FastifyProfilePluginOptions, fastifyProfilePlugin };
@@ -0,0 +1,148 @@
1
+ import {
2
+ DEFAULT_PROFILE_KEY,
3
+ __commonJS,
4
+ __toESM,
5
+ decodeAndDecompressProfileFromBase64
6
+ } from "../chunk-VPKHPMDS.js";
7
+
8
+ // node_modules/fastify-plugin/lib/getPluginName.js
9
+ var require_getPluginName = __commonJS({
10
+ "node_modules/fastify-plugin/lib/getPluginName.js"(exports, module) {
11
+ "use strict";
12
+ var fpStackTracePattern = /at\s(?:.*\.)?plugin\s.*\n\s*(.*)/;
13
+ var fileNamePattern = /(\w*(\.\w*)*)\..*/;
14
+ module.exports = function getPluginName(fn) {
15
+ if (fn.name.length > 0) return fn.name;
16
+ const stackTraceLimit = Error.stackTraceLimit;
17
+ Error.stackTraceLimit = 10;
18
+ try {
19
+ throw new Error("anonymous function");
20
+ } catch (e) {
21
+ Error.stackTraceLimit = stackTraceLimit;
22
+ return extractPluginName(e.stack);
23
+ }
24
+ };
25
+ function extractPluginName(stack) {
26
+ const m = stack.match(fpStackTracePattern);
27
+ return m ? m[1].split(/[/\\]/).slice(-1)[0].match(fileNamePattern)[1] : "anonymous";
28
+ }
29
+ module.exports.extractPluginName = extractPluginName;
30
+ }
31
+ });
32
+
33
+ // node_modules/fastify-plugin/lib/toCamelCase.js
34
+ var require_toCamelCase = __commonJS({
35
+ "node_modules/fastify-plugin/lib/toCamelCase.js"(exports, module) {
36
+ "use strict";
37
+ module.exports = function toCamelCase(name) {
38
+ if (name[0] === "@") {
39
+ name = name.slice(1).replace("/", "-");
40
+ }
41
+ return name.replace(/-(.)/g, function(match, g1) {
42
+ return g1.toUpperCase();
43
+ });
44
+ };
45
+ }
46
+ });
47
+
48
+ // node_modules/fastify-plugin/plugin.js
49
+ var require_plugin = __commonJS({
50
+ "node_modules/fastify-plugin/plugin.js"(exports, module) {
51
+ "use strict";
52
+ var getPluginName = require_getPluginName();
53
+ var toCamelCase = require_toCamelCase();
54
+ var count = 0;
55
+ function plugin(fn, options = {}) {
56
+ let autoName = false;
57
+ if (fn.default !== void 0) {
58
+ fn = fn.default;
59
+ }
60
+ if (typeof fn !== "function") {
61
+ throw new TypeError(
62
+ `fastify-plugin expects a function, instead got a '${typeof fn}'`
63
+ );
64
+ }
65
+ if (typeof options === "string") {
66
+ options = {
67
+ fastify: options
68
+ };
69
+ }
70
+ if (typeof options !== "object" || Array.isArray(options) || options === null) {
71
+ throw new TypeError("The options object should be an object");
72
+ }
73
+ if (options.fastify !== void 0 && typeof options.fastify !== "string") {
74
+ throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof options.fastify}'`);
75
+ }
76
+ if (!options.name) {
77
+ autoName = true;
78
+ options.name = getPluginName(fn) + "-auto-" + count++;
79
+ }
80
+ fn[/* @__PURE__ */ Symbol.for("skip-override")] = options.encapsulate !== true;
81
+ fn[/* @__PURE__ */ Symbol.for("fastify.display-name")] = options.name;
82
+ fn[/* @__PURE__ */ Symbol.for("plugin-meta")] = options;
83
+ if (!fn.default) {
84
+ fn.default = fn;
85
+ }
86
+ const camelCase = toCamelCase(options.name);
87
+ if (!autoName && !fn[camelCase]) {
88
+ fn[camelCase] = fn;
89
+ }
90
+ return fn;
91
+ }
92
+ module.exports = plugin;
93
+ module.exports.default = plugin;
94
+ module.exports.fastifyPlugin = plugin;
95
+ }
96
+ });
97
+
98
+ // src/fastify/index.ts
99
+ var import_fastify_plugin = __toESM(require_plugin(), 1);
100
+ function resolveEnvironment(opts) {
101
+ return opts?.environment ?? process.env.NODE_ENV ?? "development";
102
+ }
103
+ function extractHeaderValue(req) {
104
+ const value = req.headers[DEFAULT_PROFILE_KEY];
105
+ if (Array.isArray(value)) return value[0];
106
+ return value;
107
+ }
108
+ var fastifyProfilePluginImpl = async (fastify, opts) => {
109
+ fastify.decorateRequest("profile", void 0);
110
+ fastify.addHook("onRequest", async (request, reply) => {
111
+ try {
112
+ const isDev = resolveEnvironment(opts) === "development";
113
+ const headerValue = extractHeaderValue(request);
114
+ if (headerValue === void 0) {
115
+ if (isDev) {
116
+ request.profile = void 0;
117
+ return;
118
+ }
119
+ await reply.status(403).send({
120
+ detail: `Required header '${DEFAULT_PROFILE_KEY}' missing in production environment.`
121
+ });
122
+ return;
123
+ }
124
+ try {
125
+ request.profile = decodeAndDecompressProfileFromBase64(headerValue);
126
+ } catch (_error) {
127
+ if (isDev) {
128
+ request.profile = void 0;
129
+ return;
130
+ }
131
+ await reply.status(401).send({
132
+ detail: "Unable to check user identity. Please contact administrators"
133
+ });
134
+ }
135
+ } catch (error) {
136
+ await reply.status(500).send({
137
+ detail: `Internal server error: ${error instanceof Error ? error.message : String(error)}`
138
+ });
139
+ }
140
+ });
141
+ };
142
+ var fastifyProfilePlugin = (0, import_fastify_plugin.default)(fastifyProfilePluginImpl, {
143
+ name: "mycelium-profile-plugin"
144
+ });
145
+ export {
146
+ fastifyProfilePlugin
147
+ };
148
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../node_modules/fastify-plugin/lib/getPluginName.js","../../node_modules/fastify-plugin/lib/toCamelCase.js","../../node_modules/fastify-plugin/plugin.js","../../src/fastify/index.ts"],"sourcesContent":["'use strict'\n\nconst fpStackTracePattern = /at\\s(?:.*\\.)?plugin\\s.*\\n\\s*(.*)/\nconst fileNamePattern = /(\\w*(\\.\\w*)*)\\..*/\n\nmodule.exports = function getPluginName (fn) {\n if (fn.name.length > 0) return fn.name\n\n const stackTraceLimit = Error.stackTraceLimit\n Error.stackTraceLimit = 10\n try {\n throw new Error('anonymous function')\n } catch (e) {\n Error.stackTraceLimit = stackTraceLimit\n return extractPluginName(e.stack)\n }\n}\n\nfunction extractPluginName (stack) {\n const m = stack.match(fpStackTracePattern)\n\n // get last section of path and match for filename\n return m ? m[1].split(/[/\\\\]/).slice(-1)[0].match(fileNamePattern)[1] : 'anonymous'\n}\nmodule.exports.extractPluginName = extractPluginName\n","'use strict'\n\nmodule.exports = function toCamelCase (name) {\n if (name[0] === '@') {\n name = name.slice(1).replace('/', '-')\n }\n return name.replace(/-(.)/g, function (match, g1) {\n return g1.toUpperCase()\n })\n}\n","'use strict'\n\nconst getPluginName = require('./lib/getPluginName')\nconst toCamelCase = require('./lib/toCamelCase')\n\nlet count = 0\n\nfunction plugin (fn, options = {}) {\n let autoName = false\n\n if (fn.default !== undefined) {\n // Support for 'export default' behaviour in transpiled ECMAScript module\n fn = fn.default\n }\n\n if (typeof fn !== 'function') {\n throw new TypeError(\n `fastify-plugin expects a function, instead got a '${typeof fn}'`\n )\n }\n\n if (typeof options === 'string') {\n options = {\n fastify: options\n }\n }\n\n if (\n typeof options !== 'object' ||\n Array.isArray(options) ||\n options === null\n ) {\n throw new TypeError('The options object should be an object')\n }\n\n if (options.fastify !== undefined && typeof options.fastify !== 'string') {\n throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof options.fastify}'`)\n }\n\n if (!options.name) {\n autoName = true\n options.name = getPluginName(fn) + '-auto-' + count++\n }\n\n fn[Symbol.for('skip-override')] = options.encapsulate !== true\n fn[Symbol.for('fastify.display-name')] = options.name\n fn[Symbol.for('plugin-meta')] = options\n\n // Faux modules support\n if (!fn.default) {\n fn.default = fn\n }\n\n // TypeScript support for named imports\n // See https://github.com/fastify/fastify/issues/2404 for more details\n // The type definitions would have to be update to match this.\n const camelCase = toCamelCase(options.name)\n if (!autoName && !fn[camelCase]) {\n fn[camelCase] = fn\n }\n\n return fn\n}\n\nmodule.exports = plugin\nmodule.exports.default = plugin\nmodule.exports.fastifyPlugin = plugin\n","import type { FastifyPluginAsync, FastifyRequest } from \"fastify\"\nimport fp from \"fastify-plugin\"\nimport {\n decodeAndDecompressProfileFromBase64,\n} from \"../functions/decodeAndDecompressProfileFromBase64.js\"\nimport type { Profile } from \"../models/profile.js\"\nimport { DEFAULT_PROFILE_KEY } from \"../settings.js\"\n\ndeclare module \"fastify\" {\n interface FastifyRequest {\n profile?: Profile\n }\n}\n\nexport interface FastifyProfilePluginOptions {\n environment?: string\n}\n\nfunction resolveEnvironment(opts?: FastifyProfilePluginOptions): string {\n return opts?.environment ?? process.env.NODE_ENV ?? \"development\"\n}\n\nfunction extractHeaderValue(req: FastifyRequest): string | undefined {\n const value = req.headers[DEFAULT_PROFILE_KEY]\n if (Array.isArray(value)) return value[0]\n return value\n}\n\nconst fastifyProfilePluginImpl: FastifyPluginAsync<\n FastifyProfilePluginOptions\n> = async (fastify, opts) => {\n fastify.decorateRequest(\"profile\", undefined)\n\n fastify.addHook(\"onRequest\", async (request, reply) => {\n try {\n const isDev = resolveEnvironment(opts) === \"development\"\n const headerValue = extractHeaderValue(request)\n\n if (headerValue === undefined) {\n if (isDev) {\n request.profile = undefined\n return\n }\n await reply.status(403).send({\n detail: `Required header '${DEFAULT_PROFILE_KEY}' missing in production environment.`,\n })\n return\n }\n\n try {\n request.profile = decodeAndDecompressProfileFromBase64(headerValue)\n } catch (_error) {\n if (isDev) {\n request.profile = undefined\n return\n }\n await reply.status(401).send({\n detail:\n \"Unable to check user identity. Please contact administrators\",\n })\n }\n } catch (error) {\n await reply.status(500).send({\n detail: `Internal server error: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n })\n}\n\nexport const fastifyProfilePlugin = fp(fastifyProfilePluginImpl, {\n name: \"mycelium-profile-plugin\",\n})\n"],"mappings":";;;;;;;;AAAA;AAAA;AAAA;AAEA,QAAM,sBAAsB;AAC5B,QAAM,kBAAkB;AAExB,WAAO,UAAU,SAAS,cAAe,IAAI;AAC3C,UAAI,GAAG,KAAK,SAAS,EAAG,QAAO,GAAG;AAElC,YAAM,kBAAkB,MAAM;AAC9B,YAAM,kBAAkB;AACxB,UAAI;AACF,cAAM,IAAI,MAAM,oBAAoB;AAAA,MACtC,SAAS,GAAG;AACV,cAAM,kBAAkB;AACxB,eAAO,kBAAkB,EAAE,KAAK;AAAA,MAClC;AAAA,IACF;AAEA,aAAS,kBAAmB,OAAO;AACjC,YAAM,IAAI,MAAM,MAAM,mBAAmB;AAGzC,aAAO,IAAI,EAAE,CAAC,EAAE,MAAM,OAAO,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,eAAe,EAAE,CAAC,IAAI;AAAA,IAC1E;AACA,WAAO,QAAQ,oBAAoB;AAAA;AAAA;;;ACxBnC;AAAA;AAAA;AAEA,WAAO,UAAU,SAAS,YAAa,MAAM;AAC3C,UAAI,KAAK,CAAC,MAAM,KAAK;AACnB,eAAO,KAAK,MAAM,CAAC,EAAE,QAAQ,KAAK,GAAG;AAAA,MACvC;AACA,aAAO,KAAK,QAAQ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