@happyvertical/smrt-users 0.57.17 → 0.57.19
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/AGENTS.md +21 -0
- package/README.md +134 -4
- package/agents/retention.md +3 -2
- package/dist/chunks/{PasswordCredentialService-CyB9FmYp.js → PasswordCredentialService-DezdsV_v.js} +40 -3
- package/dist/chunks/PasswordCredentialService-DezdsV_v.js.map +1 -0
- package/dist/chunks/TerminalAuthService-CM-L6VyR.js +4012 -0
- package/dist/chunks/TerminalAuthService-CM-L6VyR.js.map +1 -0
- package/dist/collections/PasskeyChallengeCollection.d.ts +37 -0
- package/dist/collections/PasskeyChallengeCollection.d.ts.map +1 -0
- package/dist/collections/PasskeyCredentialCollection.d.ts +66 -0
- package/dist/collections/PasskeyCredentialCollection.d.ts.map +1 -0
- package/dist/collections/SessionCollection.d.ts.map +1 -1
- package/dist/collections/index.d.ts +2 -0
- package/dist/collections/index.d.ts.map +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +15 -6
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +1302 -428
- package/dist/models/PasskeyChallenge.d.ts +32 -0
- package/dist/models/PasskeyChallenge.d.ts.map +1 -0
- package/dist/models/PasskeyCredential.d.ts +50 -0
- package/dist/models/PasskeyCredential.d.ts.map +1 -0
- package/dist/models/Session.d.ts +23 -0
- package/dist/models/Session.d.ts.map +1 -1
- package/dist/models/index.d.ts +2 -0
- package/dist/models/index.d.ts.map +1 -1
- package/dist/operator.js +1 -1
- package/dist/retention.d.ts +3 -1
- package/dist/retention.d.ts.map +1 -1
- package/dist/services/PasskeyCredentialService.d.ts +382 -0
- package/dist/services/PasskeyCredentialService.d.ts.map +1 -0
- package/dist/services/SessionService.d.ts.map +1 -1
- package/dist/services/index.d.ts +1 -0
- package/dist/services/index.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +407 -9
- package/dist/svelte/auth.d.ts +9 -3
- package/dist/svelte/auth.d.ts.map +1 -1
- package/dist/svelte/index.d.ts +2 -0
- package/dist/svelte/index.d.ts.map +1 -1
- package/dist/svelte/index.js +1 -0
- package/dist/svelte/passkey.d.ts +58 -0
- package/dist/svelte/passkey.d.ts.map +1 -0
- package/dist/svelte/passkey.js +97 -0
- package/dist/sveltekit/index.d.ts +1 -0
- package/dist/sveltekit/index.d.ts.map +1 -1
- package/dist/sveltekit/passkey-handlers.d.ts +117 -0
- package/dist/sveltekit/passkey-handlers.d.ts.map +1 -0
- package/dist/sveltekit.js +259 -69
- package/dist/sveltekit.js.map +1 -1
- package/package.json +15 -13
- package/dist/chunks/PasswordCredentialService-CyB9FmYp.js.map +0 -1
- package/dist/chunks/TerminalAuthService-CCbM_G1V.js +0 -3012
- package/dist/chunks/TerminalAuthService-CCbM_G1V.js.map +0 -1
|
@@ -1,3012 +0,0 @@
|
|
|
1
|
-
import { $ as PermissionCatalogService, A as InvalidCredentialsError, Ct as SessionCollection, F as withoutListBounds, Ft as __exportAll, L as UserCollection, M as LoginRateLimitError, N as hashSecret, P as verifySecretHash, U as TenantCollection, _ as PermissionResolver, ft as MembershipCollection, g as SessionService, j as LoginAttemptLimiter, kt as SESSION_DATA_KEYS, ot as RoleCollection, rt as registerPermissionDefinitions, tt as deriveOperationPermissionSlug } from "./PasswordCredentialService-CyB9FmYp.js";
|
|
2
|
-
import { ObjectRegistry, SmrtCollection, SmrtObject, field, foreignKey, isUniqueViolationError, smrt } from "@happyvertical/smrt-core";
|
|
3
|
-
import { withSystemContext } from "@happyvertical/smrt-tenancy";
|
|
4
|
-
import { createHash, randomBytes } from "node:crypto";
|
|
5
|
-
import { getPackageConfig } from "@happyvertical/smrt-config";
|
|
6
|
-
import { createLogger } from "@happyvertical/logger";
|
|
7
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
8
|
-
//#region src/__smrt-register__.ts
|
|
9
|
-
ObjectRegistry.registerPackageManifest(JSON.parse(`{"version":"1.0.0","timestamp":0,"packageName":"@happyvertical/smrt-users","packageVersion":"0.57.17","objects":{"@happyvertical/smrt-users:AccessRequestCollection":{"name":"accessrequestcollection","className":"AccessRequestCollection","qualifiedName":"@happyvertical/smrt-users:AccessRequestCollection","collection":"accessrequests","description":"Collection for managing AccessRequest objects.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/AccessRequestCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"findByEmail":{"name":"findByEmail","async":true,"parameters":[{"name":"email","type":"string","optional":false}],"returnType":"Promise<AccessRequest[]>","isStatic":false,"isPublic":true},"findOpenByEmail":{"name":"findOpenByEmail","async":true,"parameters":[{"name":"email","type":"string","optional":false}],"returnType":"Promise<AccessRequest | null>","isStatic":false,"isPublic":true},"findByStatus":{"name":"findByStatus","async":true,"parameters":[{"name":"status","type":"AccessRequestStatus","optional":false}],"returnType":"Promise<AccessRequest[]>","isStatic":false,"isPublic":true},"findOpen":{"name":"findOpen","async":true,"parameters":[],"returnType":"Promise<AccessRequest[]>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"access_requests","api":{"include":[]},"mcp":{"include":[]},"cli":false},"extends":"SmrtCollection","extendsTypeArg":"AccessRequest","exportName":"AccessRequestCollection","collectionExportName":"AccessRequestCollectionCollection","schema":{"tableName":"access_requests","ddl":"CREATE TABLE IF NOT EXISTS \\"access_requests\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"email\\" TEXT NOT NULL DEFAULT '',\\n \\"name\\" TEXT,\\n \\"status\\" TEXT,\\n \\"source\\" TEXT DEFAULT '',\\n \\"request_context\\" TEXT DEFAULT '{}',\\n \\"note\\" TEXT,\\n \\"requested_at\\" TIMESTAMP,\\n \\"decided_at\\" TIMESTAMP,\\n \\"decided_by\\" TEXT,\\n \\"resulting_user_id\\" TEXT,\\n \\"tenant_hint\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"email":{"type":"TEXT","notNull":true,"unique":false,"default":""},"name":{"type":"TEXT","notNull":false,"unique":false},"status":{"type":"TEXT","notNull":false,"unique":false},"source":{"type":"TEXT","notNull":false,"unique":false,"default":""},"request_context":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"note":{"type":"TEXT","notNull":false,"unique":false},"requested_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"decided_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"decided_by":{"type":"TEXT","notNull":false,"unique":false},"resulting_user_id":{"type":"TEXT","notNull":false,"unique":false},"tenant_hint":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"access_requests_slug_context_idx","columns":["slug","context"]},{"name":"access_requests_email_idx","columns":["email"]},{"name":"access_requests_status_idx","columns":["status"]},{"name":"access_requests_source_idx","columns":["source"]},{"name":"access_requests_created_at_idx","columns":["created_at"]}],"version":"f396996f"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersCliAuthApproveLimitCollection":{"name":"userscliauthapprovelimitcollection","className":"UsersCliAuthApproveLimitCollection","qualifiedName":"@happyvertical/smrt-users:UsersCliAuthApproveLimitCollection","collection":"userscliauthapprovelimits","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/CliAuthApproveLimitCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"reserveAttempt":{"name":"reserveAttempt","async":true,"parameters":[{"name":"input","type":"object","optional":false,"memberTypes":["number","string"]}],"returnType":"Promise<CliAuthApproveReservation>","isStatic":false,"isPublic":true},"releaseAttempt":{"name":"releaseAttempt","async":true,"parameters":[{"name":"userId","type":"string","optional":false},{"name":"windowStartedAt","type":"string","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"users_cli_auth_approve_limits","api":false,"mcp":false,"cli":false},"extends":"SmrtCollection","extendsTypeArg":"UsersCliAuthApproveLimit","exportName":"UsersCliAuthApproveLimitCollection","collectionExportName":"UsersCliAuthApproveLimitCollectionCollection","schema":{"tableName":"users_cli_auth_approve_limits","ddl":"CREATE TABLE IF NOT EXISTS \\"users_cli_auth_approve_limits\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"user_id\\" UUID NOT NULL UNIQUE,\\n \\"attempt_count\\" INTEGER NOT NULL DEFAULT 0,\\n \\"window_started_at\\" TIMESTAMP NOT NULL\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"user_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":true,"foreignKey":{"table":"users","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"attempt_count":{"type":"INTEGER","notNull":true,"unique":false,"default":0},"window_started_at":{"type":"TIMESTAMP","notNull":true,"unique":false}},"indexes":[{"name":"users_cli_auth_approve_limits_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_cli_auth_approve_limits_created_at_idx","columns":["created_at"]}],"version":"c45c02de"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersCliAuthRequestCollection":{"name":"userscliauthrequestcollection","className":"UsersCliAuthRequestCollection","qualifiedName":"@happyvertical/smrt-users:UsersCliAuthRequestCollection","collection":"userscliauthrequests","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/CliAuthRequestCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"approvePendingRequest":{"name":"approvePendingRequest","async":true,"parameters":[{"name":"input","type":"ApprovePendingCliAuthRequestInput","optional":false}],"returnType":"Promise<ApprovedCliAuthRequestSnapshot | null>","isStatic":false,"isPublic":true},"consumeApprovedSession":{"name":"consumeApprovedSession","async":true,"parameters":[{"name":"deviceCodeHash","type":"string","optional":false}],"returnType":"Promise<string | null>","isStatic":false,"isPublic":true},"findByUserCode":{"name":"findByUserCode","async":true,"parameters":[{"name":"userCode","type":"string","optional":false}],"returnType":"Promise<UsersCliAuthRequest | null>","isStatic":false,"isPublic":true},"findByDeviceCodeHash":{"name":"findByDeviceCodeHash","async":true,"parameters":[{"name":"deviceCodeHash","type":"string","optional":false}],"returnType":"Promise<UsersCliAuthRequest | null>","isStatic":false,"isPublic":true},"deleteExpired":{"name":"deleteExpired","async":true,"parameters":[{"name":"options","type":"object","optional":true,"memberTypes":["boolean"]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"users_cli_auth_requests","api":{"include":[]},"mcp":{"include":[]},"cli":false},"extends":"SmrtCollection","extendsTypeArg":"UsersCliAuthRequest","exportName":"UsersCliAuthRequestCollection","collectionExportName":"UsersCliAuthRequestCollectionCollection","schema":{"tableName":"users_cli_auth_requests","ddl":"CREATE TABLE IF NOT EXISTS \\"users_cli_auth_requests\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"user_code\\" TEXT NOT NULL UNIQUE,\\n \\"device_code_hash\\" TEXT NOT NULL UNIQUE,\\n \\"status\\" TEXT,\\n \\"user_id\\" UUID,\\n \\"tenant_id\\" UUID,\\n \\"session_id\\" UUID,\\n \\"expires_at\\" TIMESTAMP,\\n \\"approved_at\\" TIMESTAMP\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"user_code":{"type":"TEXT","notNull":true,"unique":true},"device_code_hash":{"type":"TEXT","notNull":true,"unique":true},"status":{"type":"TEXT","notNull":false,"unique":false},"user_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"users","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"tenant_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"tenants","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"session_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"sessions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"approved_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"users_cli_auth_requests_tenant_id_slug_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"users_cli_auth_requests_expires_at_idx","columns":["expires_at"]},{"name":"users_cli_auth_requests_created_at_idx","columns":["created_at"]},{"name":"users_cli_auth_requests_user_id_idx","columns":["user_id"]},{"name":"users_cli_auth_requests_session_id_idx","columns":["session_id"]}],"version":"713ae04c"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:GroupCollection":{"name":"groupcollection","className":"GroupCollection","qualifiedName":"@happyvertical/smrt-users:GroupCollection","collection":"groups","description":"Collection for managing Group objects","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/GroupCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"findByTenant":{"name":"findByTenant","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Group[]>","isStatic":false,"isPublic":true},"findBySlug":{"name":"findBySlug","async":true,"parameters":[{"name":"slug","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Group | null>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"Group","exportName":"GroupCollection","collectionExportName":"GroupCollectionCollection","schema":{"tableName":"groups","ddl":"CREATE TABLE IF NOT EXISTS \\"groups\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"name\\" TEXT DEFAULT '',\\n \\"description\\" TEXT DEFAULT ''\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"tenants","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"description":{"type":"TEXT","notNull":false,"unique":false,"default":""}},"indexes":[{"name":"groups_tenant_id_slug_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"groups_created_at_idx","columns":["created_at"]}],"version":"1824c19b"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:GroupMemberCollection":{"name":"groupmembercollection","className":"GroupMemberCollection","qualifiedName":"@happyvertical/smrt-users:GroupMemberCollection","collection":"groupmembers","description":"Collection for managing GroupMember objects","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/GroupMemberCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"findByGroup":{"name":"findByGroup","async":true,"parameters":[{"name":"groupId","type":"string","optional":false}],"returnType":"Promise<GroupMember[]>","isStatic":false,"isPublic":true},"findByUser":{"name":"findByUser","async":true,"parameters":[{"name":"userId","type":"string","optional":false}],"returnType":"Promise<GroupMember[]>","isStatic":false,"isPublic":true},"isMember":{"name":"isMember","async":true,"parameters":[{"name":"groupId","type":"string","optional":false},{"name":"userId","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"addMember":{"name":"addMember","async":true,"parameters":[{"name":"groupId","type":"string","optional":false},{"name":"userId","type":"string","optional":false}],"returnType":"Promise<GroupMember>","isStatic":false,"isPublic":true},"removeMember":{"name":"removeMember","async":true,"parameters":[{"name":"groupId","type":"string","optional":false},{"name":"userId","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"getGroupIds":{"name":"getGroupIds","async":true,"parameters":[{"name":"userId","type":"string","optional":false}],"returnType":"Promise<string[]>","isStatic":false,"isPublic":true},"getGroupIdsForTenant":{"name":"getGroupIdsForTenant","async":true,"parameters":[{"name":"userId","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<string[]>","isStatic":false,"isPublic":true},"getUserIds":{"name":"getUserIds","async":true,"parameters":[{"name":"groupId","type":"string","optional":false}],"returnType":"Promise<string[]>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"GroupMember","exportName":"GroupMemberCollection","collectionExportName":"GroupMemberCollectionCollection","schema":{"tableName":"group_members","ddl":"CREATE TABLE IF NOT EXISTS \\"group_members\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"group_id\\" UUID NOT NULL,\\n \\"user_id\\" UUID NOT NULL\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"group_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"groups","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"user_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"users","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}}},"indexes":[{"name":"group_members_group_id_user_id_idx","columns":["group_id","user_id"],"unique":true},{"name":"group_members_slug_context_idx","columns":["slug","context"]},{"name":"group_members_created_at_idx","columns":["created_at"]},{"name":"group_members_user_id_idx","columns":["user_id"]}],"version":"ed4d1187"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:GroupRoleCollection":{"name":"grouprolecollection","className":"GroupRoleCollection","qualifiedName":"@happyvertical/smrt-users:GroupRoleCollection","collection":"grouproles","description":"Collection for managing GroupRole objects","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/GroupRoleCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"findByGroup":{"name":"findByGroup","async":true,"parameters":[{"name":"groupId","type":"string","optional":false}],"returnType":"Promise<GroupRole[]>","isStatic":false,"isPublic":true},"findByRole":{"name":"findByRole","async":true,"parameters":[{"name":"roleId","type":"string","optional":false}],"returnType":"Promise<GroupRole[]>","isStatic":false,"isPublic":true},"hasRole":{"name":"hasRole","async":true,"parameters":[{"name":"groupId","type":"string","optional":false},{"name":"roleId","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"addRole":{"name":"addRole","async":true,"parameters":[{"name":"groupId","type":"string","optional":false},{"name":"roleId","type":"string","optional":false}],"returnType":"Promise<GroupRole>","isStatic":false,"isPublic":true},"removeRole":{"name":"removeRole","async":true,"parameters":[{"name":"groupId","type":"string","optional":false},{"name":"roleId","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"getRoleIds":{"name":"getRoleIds","async":true,"parameters":[{"name":"groupId","type":"string","optional":false}],"returnType":"Promise<string[]>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"GroupRole","exportName":"GroupRoleCollection","collectionExportName":"GroupRoleCollectionCollection","schema":{"tableName":"group_roles","ddl":"CREATE TABLE IF NOT EXISTS \\"group_roles\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"group_id\\" UUID NOT NULL,\\n \\"role_id\\" UUID NOT NULL\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"group_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"groups","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"role_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"roles","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}}},"indexes":[{"name":"group_roles_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"group_roles_created_at_idx","columns":["created_at"]},{"name":"group_roles_group_id_idx","columns":["group_id"]},{"name":"group_roles_role_id_idx","columns":["role_id"]}],"version":"b1e35f93"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersLoginAttemptCollection":{"name":"usersloginattemptcollection","className":"UsersLoginAttemptCollection","qualifiedName":"@happyvertical/smrt-users:UsersLoginAttemptCollection","collection":"usersloginattempts","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/LoginAttemptCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"reserveAttempt":{"name":"reserveAttempt","async":true,"parameters":[{"name":"input","type":"ReserveLoginAttemptInput","optional":false}],"returnType":"Promise<LoginAttemptReservation>","isStatic":false,"isPublic":true},"recordFailure":{"name":"recordFailure","async":true,"parameters":[{"name":"input","type":"RecordLoginFailureInput","optional":false}],"returnType":"Promise<RecordedLoginFailure>","isStatic":false,"isPublic":true},"releaseAttempt":{"name":"releaseAttempt","async":true,"parameters":[{"name":"limiterKey","type":"string","optional":false},{"name":"windowStartedAt","type":"string","optional":false},{"name":"options","type":"object","optional":true,"memberTypes":["boolean"]}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"deleteIdle":{"name":"deleteIdle","async":true,"parameters":[{"name":"options","type":"object","optional":true,"memberTypes":["boolean"]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"users_login_attempts","api":false,"mcp":false,"cli":false},"extends":"SmrtCollection","extendsTypeArg":"UsersLoginAttempt","exportName":"UsersLoginAttemptCollection","collectionExportName":"UsersLoginAttemptCollectionCollection","schema":{"tableName":"users_login_attempts","ddl":"CREATE TABLE IF NOT EXISTS \\"users_login_attempts\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"limiter_key\\" TEXT NOT NULL UNIQUE,\\n \\"scope\\" TEXT NOT NULL,\\n \\"attempt_count\\" INTEGER NOT NULL DEFAULT 0,\\n \\"window_started_at\\" TIMESTAMP NOT NULL,\\n \\"failure_streak\\" INTEGER NOT NULL DEFAULT 0,\\n \\"locked_until\\" TIMESTAMP,\\n \\"last_failed_at\\" TIMESTAMP,\\n \\"retain_until\\" TIMESTAMP NOT NULL\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"limiter_key":{"type":"TEXT","notNull":true,"unique":true},"scope":{"type":"TEXT","notNull":true,"unique":false},"attempt_count":{"type":"INTEGER","notNull":true,"unique":false,"default":0},"window_started_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"failure_streak":{"type":"INTEGER","notNull":true,"unique":false,"default":0},"locked_until":{"type":"TIMESTAMP","notNull":false,"unique":false},"last_failed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"retain_until":{"type":"TIMESTAMP","notNull":true,"unique":false}},"indexes":[{"name":"users_login_attempts_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_login_attempts_locked_until_idx","columns":["locked_until"]},{"name":"users_login_attempts_retain_until_idx","columns":["retain_until"]},{"name":"users_login_attempts_created_at_idx","columns":["created_at"]}],"version":"89dfe336"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersLoginAuditEventCollection":{"name":"usersloginauditeventcollection","className":"UsersLoginAuditEventCollection","qualifiedName":"@happyvertical/smrt-users:UsersLoginAuditEventCollection","collection":"usersloginauditevents","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/LoginAuditEventCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"deleteOlderThan":{"name":"deleteOlderThan","async":true,"parameters":[{"name":"maxAgeMs","type":"number","optional":false},{"name":"options","type":"object","optional":true,"memberTypes":["boolean"]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"users_login_audit_events","api":false,"mcp":false,"cli":false},"extends":"SmrtCollection","extendsTypeArg":"UsersLoginAuditEvent","exportName":"UsersLoginAuditEventCollection","collectionExportName":"UsersLoginAuditEventCollectionCollection","schema":{"tableName":"users_login_audit_events","ddl":"CREATE TABLE IF NOT EXISTS \\"users_login_audit_events\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"kind\\" TEXT NOT NULL,\\n \\"outcome\\" TEXT NOT NULL,\\n \\"subject_key_hash\\" TEXT,\\n \\"source_key_hash\\" TEXT,\\n \\"retry_after_seconds\\" INTEGER,\\n \\"occurred_at\\" TIMESTAMP NOT NULL,\\n \\"metadata\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"kind":{"type":"TEXT","notNull":true,"unique":false},"outcome":{"type":"TEXT","notNull":true,"unique":false},"subject_key_hash":{"type":"TEXT","notNull":false,"unique":false},"source_key_hash":{"type":"TEXT","notNull":false,"unique":false},"retry_after_seconds":{"type":"INTEGER","notNull":false,"unique":false},"occurred_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"metadata":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"users_login_audit_events_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_login_audit_events_subject_key_hash_idx","columns":["subject_key_hash"]},{"name":"users_login_audit_events_source_key_hash_idx","columns":["source_key_hash"]},{"name":"users_login_audit_events_occurred_at_idx","columns":["occurred_at"]},{"name":"users_login_audit_events_created_at_idx","columns":["created_at"]}],"version":"485105a9"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersMagicLinkTokenCollection":{"name":"usersmagiclinktokencollection","className":"UsersMagicLinkTokenCollection","qualifiedName":"@happyvertical/smrt-users:UsersMagicLinkTokenCollection","collection":"usersmagiclinktokens","description":"Collection for managing smrt-users magic link token records","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/MagicLinkTokenCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"findByNonce":{"name":"findByNonce","async":true,"parameters":[{"name":"nonce","type":"string","optional":false}],"returnType":"Promise<UsersMagicLinkToken | null>","isStatic":false,"isPublic":true},"markUsed":{"name":"markUsed","async":true,"parameters":[{"name":"nonce","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"deleteExpired":{"name":"deleteExpired","async":true,"parameters":[{"name":"options","type":"object","optional":true,"memberTypes":["boolean"]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"users_magic_link_tokens","api":{"include":[]},"mcp":{"include":[]},"cli":false},"extends":"SmrtCollection","extendsTypeArg":"UsersMagicLinkToken","exportName":"UsersMagicLinkTokenCollection","collectionExportName":"UsersMagicLinkTokenCollectionCollection","schema":{"tableName":"users_magic_link_tokens","ddl":"CREATE TABLE IF NOT EXISTS \\"users_magic_link_tokens\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"nonce\\" TEXT NOT NULL UNIQUE DEFAULT '',\\n \\"email\\" TEXT DEFAULT '',\\n \\"used\\" BOOLEAN DEFAULT FALSE,\\n \\"expires_at\\" TIMESTAMP\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"nonce":{"type":"TEXT","notNull":true,"unique":true,"default":""},"email":{"type":"TEXT","notNull":false,"unique":false,"default":""},"used":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"users_magic_link_tokens_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_magic_link_tokens_expires_at_idx","columns":["expires_at"]},{"name":"users_magic_link_tokens_created_at_idx","columns":["created_at"]}],"version":"537853d3"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:MembershipCollection":{"name":"membershipcollection","className":"MembershipCollection","qualifiedName":"@happyvertical/smrt-users:MembershipCollection","collection":"memberships","description":"Collection for managing Membership objects","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/MembershipCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"findByUser":{"name":"findByUser","async":true,"parameters":[{"name":"userId","type":"string","optional":false}],"returnType":"Promise<Membership[]>","isStatic":false,"isPublic":true},"findActiveByUser":{"name":"findActiveByUser","async":true,"parameters":[{"name":"userId","type":"string","optional":false}],"returnType":"Promise<Membership[]>","isStatic":false,"isPublic":true},"findByTenant":{"name":"findByTenant","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Membership[]>","isStatic":false,"isPublic":true},"findActiveByTenant":{"name":"findActiveByTenant","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Membership[]>","isStatic":false,"isPublic":true},"findByUserAndTenant":{"name":"findByUserAndTenant","async":true,"parameters":[{"name":"userId","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Membership | null>","isStatic":false,"isPublic":true},"findByRole":{"name":"findByRole","async":true,"parameters":[{"name":"roleId","type":"string","optional":false}],"returnType":"Promise<Membership[]>","isStatic":false,"isPublic":true},"findByStatus":{"name":"findByStatus","async":true,"parameters":[{"name":"status","type":"MembershipStatus","optional":false}],"returnType":"Promise<Membership[]>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"Membership","exportName":"MembershipCollection","collectionExportName":"MembershipCollectionCollection","schema":{"tableName":"memberships","ddl":"CREATE TABLE IF NOT EXISTS \\"memberships\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"user_id\\" UUID NOT NULL,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"role_id\\" UUID NOT NULL,\\n \\"status\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"user_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"users","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"tenant_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"tenants","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"role_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"roles","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"status":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"memberships_tenant_id_slug_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"memberships_tenant_id_user_id_idx","columns":["tenant_id","user_id"]},{"name":"memberships_created_at_idx","columns":["created_at"]},{"name":"memberships_user_id_idx","columns":["user_id"]},{"name":"memberships_role_id_idx","columns":["role_id"]}],"version":"ebfd11e0"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:MembershipOverrideCollection":{"name":"membershipoverridecollection","className":"MembershipOverrideCollection","qualifiedName":"@happyvertical/smrt-users:MembershipOverrideCollection","collection":"membershipoverrides","description":"Collection for managing MembershipOverride objects","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/MembershipOverrideCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"findByMembership":{"name":"findByMembership","async":true,"parameters":[{"name":"membershipId","type":"string","optional":false}],"returnType":"Promise<MembershipOverride[]>","isStatic":false,"isPublic":true},"findGrants":{"name":"findGrants","async":true,"parameters":[{"name":"membershipId","type":"string","optional":false}],"returnType":"Promise<MembershipOverride[]>","isStatic":false,"isPublic":true},"findDenies":{"name":"findDenies","async":true,"parameters":[{"name":"membershipId","type":"string","optional":false}],"returnType":"Promise<MembershipOverride[]>","isStatic":false,"isPublic":true},"getGrantedPermissionIds":{"name":"getGrantedPermissionIds","async":true,"parameters":[{"name":"membershipId","type":"string","optional":false}],"returnType":"Promise<string[]>","isStatic":false,"isPublic":true},"getDeniedPermissionIds":{"name":"getDeniedPermissionIds","async":true,"parameters":[{"name":"membershipId","type":"string","optional":false}],"returnType":"Promise<string[]>","isStatic":false,"isPublic":true},"setOverride":{"name":"setOverride","async":true,"parameters":[{"name":"membershipId","type":"string","optional":false},{"name":"permissionId","type":"string","optional":false},{"name":"effect","type":"OverrideEffect","optional":false}],"returnType":"Promise<MembershipOverride>","isStatic":false,"isPublic":true},"removeOverride":{"name":"removeOverride","async":true,"parameters":[{"name":"membershipId","type":"string","optional":false},{"name":"permissionId","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"grantPermission":{"name":"grantPermission","async":true,"parameters":[{"name":"membershipId","type":"string","optional":false},{"name":"permissionId","type":"string","optional":false}],"returnType":"Promise<MembershipOverride>","isStatic":false,"isPublic":true},"denyPermission":{"name":"denyPermission","async":true,"parameters":[{"name":"membershipId","type":"string","optional":false},{"name":"permissionId","type":"string","optional":false}],"returnType":"Promise<MembershipOverride>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"MembershipOverride","exportName":"MembershipOverrideCollection","collectionExportName":"MembershipOverrideCollectionCollection","schema":{"tableName":"membership_overrides","ddl":"CREATE TABLE IF NOT EXISTS \\"membership_overrides\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"membership_id\\" UUID NOT NULL,\\n \\"permission_id\\" UUID NOT NULL,\\n \\"effect\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"membership_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"memberships","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"permission_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"permissions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"effect":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"membership_overrides_membership_id_permission_id_idx","columns":["membership_id","permission_id"],"unique":true},{"name":"membership_overrides_slug_context_idx","columns":["slug","context"]},{"name":"membership_overrides_created_at_idx","columns":["created_at"]},{"name":"membership_overrides_permission_id_idx","columns":["permission_id"]}],"version":"25fe9da8"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersOAuthClientCollection":{"name":"usersoauthclientcollection","className":"UsersOAuthClientCollection","qualifiedName":"@happyvertical/smrt-users:UsersOAuthClientCollection","collection":"usersoauthclients","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/OAuthAuthorizationCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"findByClientId":{"name":"findByClientId","async":false,"parameters":[{"name":"clientId","type":"string","optional":false}],"returnType":"Promise<UsersOAuthClient | null>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"users_oauth_clients","api":{"include":[]},"mcp":{"include":[]},"cli":false},"extends":"SmrtCollection","extendsTypeArg":"UsersOAuthClient","exportName":"UsersOAuthClientCollection","collectionExportName":"UsersOAuthClientCollectionCollection","schema":{"tableName":"users_oauth_clients","ddl":"CREATE TABLE IF NOT EXISTS \\"users_oauth_clients\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"client_id\\" TEXT NOT NULL UNIQUE,\\n \\"redirect_uris\\" TEXT,\\n \\"allowed_scopes\\" TEXT,\\n \\"token_endpoint_auth_method\\" TEXT DEFAULT 'none',\\n \\"secret_hash\\" TEXT,\\n \\"allowed_resources\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"client_id":{"type":"TEXT","notNull":true,"unique":true},"redirect_uris":{"type":"TEXT","notNull":false,"unique":false},"allowed_scopes":{"type":"TEXT","notNull":false,"unique":false},"token_endpoint_auth_method":{"type":"TEXT","notNull":false,"unique":false,"default":"none"},"secret_hash":{"type":"TEXT","notNull":false,"unique":false},"allowed_resources":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"users_oauth_clients_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_oauth_clients_created_at_idx","columns":["created_at"]}],"version":"0ecda18c"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersOAuthAuthorizationCodeCollection":{"name":"usersoauthauthorizationcodecollection","className":"UsersOAuthAuthorizationCodeCollection","qualifiedName":"@happyvertical/smrt-users:UsersOAuthAuthorizationCodeCollection","collection":"usersoauthauthorizationcodes","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/OAuthAuthorizationCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"consume":{"name":"consume","async":true,"parameters":[{"name":"id","type":"string","optional":false},{"name":"codeHash","type":"string","optional":false},{"name":"clientId","type":"string","optional":false},{"name":"redirectUri","type":"string","optional":false},{"name":"resource","type":"string | null","optional":false,"unionBranches":[{"type":"string"},{"type":"null"}]},{"name":"now","type":"Date","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"users_oauth_authorization_codes","api":{"include":[]},"mcp":{"include":[]},"cli":false},"extends":"SmrtCollection","extendsTypeArg":"UsersOAuthAuthorizationCode","exportName":"UsersOAuthAuthorizationCodeCollection","collectionExportName":"UsersOAuthAuthorizationCodeCollectionCollection","schema":{"tableName":"users_oauth_authorization_codes","ddl":"CREATE TABLE IF NOT EXISTS \\"users_oauth_authorization_codes\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"authorization_id\\" TEXT,\\n \\"code_hash\\" TEXT NOT NULL UNIQUE,\\n \\"client_id\\" TEXT,\\n \\"subject\\" TEXT,\\n \\"tenant_id\\" TEXT,\\n \\"claims\\" TEXT,\\n \\"redirect_uri\\" TEXT,\\n \\"scopes\\" TEXT,\\n \\"resource\\" TEXT,\\n \\"code_challenge\\" TEXT,\\n \\"expires_at\\" TIMESTAMP,\\n \\"consumed_at\\" TIMESTAMP\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"authorization_id":{"type":"TEXT","notNull":false,"unique":false},"code_hash":{"type":"TEXT","notNull":true,"unique":true},"client_id":{"type":"TEXT","notNull":false,"unique":false},"subject":{"type":"TEXT","notNull":false,"unique":false},"tenant_id":{"type":"TEXT","notNull":false,"unique":false},"claims":{"type":"TEXT","notNull":false,"unique":false},"redirect_uri":{"type":"TEXT","notNull":false,"unique":false},"scopes":{"type":"TEXT","notNull":false,"unique":false},"resource":{"type":"TEXT","notNull":false,"unique":false},"code_challenge":{"type":"TEXT","notNull":false,"unique":false},"expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"consumed_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"users_oauth_authorization_codes_tenant_id_slug_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"users_oauth_authorization_codes_authorization_id_idx","columns":["authorization_id"]},{"name":"users_oauth_authorization_codes_client_id_idx","columns":["client_id"]},{"name":"users_oauth_authorization_codes_subject_idx","columns":["subject"]},{"name":"users_oauth_authorization_codes_tenant_id_idx","columns":["tenant_id"]},{"name":"users_oauth_authorization_codes_expires_at_idx","columns":["expires_at"]},{"name":"users_oauth_authorization_codes_created_at_idx","columns":["created_at"]}],"version":"f5c5d615"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersOAuthRefreshGrantCollection":{"name":"usersoauthrefreshgrantcollection","className":"UsersOAuthRefreshGrantCollection","qualifiedName":"@happyvertical/smrt-users:UsersOAuthRefreshGrantCollection","collection":"usersoauthrefreshgrants","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/OAuthAuthorizationCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"consume":{"name":"consume","async":true,"parameters":[{"name":"id","type":"string","optional":false},{"name":"tokenHash","type":"string","optional":false},{"name":"clientId","type":"string","optional":false},{"name":"resource","type":"string | null","optional":false,"unionBranches":[{"type":"string"},{"type":"null"}]},{"name":"now","type":"Date","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"revokeFamily":{"name":"revokeFamily","async":true,"parameters":[{"name":"familyId","type":"string","optional":false},{"name":"now","type":"Date","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"users_oauth_refresh_grants","api":{"include":[]},"mcp":{"include":[]},"cli":false},"extends":"SmrtCollection","extendsTypeArg":"UsersOAuthRefreshGrant","exportName":"UsersOAuthRefreshGrantCollection","collectionExportName":"UsersOAuthRefreshGrantCollectionCollection","schema":{"tableName":"users_oauth_refresh_grants","ddl":"CREATE TABLE IF NOT EXISTS \\"users_oauth_refresh_grants\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"authorization_id\\" TEXT,\\n \\"token_hash\\" TEXT NOT NULL UNIQUE,\\n \\"family_id\\" TEXT,\\n \\"client_id\\" TEXT,\\n \\"subject\\" TEXT,\\n \\"tenant_id\\" TEXT,\\n \\"claims\\" TEXT,\\n \\"scopes\\" TEXT,\\n \\"resource\\" TEXT,\\n \\"expires_at\\" TIMESTAMP,\\n \\"consumed_at\\" TIMESTAMP,\\n \\"revoked_at\\" TIMESTAMP\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"authorization_id":{"type":"TEXT","notNull":false,"unique":false},"token_hash":{"type":"TEXT","notNull":true,"unique":true},"family_id":{"type":"TEXT","notNull":false,"unique":false},"client_id":{"type":"TEXT","notNull":false,"unique":false},"subject":{"type":"TEXT","notNull":false,"unique":false},"tenant_id":{"type":"TEXT","notNull":false,"unique":false},"claims":{"type":"TEXT","notNull":false,"unique":false},"scopes":{"type":"TEXT","notNull":false,"unique":false},"resource":{"type":"TEXT","notNull":false,"unique":false},"expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"consumed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"revoked_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"users_oauth_refresh_grants_tenant_id_slug_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"users_oauth_refresh_grants_authorization_id_idx","columns":["authorization_id"]},{"name":"users_oauth_refresh_grants_family_id_idx","columns":["family_id"]},{"name":"users_oauth_refresh_grants_client_id_idx","columns":["client_id"]},{"name":"users_oauth_refresh_grants_subject_idx","columns":["subject"]},{"name":"users_oauth_refresh_grants_tenant_id_idx","columns":["tenant_id"]},{"name":"users_oauth_refresh_grants_expires_at_idx","columns":["expires_at"]},{"name":"users_oauth_refresh_grants_revoked_at_idx","columns":["revoked_at"]},{"name":"users_oauth_refresh_grants_created_at_idx","columns":["created_at"]}],"version":"d332998e"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersOAuthAccessTokenRevocationCollection":{"name":"usersoauthaccesstokenrevocationcollection","className":"UsersOAuthAccessTokenRevocationCollection","qualifiedName":"@happyvertical/smrt-users:UsersOAuthAccessTokenRevocationCollection","collection":"usersoauthaccesstokenrevocations","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/OAuthAuthorizationCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"findByJti":{"name":"findByJti","async":true,"parameters":[{"name":"jti","type":"string","optional":false}],"returnType":"Promise<UsersOAuthAccessTokenRevocation | null>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"users_oauth_access_token_revocations","api":{"include":[]},"mcp":{"include":[]},"cli":false},"extends":"SmrtCollection","extendsTypeArg":"UsersOAuthAccessTokenRevocation","exportName":"UsersOAuthAccessTokenRevocationCollection","collectionExportName":"UsersOAuthAccessTokenRevocationCollectionCollection","schema":{"tableName":"users_oauth_access_token_revocations","ddl":"CREATE TABLE IF NOT EXISTS \\"users_oauth_access_token_revocations\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"jti\\" TEXT NOT NULL UNIQUE,\\n \\"expires_at\\" TIMESTAMP\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"jti":{"type":"TEXT","notNull":true,"unique":true},"expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"users_oauth_access_token_revocations_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_oauth_access_token_revocations_expires_at_idx","columns":["expires_at"]},{"name":"users_oauth_access_token_revocations_created_at_idx","columns":["created_at"]}],"version":"79147089"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersOAuthAuthorizationCollection":{"name":"usersoauthauthorizationcollection","className":"UsersOAuthAuthorizationCollection","qualifiedName":"@happyvertical/smrt-users:UsersOAuthAuthorizationCollection","collection":"usersoauthauthorizations","description":"Consent storage is intentionally inaccessible through generated surfaces.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/OAuthAuthorizationCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{},"decoratorConfig":{"tableName":"users_oauth_authorizations","api":{"include":[]},"mcp":{"include":[]},"cli":false},"extends":"SmrtCollection","extendsTypeArg":"UsersOAuthAuthorization","exportName":"UsersOAuthAuthorizationCollection","collectionExportName":"UsersOAuthAuthorizationCollectionCollection","schema":{"tableName":"users_oauth_authorizations","ddl":"CREATE TABLE IF NOT EXISTS \\"users_oauth_authorizations\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"subject\\" TEXT,\\n \\"session_id\\" TEXT,\\n \\"client_id\\" TEXT,\\n \\"tenant_id\\" TEXT,\\n \\"scopes\\" TEXT,\\n \\"permission_ceiling\\" TEXT,\\n \\"resource\\" TEXT,\\n \\"revoked_at\\" TIMESTAMP\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"subject":{"type":"TEXT","notNull":false,"unique":false},"session_id":{"type":"TEXT","notNull":false,"unique":false},"client_id":{"type":"TEXT","notNull":false,"unique":false},"tenant_id":{"type":"TEXT","notNull":false,"unique":false},"scopes":{"type":"TEXT","notNull":false,"unique":false},"permission_ceiling":{"type":"TEXT","notNull":false,"unique":false},"resource":{"type":"TEXT","notNull":false,"unique":false},"revoked_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"users_oauth_authorizations_tenant_id_slug_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"users_oauth_authorizations_subject_idx","columns":["subject"]},{"name":"users_oauth_authorizations_client_id_idx","columns":["client_id"]},{"name":"users_oauth_authorizations_created_at_idx","columns":["created_at"]}],"version":"291f8816"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersOAuthRefreshFamilyCollection":{"name":"usersoauthrefreshfamilycollection","className":"UsersOAuthRefreshFamilyCollection","qualifiedName":"@happyvertical/smrt-users:UsersOAuthRefreshFamilyCollection","collection":"usersoauthrefreshfamilies","description":"Family rows exist for the entire lifetime of every descendant refresh token.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/OAuthAuthorizationCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"lock":{"name":"lock","async":true,"parameters":[{"name":"id","type":"string","optional":false},{"name":"now","type":"Date","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"revoke":{"name":"revoke","async":true,"parameters":[{"name":"id","type":"string","optional":false},{"name":"now","type":"Date","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"users_oauth_refresh_families","api":{"include":[]},"mcp":{"include":[]},"cli":false},"extends":"SmrtCollection","extendsTypeArg":"UsersOAuthRefreshFamily","exportName":"UsersOAuthRefreshFamilyCollection","collectionExportName":"UsersOAuthRefreshFamilyCollectionCollection","schema":{"tableName":"users_oauth_refresh_families","ddl":"CREATE TABLE IF NOT EXISTS \\"users_oauth_refresh_families\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"authorization_id\\" TEXT,\\n \\"revoked_at\\" TIMESTAMP\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"authorization_id":{"type":"TEXT","notNull":false,"unique":false},"revoked_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"users_oauth_refresh_families_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_oauth_refresh_families_authorization_id_idx","columns":["authorization_id"]},{"name":"users_oauth_refresh_families_created_at_idx","columns":["created_at"]}],"version":"37392f31"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersPasswordCredentialCollection":{"name":"userspasswordcredentialcollection","className":"UsersPasswordCredentialCollection","qualifiedName":"@happyvertical/smrt-users:UsersPasswordCredentialCollection","collection":"userspasswordcredentials","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/PasswordCredentialCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"findByUserId":{"name":"findByUserId","async":true,"parameters":[{"name":"userId","type":"string","optional":false}],"returnType":"Promise<UsersPasswordCredential | null>","isStatic":false,"isPublic":true},"insertIfAbsent":{"name":"insertIfAbsent","async":true,"parameters":[{"name":"userId","type":"string","optional":false},{"name":"write","type":"PasswordCredentialWrite","optional":false}],"returnType":"Promise<UsersPasswordCredential | null>","isStatic":false,"isPublic":true},"upsertForUser":{"name":"upsertForUser","async":true,"parameters":[{"name":"userId","type":"string","optional":false},{"name":"write","type":"PasswordCredentialWrite","optional":false}],"returnType":"Promise<UsersPasswordCredential>","isStatic":false,"isPublic":true},"replaceIfCurrent":{"name":"replaceIfCurrent","async":true,"parameters":[{"name":"expected","type":"UsersPasswordCredential","optional":false},{"name":"write","type":"Omit<PasswordCredentialWrite, 'mustChange'>","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"deleteIfCurrent":{"name":"deleteIfCurrent","async":true,"parameters":[{"name":"expected","type":"UsersPasswordCredential","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"replaceHashIfUnchanged":{"name":"replaceHashIfUnchanged","async":true,"parameters":[{"name":"userId","type":"string","optional":false},{"name":"expectedHash","type":"string","optional":false},{"name":"upgradedHash","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"deleteByUserId":{"name":"deleteByUserId","async":true,"parameters":[{"name":"userId","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"users_password_credentials","api":false,"mcp":false,"cli":false},"extends":"SmrtCollection","extendsTypeArg":"UsersPasswordCredential","exportName":"UsersPasswordCredentialCollection","collectionExportName":"UsersPasswordCredentialCollectionCollection","schema":{"tableName":"users_password_credentials","ddl":"CREATE TABLE IF NOT EXISTS \\"users_password_credentials\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"user_id\\" UUID NOT NULL UNIQUE,\\n \\"password_hash\\" TEXT NOT NULL,\\n \\"version\\" INTEGER NOT NULL DEFAULT 1,\\n \\"must_change\\" BOOLEAN NOT NULL DEFAULT FALSE,\\n \\"rotated_at\\" TIMESTAMP,\\n \\"rotated_by\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"user_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":true,"foreignKey":{"table":"users","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"password_hash":{"type":"TEXT","notNull":true,"unique":false},"version":{"type":"INTEGER","notNull":true,"unique":false,"default":1},"must_change":{"type":"BOOLEAN","notNull":true,"unique":false,"default":false},"rotated_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"rotated_by":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"users_password_credentials_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_password_credentials_created_at_idx","columns":["created_at"]}],"version":"9a828f77"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:PermissionCollection":{"name":"permissioncollection","className":"PermissionCollection","qualifiedName":"@happyvertical/smrt-users:PermissionCollection","collection":"permissions","description":"Collection for managing Permission objects","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/PermissionCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"findByCategory":{"name":"findByCategory","async":true,"parameters":[{"name":"category","type":"string","optional":false}],"returnType":"Promise<Permission[]>","isStatic":false,"isPublic":true},"findBySlug":{"name":"findBySlug","async":true,"parameters":[{"name":"slug","type":"string","optional":false}],"returnType":"Promise<Permission | null>","isStatic":false,"isPublic":true},"findByIds":{"name":"findByIds","async":true,"parameters":[{"name":"ids","type":"string[]","optional":false}],"returnType":"Promise<Map<string, Permission>>","isStatic":false,"isPublic":true},"getCategories":{"name":"getCategories","async":true,"parameters":[],"returnType":"Promise<string[]>","isStatic":false,"isPublic":true},"findOrCreate":{"name":"findOrCreate","async":true,"parameters":[{"name":"slug","type":"string","optional":false},{"name":"defaults","type":"Partial<object>","optional":true,"memberTypes":["string"]}],"returnType":"Promise<Permission>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"Permission","exportName":"PermissionCollection","collectionExportName":"PermissionCollectionCollection","schema":{"tableName":"permissions","ddl":"CREATE TABLE IF NOT EXISTS \\"permissions\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"name\\" TEXT DEFAULT '',\\n \\"description\\" TEXT DEFAULT '',\\n \\"category\\" TEXT DEFAULT ''\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"description":{"type":"TEXT","notNull":false,"unique":false,"default":""},"category":{"type":"TEXT","notNull":false,"unique":false,"default":""}},"indexes":[{"name":"permissions_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"permissions_created_at_idx","columns":["created_at"]}],"version":"4c81b2af"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersPinCredentialCollection":{"name":"userspincredentialcollection","className":"UsersPinCredentialCollection","qualifiedName":"@happyvertical/smrt-users:UsersPinCredentialCollection","collection":"userspincredentials","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/PinCredentialCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"findByUserId":{"name":"findByUserId","async":true,"parameters":[{"name":"userId","type":"string","optional":false}],"returnType":"Promise<UsersPinCredential | null>","isStatic":false,"isPublic":true},"upsertForUser":{"name":"upsertForUser","async":true,"parameters":[{"name":"userId","type":"string","optional":false},{"name":"write","type":"PinCredentialWrite","optional":false}],"returnType":"Promise<UsersPinCredential>","isStatic":false,"isPublic":true},"deleteByUserId":{"name":"deleteByUserId","async":true,"parameters":[{"name":"userId","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"users_pin_credentials","api":false,"mcp":false,"cli":false},"extends":"SmrtCollection","extendsTypeArg":"UsersPinCredential","exportName":"UsersPinCredentialCollection","collectionExportName":"UsersPinCredentialCollectionCollection","schema":{"tableName":"users_pin_credentials","ddl":"CREATE TABLE IF NOT EXISTS \\"users_pin_credentials\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"user_id\\" UUID NOT NULL UNIQUE,\\n \\"pin_hash\\" TEXT NOT NULL,\\n \\"version\\" INTEGER NOT NULL DEFAULT 1,\\n \\"must_reset\\" BOOLEAN NOT NULL DEFAULT FALSE,\\n \\"rotated_at\\" TIMESTAMP,\\n \\"rotated_by\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"user_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":true,"foreignKey":{"table":"users","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"pin_hash":{"type":"TEXT","notNull":true,"unique":false},"version":{"type":"INTEGER","notNull":true,"unique":false,"default":1},"must_reset":{"type":"BOOLEAN","notNull":true,"unique":false,"default":false},"rotated_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"rotated_by":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"users_pin_credentials_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_pin_credentials_created_at_idx","columns":["created_at"]}],"version":"0e2fa003"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:ResourceGrantCollection":{"name":"resourcegrantcollection","className":"ResourceGrantCollection","qualifiedName":"@happyvertical/smrt-users:ResourceGrantCollection","collection":"resourcegrants","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/ResourceGrantCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"findExact":{"name":"findExact","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false},{"name":"userId","type":"string","optional":false},{"name":"resourceType","type":"string","optional":false},{"name":"resourceId","type":"string","optional":false},{"name":"permission","type":"string","optional":false}],"returnType":"Promise<ResourceGrant[]>","isStatic":false,"isPublic":true},"findChildren":{"name":"findChildren","async":true,"parameters":[{"name":"parentGrantId","type":"string","optional":false}],"returnType":"Promise<ResourceGrant[]>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":[]},"mcp":{"include":[]},"cli":false},"extends":"SmrtCollection","extendsTypeArg":"ResourceGrant","exportName":"ResourceGrantCollection","collectionExportName":"ResourceGrantCollectionCollection","schema":{"tableName":"resource_grants","ddl":"CREATE TABLE IF NOT EXISTS \\"resource_grants\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"user_id\\" UUID NOT NULL,\\n \\"resource_type\\" TEXT,\\n \\"resource_id\\" TEXT,\\n \\"permission\\" TEXT,\\n \\"effect\\" TEXT,\\n \\"can_delegate\\" BOOLEAN DEFAULT FALSE,\\n \\"parent_grant_id\\" UUID,\\n \\"revoked_at\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"user_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"users","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"resource_type":{"type":"TEXT","notNull":false,"unique":false},"resource_id":{"type":"TEXT","notNull":false,"unique":false},"permission":{"type":"TEXT","notNull":false,"unique":false},"effect":{"type":"TEXT","notNull":false,"unique":false},"can_delegate":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"parent_grant_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"resource_grants","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"revoked_at":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"resource_grants_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"resource_grants_lookup_idx","columns":["tenant_id","user_id"]},{"name":"resource_grants_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"resource_grants_user_id_idx","columns":["user_id"]},{"name":"resource_grants_parent_grant_id_idx","columns":["parent_grant_id"]}],"version":"52e03776"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:RoleCollection":{"name":"rolecollection","className":"RoleCollection","qualifiedName":"@happyvertical/smrt-users:RoleCollection","collection":"roles","description":"Collection for managing Role objects","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/RoleCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"findSystemRoles":{"name":"findSystemRoles","async":true,"parameters":[],"returnType":"Promise<Role[]>","isStatic":false,"isPublic":true},"findByTenant":{"name":"findByTenant","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Role[]>","isStatic":false,"isPublic":true},"findTenantRoles":{"name":"findTenantRoles","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Role[]>","isStatic":false,"isPublic":true},"findBySlug":{"name":"findBySlug","async":true,"parameters":[{"name":"slug","type":"string","optional":false},{"name":"tenantId","type":"string","optional":true}],"returnType":"Promise<Role | null>","isStatic":false,"isPublic":true},"findSystemRoleBySlug":{"name":"findSystemRoleBySlug","async":true,"parameters":[{"name":"slug","type":"string","optional":false}],"returnType":"Promise<Role | null>","isStatic":false,"isPublic":true},"seedSystemRoles":{"name":"seedSystemRoles","async":true,"parameters":[{"name":"options","type":"SeedSystemRolesOptions","optional":true}],"returnType":"Promise<Role[]>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"Role","exportName":"RoleCollection","collectionExportName":"RoleCollectionCollection","schema":{"tableName":"roles","ddl":"CREATE TABLE IF NOT EXISTS \\"roles\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"name\\" TEXT DEFAULT '',\\n \\"description\\" TEXT DEFAULT '',\\n \\"is_system\\" BOOLEAN DEFAULT FALSE,\\n \\"inherits_to_descendants\\" BOOLEAN DEFAULT FALSE\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"tenants","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"description":{"type":"TEXT","notNull":false,"unique":false,"default":""},"is_system":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"inherits_to_descendants":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false}},"indexes":[{"name":"roles_tenant_id_slug_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"roles_created_at_idx","columns":["created_at"]}],"version":"47369d9d"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:RolePermissionCollection":{"name":"rolepermissioncollection","className":"RolePermissionCollection","qualifiedName":"@happyvertical/smrt-users:RolePermissionCollection","collection":"rolepermissions","description":"Collection for managing RolePermission objects","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/RolePermissionCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"findByRole":{"name":"findByRole","async":true,"parameters":[{"name":"roleId","type":"string","optional":false}],"returnType":"Promise<RolePermission[]>","isStatic":false,"isPublic":true},"findByPermission":{"name":"findByPermission","async":true,"parameters":[{"name":"permissionId","type":"string","optional":false}],"returnType":"Promise<RolePermission[]>","isStatic":false,"isPublic":true},"hasPermission":{"name":"hasPermission","async":true,"parameters":[{"name":"roleId","type":"string","optional":false},{"name":"permissionId","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"addPermission":{"name":"addPermission","async":true,"parameters":[{"name":"roleId","type":"string","optional":false},{"name":"permissionId","type":"string","optional":false}],"returnType":"Promise<RolePermission>","isStatic":false,"isPublic":true},"removePermission":{"name":"removePermission","async":true,"parameters":[{"name":"roleId","type":"string","optional":false},{"name":"permissionId","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"getPermissionIds":{"name":"getPermissionIds","async":true,"parameters":[{"name":"roleId","type":"string","optional":false}],"returnType":"Promise<string[]>","isStatic":false,"isPublic":true},"seedRolePermissions":{"name":"seedRolePermissions","async":true,"parameters":[{"name":"matrix","type":"RolePermissionPatternMatrix","optional":true},{"name":"options","type":"SeedRolePermissionsOptions","optional":true}],"returnType":"Promise<SeedRolePermissionsResult>","isStatic":false,"isPublic":true},"seedDefaultRolePersonalizationPermissions":{"name":"seedDefaultRolePersonalizationPermissions","async":true,"parameters":[{"name":"options","type":"Omit<SeedRolePermissionsOptions, 'prune'>","optional":true}],"returnType":"Promise<SeedRolePermissionsResult>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"RolePermission","exportName":"RolePermissionCollection","collectionExportName":"RolePermissionCollectionCollection","schema":{"tableName":"role_permissions","ddl":"CREATE TABLE IF NOT EXISTS \\"role_permissions\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"role_id\\" UUID NOT NULL,\\n \\"permission_id\\" UUID NOT NULL\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"role_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"roles","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"permission_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"permissions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}}},"indexes":[{"name":"role_permissions_role_id_permission_id_idx","columns":["role_id","permission_id"],"unique":true},{"name":"role_permissions_slug_context_idx","columns":["slug","context"]},{"name":"role_permissions_created_at_idx","columns":["created_at"]},{"name":"role_permissions_permission_id_idx","columns":["permission_id"]}],"version":"4dfed3ac"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:SessionCollection":{"name":"sessioncollection","className":"SessionCollection","qualifiedName":"@happyvertical/smrt-users:SessionCollection","collection":"sessions","description":"Collection for managing Session objects","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/SessionCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"createSession":{"name":"createSession","async":true,"parameters":[{"name":"options","type":"CreateSessionOptions","optional":false}],"returnType":"Promise<Session>","isStatic":false,"isPublic":true},"findChildren":{"name":"findChildren","async":true,"parameters":[{"name":"parentSessionId","type":"string","optional":false}],"returnType":"Promise<Session[]>","isStatic":false,"isPublic":true},"revokeChildren":{"name":"revokeChildren","async":true,"parameters":[{"name":"parentSessionId","type":"string","optional":false},{"name":"options","type":"object","optional":true,"memberTypes":["string"]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true},"revokeUserSessionsByAuthMethod":{"name":"revokeUserSessionsByAuthMethod","async":true,"parameters":[{"name":"userId","type":"string","optional":false},{"name":"authMethod","type":"SessionAuthMethod","optional":false},{"name":"options","type":"object","optional":true,"memberTypes":["string"]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true},"findValidSession":{"name":"findValidSession","async":true,"parameters":[{"name":"sessionId","type":"string","optional":false}],"returnType":"Promise<Session | null>","isStatic":false,"isPublic":true},"touch":{"name":"touch","async":true,"parameters":[{"name":"sessionId","type":"string","optional":false},{"name":"extendTtl","type":"boolean","optional":true},{"name":"ttl","type":"number","optional":true}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"findByUser":{"name":"findByUser","async":true,"parameters":[{"name":"userId","type":"string","optional":false}],"returnType":"Promise<Session[]>","isStatic":false,"isPublic":true},"deleteUserSessions":{"name":"deleteUserSessions","async":true,"parameters":[{"name":"userId","type":"string","optional":false}],"returnType":"Promise<number>","isStatic":false,"isPublic":true},"revokeUserSessions":{"name":"revokeUserSessions","async":true,"parameters":[{"name":"userId","type":"string","optional":false},{"name":"options","type":"object","optional":true,"memberTypes":["string"]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true},"revokeSession":{"name":"revokeSession","async":true,"parameters":[{"name":"sessionId","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"deleteExpired":{"name":"deleteExpired","async":true,"parameters":[{"name":"options","type":"object","optional":true,"memberTypes":["boolean"]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true},"countUserSessions":{"name":"countUserSessions","async":true,"parameters":[{"name":"userId","type":"string","optional":false}],"returnType":"Promise<number>","isStatic":false,"isPublic":true},"setSessionTenant":{"name":"setSessionTenant","async":true,"parameters":[{"name":"sessionId","type":"string","optional":false},{"name":"tenantId","type":"string | null","optional":false,"unionBranches":[{"type":"string"},{"type":"null"}]}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"setSessionData":{"name":"setSessionData","async":true,"parameters":[{"name":"sessionId","type":"string","optional":false},{"name":"key","type":"string","optional":false},{"name":"value","type":"unknown","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"getSessionData":{"name":"getSessionData","async":true,"parameters":[{"name":"sessionId","type":"string","optional":false},{"name":"key","type":"string","optional":false}],"returnType":"Promise<T | undefined>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["get","delete"]},"mcp":{"include":[]},"cli":false},"extends":"SmrtCollection","extendsTypeArg":"Session","exportName":"SessionCollection","collectionExportName":"SessionCollectionCollection","schema":{"tableName":"sessions","ddl":"CREATE TABLE IF NOT EXISTS \\"sessions\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"user_id\\" UUID,\\n \\"tenant_id\\" UUID,\\n \\"status\\" TEXT,\\n \\"expires_at\\" TIMESTAMP,\\n \\"user_agent\\" TEXT DEFAULT '',\\n \\"ip_address\\" TEXT DEFAULT '',\\n \\"last_accessed_at\\" TIMESTAMP,\\n \\"data\\" JSON DEFAULT '{}',\\n \\"auth_method\\" TEXT,\\n \\"parent_session_id\\" UUID\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"user_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"users","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"tenant_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"tenants","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"status":{"type":"TEXT","notNull":false,"unique":false},"expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"user_agent":{"type":"TEXT","notNull":false,"unique":false,"default":""},"ip_address":{"type":"TEXT","notNull":false,"unique":false,"default":""},"last_accessed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"data":{"type":"JSON","notNull":false,"unique":false,"default":{}},"auth_method":{"type":"TEXT","notNull":false,"unique":false},"parent_session_id":{"type":"UUID","notNull":false,"unique":false}},"indexes":[{"name":"sessions_tenant_id_slug_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"sessions_expires_at_idx","columns":["expires_at"]},{"name":"sessions_parent_session_id_idx","columns":["parent_session_id"]},{"name":"sessions_created_at_idx","columns":["created_at"]},{"name":"sessions_user_id_idx","columns":["user_id"]}],"version":"b4260a0f"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:TenantCollection":{"name":"tenantcollection","className":"TenantCollection","qualifiedName":"@happyvertical/smrt-users:TenantCollection","collection":"tenants","description":"Collection for managing Tenant objects with hierarchical support.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/TenantCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"findByStatus":{"name":"findByStatus","async":true,"parameters":[{"name":"status","type":"TenantStatus","optional":false}],"returnType":"Promise<Tenant[]>","isStatic":false,"isPublic":true},"findActive":{"name":"findActive","async":true,"parameters":[],"returnType":"Promise<Tenant[]>","isStatic":false,"isPublic":true},"findBySlug":{"name":"findBySlug","async":true,"parameters":[{"name":"slug","type":"string","optional":false}],"returnType":"Promise<Tenant | null>","isStatic":false,"isPublic":true},"findRoots":{"name":"findRoots","async":true,"parameters":[],"returnType":"Promise<Tenant[]>","isStatic":false,"isPublic":true},"findChildren":{"name":"findChildren","async":true,"parameters":[{"name":"parentTenantId","type":"string","optional":false}],"returnType":"Promise<Tenant[]>","isStatic":false,"isPublic":true},"findParent":{"name":"findParent","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Tenant | null>","isStatic":false,"isPublic":true},"getAncestors":{"name":"getAncestors","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Tenant[]>","isStatic":false,"isPublic":true},"getAncestorIds":{"name":"getAncestorIds","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<string[]>","isStatic":false,"isPublic":true},"getAncestorsFromRoot":{"name":"getAncestorsFromRoot","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Tenant[]>","isStatic":false,"isPublic":true},"getDescendants":{"name":"getDescendants","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Tenant[]>","isStatic":false,"isPublic":true},"getDescendantIds":{"name":"getDescendantIds","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<string[]>","isStatic":false,"isPublic":true},"getSiblings":{"name":"getSiblings","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Tenant[]>","isStatic":false,"isPublic":true},"isAncestorOf":{"name":"isAncestorOf","async":true,"parameters":[{"name":"potentialAncestorId","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"isDescendantOf":{"name":"isDescendantOf","async":true,"parameters":[{"name":"potentialDescendantId","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"requireChildOf":{"name":"requireChildOf","async":true,"parameters":[{"name":"parentId","type":"string","optional":false},{"name":"childId","type":"string","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"withTenantCatalogReadScope":{"name":"withTenantCatalogReadScope","async":true,"parameters":[{"name":"options","type":"TenantReadScopeOptions","optional":false},{"name":"callback","type":"Function","optional":false}],"returnType":"Promise<T>","isStatic":false,"isPublic":true},"withTenantHierarchyContext":{"name":"withTenantHierarchyContext","async":true,"parameters":[{"name":"rootTenantId","type":"string","optional":false},{"name":"options","type":"TenantReadScopeOptions","optional":false},{"name":"callback","type":"Function","optional":false}],"returnType":"Promise<T>","isStatic":false,"isPublic":true},"createChild":{"name":"createChild","async":true,"parameters":[{"name":"parentTenantId","type":"string","optional":false},{"name":"options","type":"CreateChildTenantOptions","optional":false}],"returnType":"Promise<Tenant>","isStatic":false,"isPublic":true},"moveToParent":{"name":"moveToParent","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false},{"name":"newParentId","type":"string | null","optional":false,"unionBranches":[{"type":"string"},{"type":"null"}]}],"returnType":"Promise<Tenant>","isStatic":false,"isPublic":true},"makeRoot":{"name":"makeRoot","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Tenant>","isStatic":false,"isPublic":true},"validateHierarchy":{"name":"validateHierarchy","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<string[]>","isStatic":false,"isPublic":true},"getTree":{"name":"getTree","async":true,"parameters":[{"name":"rootTenantId","type":"string","optional":true}],"returnType":"any","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"Tenant","exportName":"TenantCollection","collectionExportName":"TenantCollectionCollection","schema":{"tableName":"tenants","ddl":"CREATE TABLE IF NOT EXISTS \\"tenants\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"_meta_type\\" TEXT NOT NULL,\\n \\"_meta_data\\" JSON,\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"name\\" TEXT DEFAULT '',\\n \\"status\\" TEXT,\\n \\"description\\" TEXT DEFAULT '',\\n \\"parent_tenant_id\\" UUID,\\n \\"hierarchy_level\\" INTEGER DEFAULT 0,\\n \\"hierarchy_path\\" TEXT DEFAULT '',\\n \\"cascade_permissions\\" BOOLEAN DEFAULT TRUE,\\n \\"inherit_permissions\\" BOOLEAN DEFAULT TRUE\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"_meta_type":{"type":"TEXT","notNull":true},"_meta_data":{"type":"JSON","notNull":false},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"name":{"type":"TEXT","notNull":false,"default":""},"status":{"type":"TEXT","notNull":false},"description":{"type":"TEXT","notNull":false,"default":""},"parent_tenant_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"foreignKey":{"table":"tenants","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"hierarchy_level":{"type":"INTEGER","notNull":false,"default":0},"hierarchy_path":{"type":"TEXT","notNull":false,"default":""},"cascade_permissions":{"type":"BOOLEAN","notNull":false,"default":true},"inherit_permissions":{"type":"BOOLEAN","notNull":false,"default":true}},"indexes":[{"name":"tenants_slug_context_meta_type_idx","columns":["slug","context","_meta_type"],"unique":true},{"name":"tenants_meta_type_idx","columns":["_meta_type"]},{"name":"tenants_created_at_idx","columns":["created_at"]},{"name":"tenants_parent_tenant_id_idx","columns":["parent_tenant_id"]}],"version":"934f7025"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:TenantIntegrationCollection":{"name":"tenantintegrationcollection","className":"TenantIntegrationCollection","qualifiedName":"@happyvertical/smrt-users:TenantIntegrationCollection","collection":"tenantintegrations","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/TenantIntegrationCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"listForTenant":{"name":"listForTenant","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<TenantIntegration[]>","isStatic":false,"isPublic":true},"findFor":{"name":"findFor","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false},{"name":"provider","type":"TenantIntegrationProvider","optional":false}],"returnType":"Promise<TenantIntegration | null>","isStatic":false,"isPublic":true},"findOrInit":{"name":"findOrInit","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false},{"name":"provider","type":"TenantIntegrationProvider","optional":false}],"returnType":"Promise<TenantIntegration>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"tenant_integrations","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"TenantIntegration","exportName":"TenantIntegrationCollection","collectionExportName":"TenantIntegrationCollectionCollection","schema":{"tableName":"tenant_integrations","ddl":"CREATE TABLE IF NOT EXISTS \\"tenant_integrations\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"provider\\" TEXT DEFAULT 'aws',\\n \\"external_ids\\" TEXT,\\n \\"status\\" TEXT DEFAULT 'unprovisioned',\\n \\"last_checked_at\\" TIMESTAMP,\\n \\"last_check_summary\\" TEXT,\\n \\"last_error\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"provider":{"type":"TEXT","notNull":false,"unique":false,"default":"aws"},"external_ids":{"type":"TEXT","notNull":false,"unique":false},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"unprovisioned"},"last_checked_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"last_check_summary":{"type":"TEXT","notNull":false,"unique":false},"last_error":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"tenant_integrations_tenant_id_provider_idx","columns":["tenant_id","provider"],"unique":true,"nullsNotDistinct":true},{"name":"tenant_integrations_slug_context_idx","columns":["slug","context"]},{"name":"tenant_integrations_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"3ed31966"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:TenantPermissionOverrideCollection":{"name":"tenantpermissionoverridecollection","className":"TenantPermissionOverrideCollection","qualifiedName":"@happyvertical/smrt-users:TenantPermissionOverrideCollection","collection":"tenantpermissionoverrides","description":"Collection for managing TenantPermissionOverride objects.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/TenantPermissionOverrideCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"findByTenant":{"name":"findByTenant","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<TenantPermissionOverride[]>","isStatic":false,"isPublic":true},"findGrants":{"name":"findGrants","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<TenantPermissionOverride[]>","isStatic":false,"isPublic":true},"findDenies":{"name":"findDenies","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<TenantPermissionOverride[]>","isStatic":false,"isPublic":true},"findInherits":{"name":"findInherits","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<TenantPermissionOverride[]>","isStatic":false,"isPublic":true},"getGrantedPermissionIds":{"name":"getGrantedPermissionIds","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<string[]>","isStatic":false,"isPublic":true},"getDeniedPermissionIds":{"name":"getDeniedPermissionIds","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<string[]>","isStatic":false,"isPublic":true},"getOverridesByEffect":{"name":"getOverridesByEffect","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<TenantPermissionOverrideResult>","isStatic":false,"isPublic":true},"getOverridesByEffectBatch":{"name":"getOverridesByEffectBatch","async":true,"parameters":[{"name":"tenantIds","type":"string[]","optional":false}],"returnType":"Promise<Map<string, TenantPermissionOverrideResult>>","isStatic":false,"isPublic":true},"setOverride":{"name":"setOverride","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false},{"name":"permissionId","type":"string","optional":false},{"name":"effect","type":"TenantPermissionEffect","optional":false}],"returnType":"Promise<TenantPermissionOverride>","isStatic":false,"isPublic":true},"removeOverride":{"name":"removeOverride","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false},{"name":"permissionId","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"removeAllOverrides":{"name":"removeAllOverrides","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<number>","isStatic":false,"isPublic":true},"grantPermission":{"name":"grantPermission","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false},{"name":"permissionId","type":"string","optional":false}],"returnType":"Promise<TenantPermissionOverride>","isStatic":false,"isPublic":true},"denyPermission":{"name":"denyPermission","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false},{"name":"permissionId","type":"string","optional":false}],"returnType":"Promise<TenantPermissionOverride>","isStatic":false,"isPublic":true},"inheritPermission":{"name":"inheritPermission","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false},{"name":"permissionId","type":"string","optional":false}],"returnType":"Promise<TenantPermissionOverride>","isStatic":false,"isPublic":true},"bulkSetOverrides":{"name":"bulkSetOverrides","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false},{"name":"overrides","type":"Array<object>","optional":false,"memberTypes":["string","TenantPermissionEffect"]}],"returnType":"Promise<TenantPermissionOverride[]>","isStatic":false,"isPublic":true},"copyOverrides":{"name":"copyOverrides","async":true,"parameters":[{"name":"fromTenantId","type":"string","optional":false},{"name":"toTenantId","type":"string","optional":false}],"returnType":"Promise<TenantPermissionOverride[]>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"TenantPermissionOverride","exportName":"TenantPermissionOverrideCollection","collectionExportName":"TenantPermissionOverrideCollectionCollection","schema":{"tableName":"tenant_permission_overrides","ddl":"CREATE TABLE IF NOT EXISTS \\"tenant_permission_overrides\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"permission_id\\" UUID NOT NULL,\\n \\"effect\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"tenants","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"permission_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"permissions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"effect":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"tenant_permission_overrides_tenant_id_permission_id_idx","columns":["tenant_id","permission_id"],"unique":true},{"name":"tenant_permission_overrides_slug_context_idx","columns":["slug","context"]},{"name":"tenant_permission_overrides_created_at_idx","columns":["created_at"]},{"name":"tenant_permission_overrides_permission_id_idx","columns":["permission_id"]}],"version":"95b78bdd"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UserCollection":{"name":"usercollection","className":"UserCollection","qualifiedName":"@happyvertical/smrt-users:UserCollection","collection":"users","description":"Collection for managing User objects","filePath":"/home/runner/work/smrt/smrt/packages/users/src/collections/UserCollection.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{"findByEmail":{"name":"findByEmail","async":true,"parameters":[{"name":"email","type":"string","optional":false}],"returnType":"Promise<User | null>","isStatic":false,"isPublic":true},"findByProfile":{"name":"findByProfile","async":true,"parameters":[{"name":"profileId","type":"string","optional":false}],"returnType":"Promise<User | null>","isStatic":false,"isPublic":true},"findByStatus":{"name":"findByStatus","async":true,"parameters":[{"name":"status","type":"UserStatus","optional":false}],"returnType":"Promise<User[]>","isStatic":false,"isPublic":true},"findActive":{"name":"findActive","async":true,"parameters":[],"returnType":"Promise<User[]>","isStatic":false,"isPublic":true},"findPending":{"name":"findPending","async":true,"parameters":[],"returnType":"Promise<User[]>","isStatic":false,"isPublic":true},"getOrCreateForProfile":{"name":"getOrCreateForProfile","async":true,"parameters":[{"name":"profileId","type":"string","optional":false},{"name":"email","type":"string","optional":false},{"name":"defaults","type":"Partial<object>","optional":true,"memberTypes":["UserStatus"]}],"returnType":"Promise<User>","isStatic":false,"isPublic":true},"getOrCreateFromOidc":{"name":"getOrCreateFromOidc","async":true,"parameters":[{"name":"claims","type":"OidcClaims","optional":false},{"name":"provider","type":"string","optional":false},{"name":"options","type":"GetOrCreateFromOidcOptions","optional":true}],"returnType":"Promise<OidcIdentityResult>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"User","exportName":"UserCollection","collectionExportName":"UserCollectionCollection","schema":{"tableName":"users","ddl":"CREATE TABLE IF NOT EXISTS \\"users\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"profile_id\\" UUID UNIQUE,\\n \\"email\\" TEXT DEFAULT '',\\n \\"email_key\\" TEXT UNIQUE,\\n \\"username\\" TEXT,\\n \\"username_key\\" TEXT UNIQUE,\\n \\"status\\" TEXT,\\n \\"last_login_at\\" TIMESTAMP\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":true},"email":{"type":"TEXT","notNull":false,"unique":false,"default":""},"email_key":{"type":"TEXT","notNull":false,"unique":true},"username":{"type":"TEXT","notNull":false,"unique":false},"username_key":{"type":"TEXT","notNull":false,"unique":true},"status":{"type":"TEXT","notNull":false,"unique":false},"last_login_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"users_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_email_idx","columns":["email"]},{"name":"users_username_idx","columns":["username"]},{"name":"users_created_at_idx","columns":["created_at"]}],"version":"3ee8f0f4"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:MemberClass":{"name":"memberclass","className":"MemberClass","qualifiedName":"@happyvertical/smrt-users:MemberClass","collection":"memberclasses","description":"A tenant-configured legal class; it has no authority or entitlement effect.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/member-register/models.ts","packageName":"@happyvertical/smrt-users","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"key":{"type":"text","required":false,"_meta":{}},"name":{"type":"text","required":false},"description":{"type":"text","required":false},"policyMetadata":{"type":"json","required":false,"_meta":{"nullable":true}}},"methods":{},"decoratorConfig":{"tableName":"member_classes","sensitive":true,"indexes":[{"name":"member_classes_tenant_key_uq","columns":["tenantId","key"],"unique":true}],"api":{"include":[]},"mcp":{"include":[]},"cli":false,"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"MemberClass","collectionExportName":"MemberClassCollection","displayLabelField":"name","validationRules":[],"schema":{"tableName":"member_classes","ddl":"CREATE TABLE IF NOT EXISTS \\"member_classes\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"key\\" TEXT,\\n \\"name\\" TEXT,\\n \\"description\\" TEXT,\\n \\"policy_metadata\\" JSON\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"key":{"type":"TEXT","notNull":false,"unique":false},"name":{"type":"TEXT","notNull":false,"unique":false},"description":{"type":"TEXT","notNull":false,"unique":false},"policy_metadata":{"type":"JSON","notNull":false,"unique":false}},"indexes":[{"name":"member_classes_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"member_classes_tenant_key_uq","columns":["tenant_id","key"],"unique":true},{"name":"member_classes_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"0fa7a152"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:LegalMember":{"name":"legalmember","className":"LegalMember","qualifiedName":"@happyvertical/smrt-users:LegalMember","collection":"legalmembers","description":"The legal register entry, deliberately separate from RBAC Membership.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/member-register/models.ts","packageName":"@happyvertical/smrt-users","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"memberClassId":{"type":"foreignKey","required":false,"related":"MemberClass","_meta":{"onDelete":"RESTRICT"}},"kind":{"type":"text","required":false,"_meta":{},"enum":["individual","organisation"]},"displayName":{"type":"text","required":false},"userId":{"type":"foreignKey","required":false,"related":"User","_meta":{"nullable":true,"onDelete":"RESTRICT"}},"profileId":{"type":"crossPackageRef","required":false,"related":"@happyvertical/smrt-profiles:Profile","_meta":{"nullable":true,"onDelete":"RESTRICT"}},"externalPartyRef":{"type":"text","required":false,"_meta":{"nullable":true}},"joinedOn":{"type":"text","required":false,"_meta":{}},"leftOn":{"type":"text","required":false,"_meta":{"nullable":true}},"status":{"type":"text","required":false,"_meta":{},"enum":["active","suspended","resigned","ceased"]}},"methods":{},"decoratorConfig":{"tableName":"legal_members","sensitive":true,"indexes":[{"name":"legal_members_tenant_class_status_idx","columns":["tenantId","memberClassId","status"]},{"name":"legal_members_tenant_user_idx","columns":["tenantId","userId"]}],"api":{"include":[]},"mcp":{"include":[]},"cli":false,"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"LegalMember","collectionExportName":"LegalMemberCollection","validationRules":[],"schema":{"tableName":"legal_members","ddl":"CREATE TABLE IF NOT EXISTS \\"legal_members\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"member_class_id\\" UUID,\\n \\"kind\\" TEXT,\\n \\"display_name\\" TEXT,\\n \\"user_id\\" UUID,\\n \\"profile_id\\" UUID,\\n \\"external_party_ref\\" TEXT,\\n \\"joined_on\\" TEXT,\\n \\"left_on\\" TEXT,\\n \\"status\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"member_class_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"member_classes","column":"id","onDelete":"RESTRICT","onUpdate":"CASCADE"}},"kind":{"type":"TEXT","notNull":false,"unique":false},"display_name":{"type":"TEXT","notNull":false,"unique":false},"user_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"users","column":"id","onDelete":"RESTRICT","onUpdate":"CASCADE"}},"profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"external_party_ref":{"type":"TEXT","notNull":false,"unique":false},"joined_on":{"type":"TEXT","notNull":false,"unique":false},"left_on":{"type":"TEXT","notNull":false,"unique":false},"status":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"legal_members_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"legal_members_tenant_class_status_idx","columns":["tenant_id","member_class_id","status"]},{"name":"legal_members_tenant_user_idx","columns":["tenant_id","user_id"]},{"name":"legal_members_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"legal_members_member_class_id_idx","columns":["member_class_id"]},{"name":"legal_members_user_id_idx","columns":["user_id"]},{"name":"legal_members_profile_id_idx","columns":["profile_id"]}],"version":"b05fd9f3"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:LegalMemberStatusHistory":{"name":"legalmemberstatushistory","className":"LegalMemberStatusHistory","qualifiedName":"@happyvertical/smrt-users:LegalMemberStatusHistory","collection":"legalmemberstatushistories","description":"Append-only effective history; current status never erases it.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/member-register/models.ts","packageName":"@happyvertical/smrt-users","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"memberId":{"type":"foreignKey","required":false,"related":"LegalMember","_meta":{"onDelete":"RESTRICT"}},"status":{"type":"text","required":false,"_meta":{},"enum":["active","suspended","resigned","ceased"]},"effectiveOn":{"type":"text","required":false,"_meta":{}},"sequence":{"type":"integer","required":false,"_meta":{}},"reason":{"type":"text","required":false},"actorRef":{"type":"text","required":false,"_meta":{"nullable":true}}},"methods":{"save":{"name":"save","async":true,"parameters":[],"returnType":"Promise<this>","isStatic":false,"isPublic":true},"delete":{"name":"delete","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"legal_member_status_history","sensitive":true,"indexes":[{"name":"legal_member_status_history_member_on_idx","columns":["tenantId","memberId","effectiveOn"]}],"api":{"include":[]},"mcp":{"include":[]},"cli":false,"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"LegalMemberStatusHistory","collectionExportName":"LegalMemberStatusHistoryCollection","validationRules":[],"schema":{"tableName":"legal_member_status_history","ddl":"CREATE TABLE IF NOT EXISTS \\"legal_member_status_history\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"member_id\\" UUID,\\n \\"status\\" TEXT,\\n \\"effective_on\\" TEXT,\\n \\"sequence\\" INTEGER,\\n \\"reason\\" TEXT,\\n \\"actor_ref\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"member_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"legal_members","column":"id","onDelete":"RESTRICT","onUpdate":"CASCADE"}},"status":{"type":"TEXT","notNull":false,"unique":false},"effective_on":{"type":"TEXT","notNull":false,"unique":false},"sequence":{"type":"INTEGER","notNull":false,"unique":false},"reason":{"type":"TEXT","notNull":false,"unique":false},"actor_ref":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"legal_member_status_history_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"legal_member_status_history_member_on_idx","columns":["tenant_id","member_id","effective_on"]},{"name":"legal_member_status_history_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"legal_member_status_history_member_id_idx","columns":["member_id"]}],"version":"3885f61f"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:LegalMemberReference":{"name":"legalmemberreference","className":"LegalMemberReference","qualifiedName":"@happyvertical/smrt-users:LegalMemberReference","collection":"legalmemberreferences","description":"A link to authoritative share/dues/subscription/agreement/ledger evidence.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/member-register/models.ts","packageName":"@happyvertical/smrt-users","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"memberId":{"type":"foreignKey","required":false,"related":"LegalMember","_meta":{"onDelete":"RESTRICT"}},"kind":{"type":"text","required":false,"_meta":{},"enum":["share","dues","subscription","agreement","ledger"]},"sourceType":{"type":"text","required":false},"sourceId":{"type":"text","required":false},"authoritative":{"type":"boolean","required":false,"_meta":{}},"effectiveFrom":{"type":"text","required":false,"_meta":{}},"effectiveTo":{"type":"text","required":false,"_meta":{"nullable":true}},"revokesId":{"type":"foreignKey","required":false,"related":"LegalMemberReference","_meta":{"nullable":true,"onDelete":"RESTRICT"}}},"methods":{"save":{"name":"save","async":true,"parameters":[],"returnType":"Promise<this>","isStatic":false,"isPublic":true},"delete":{"name":"delete","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"legal_member_references","sensitive":true,"indexes":[{"name":"legal_member_references_member_kind_idx","columns":["tenantId","memberId","kind"]}],"api":{"include":[]},"mcp":{"include":[]},"cli":false,"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"LegalMemberReference","collectionExportName":"LegalMemberReferenceCollection","validationRules":[],"schema":{"tableName":"legal_member_references","ddl":"CREATE TABLE IF NOT EXISTS \\"legal_member_references\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"member_id\\" UUID,\\n \\"kind\\" TEXT,\\n \\"source_type\\" TEXT,\\n \\"source_id\\" TEXT,\\n \\"authoritative\\" BOOLEAN,\\n \\"effective_from\\" TEXT,\\n \\"effective_to\\" TEXT,\\n \\"revokes_id\\" UUID\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"member_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"legal_members","column":"id","onDelete":"RESTRICT","onUpdate":"CASCADE"}},"kind":{"type":"TEXT","notNull":false,"unique":false},"source_type":{"type":"TEXT","notNull":false,"unique":false},"source_id":{"type":"TEXT","notNull":false,"unique":false},"authoritative":{"type":"BOOLEAN","notNull":false,"unique":false},"effective_from":{"type":"TEXT","notNull":false,"unique":false},"effective_to":{"type":"TEXT","notNull":false,"unique":false},"revokes_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"legal_member_references","column":"id","onDelete":"RESTRICT","onUpdate":"CASCADE"}}},"indexes":[{"name":"legal_member_references_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"legal_member_references_member_kind_idx","columns":["tenant_id","member_id","kind"]},{"name":"legal_member_references_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"legal_member_references_member_id_idx","columns":["member_id"]},{"name":"legal_member_references_revokes_id_idx","columns":["revokes_id"]}],"version":"30237bd4"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:MemberOfficerAppointment":{"name":"memberofficerappointment","className":"MemberOfficerAppointment","qualifiedName":"@happyvertical/smrt-users:MemberOfficerAppointment","collection":"memberofficerappointments","description":"A dated register of board/officer appointments; it does not implement elections.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/member-register/models.ts","packageName":"@happyvertical/smrt-users","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"memberId":{"type":"foreignKey","required":false,"related":"LegalMember","_meta":{"onDelete":"RESTRICT"}},"role":{"type":"text","required":false,"_meta":{}},"effectiveFrom":{"type":"text","required":false,"_meta":{}},"effectiveTo":{"type":"text","required":false,"_meta":{"nullable":true}},"authority":{"type":"json","required":false,"_meta":{"nullable":true}}},"methods":{},"decoratorConfig":{"tableName":"member_officer_appointments","sensitive":true,"indexes":[{"name":"member_officer_appointments_member_term_idx","columns":["tenantId","memberId","effectiveFrom"]}],"api":{"include":[]},"mcp":{"include":[]},"cli":false,"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"MemberOfficerAppointment","collectionExportName":"MemberOfficerAppointmentCollection","validationRules":[],"schema":{"tableName":"member_officer_appointments","ddl":"CREATE TABLE IF NOT EXISTS \\"member_officer_appointments\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"member_id\\" UUID,\\n \\"role\\" TEXT,\\n \\"effective_from\\" TEXT,\\n \\"effective_to\\" TEXT,\\n \\"authority\\" JSON\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"member_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"legal_members","column":"id","onDelete":"RESTRICT","onUpdate":"CASCADE"}},"role":{"type":"TEXT","notNull":false,"unique":false},"effective_from":{"type":"TEXT","notNull":false,"unique":false},"effective_to":{"type":"TEXT","notNull":false,"unique":false},"authority":{"type":"JSON","notNull":false,"unique":false}},"indexes":[{"name":"member_officer_appointments_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"member_officer_appointments_member_term_idx","columns":["tenant_id","member_id","effective_from"]},{"name":"member_officer_appointments_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"member_officer_appointments_member_id_idx","columns":["member_id"]}],"version":"eed54759"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:MemberEligibilitySnapshot":{"name":"membereligibilitysnapshot","className":"MemberEligibilitySnapshot","qualifiedName":"@happyvertical/smrt-users:MemberEligibilitySnapshot","collection":"membereligibilitysnapshots","filePath":"/home/runner/work/smrt/smrt/packages/users/src/member-register/models.ts","packageName":"@happyvertical/smrt-users","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"memberId":{"type":"foreignKey","required":false,"related":"LegalMember","_meta":{"onDelete":"RESTRICT"}},"recordDate":{"type":"text","required":false,"_meta":{}},"eligible":{"type":"boolean","required":false,"_meta":{}},"reason":{"type":"text","required":false},"evidence":{"type":"json","required":false,"_meta":{"nullable":true}}},"methods":{"save":{"name":"save","async":true,"parameters":[],"returnType":"Promise<this>","isStatic":false,"isPublic":true},"delete":{"name":"delete","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"member_eligibility_snapshots","sensitive":true,"indexes":[{"name":"member_eligibility_snapshots_tenant_date_idx","columns":["tenantId","recordDate"]}],"api":{"include":[]},"mcp":{"include":[]},"cli":false,"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"MemberEligibilitySnapshot","collectionExportName":"MemberEligibilitySnapshotCollection","validationRules":[],"schema":{"tableName":"member_eligibility_snapshots","ddl":"CREATE TABLE IF NOT EXISTS \\"member_eligibility_snapshots\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"member_id\\" UUID,\\n \\"record_date\\" TEXT,\\n \\"eligible\\" BOOLEAN,\\n \\"reason\\" TEXT,\\n \\"evidence\\" JSON\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"member_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"legal_members","column":"id","onDelete":"RESTRICT","onUpdate":"CASCADE"}},"record_date":{"type":"TEXT","notNull":false,"unique":false},"eligible":{"type":"BOOLEAN","notNull":false,"unique":false},"reason":{"type":"TEXT","notNull":false,"unique":false},"evidence":{"type":"JSON","notNull":false,"unique":false}},"indexes":[{"name":"member_eligibility_snapshots_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"member_eligibility_snapshots_tenant_date_idx","columns":["tenant_id","record_date"]},{"name":"member_eligibility_snapshots_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"member_eligibility_snapshots_member_id_idx","columns":["member_id"]}],"version":"f3899c14"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:MemberClassCollection":{"name":"memberclasscollection","className":"MemberClassCollection","qualifiedName":"@happyvertical/smrt-users:MemberClassCollection","collection":"memberclasses","filePath":"/home/runner/work/smrt/smrt/packages/users/src/member-register/models.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{},"decoratorConfig":{"api":{"include":[]},"mcp":{"include":[]},"cli":false,"tableName":"member_classes"},"extends":"SmrtCollection","extendsTypeArg":"MemberClass","exportName":"MemberClassCollection","collectionExportName":"MemberClassCollectionCollection","schema":{"tableName":"member_classes","ddl":"CREATE TABLE IF NOT EXISTS \\"member_classes\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"key\\" TEXT,\\n \\"name\\" TEXT,\\n \\"description\\" TEXT,\\n \\"policy_metadata\\" JSON\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"key":{"type":"TEXT","notNull":false,"unique":false},"name":{"type":"TEXT","notNull":false,"unique":false},"description":{"type":"TEXT","notNull":false,"unique":false},"policy_metadata":{"type":"JSON","notNull":false,"unique":false}},"indexes":[{"name":"member_classes_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"member_classes_tenant_key_uq","columns":["tenant_id","key"],"unique":true},{"name":"member_classes_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"0fa7a152"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:LegalMemberCollection":{"name":"legalmembercollection","className":"LegalMemberCollection","qualifiedName":"@happyvertical/smrt-users:LegalMemberCollection","collection":"legalmembers","filePath":"/home/runner/work/smrt/smrt/packages/users/src/member-register/models.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{},"decoratorConfig":{"api":{"include":[]},"mcp":{"include":[]},"cli":false,"tableName":"legal_members"},"extends":"SmrtCollection","extendsTypeArg":"LegalMember","exportName":"LegalMemberCollection","collectionExportName":"LegalMemberCollectionCollection","schema":{"tableName":"legal_members","ddl":"CREATE TABLE IF NOT EXISTS \\"legal_members\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"member_class_id\\" UUID,\\n \\"kind\\" TEXT,\\n \\"display_name\\" TEXT,\\n \\"user_id\\" UUID,\\n \\"profile_id\\" UUID,\\n \\"external_party_ref\\" TEXT,\\n \\"joined_on\\" TEXT,\\n \\"left_on\\" TEXT,\\n \\"status\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"member_class_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"member_classes","column":"id","onDelete":"RESTRICT","onUpdate":"CASCADE"}},"kind":{"type":"TEXT","notNull":false,"unique":false},"display_name":{"type":"TEXT","notNull":false,"unique":false},"user_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"users","column":"id","onDelete":"RESTRICT","onUpdate":"CASCADE"}},"profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"external_party_ref":{"type":"TEXT","notNull":false,"unique":false},"joined_on":{"type":"TEXT","notNull":false,"unique":false},"left_on":{"type":"TEXT","notNull":false,"unique":false},"status":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"legal_members_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"legal_members_tenant_class_status_idx","columns":["tenant_id","member_class_id","status"]},{"name":"legal_members_tenant_user_idx","columns":["tenant_id","user_id"]},{"name":"legal_members_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"legal_members_member_class_id_idx","columns":["member_class_id"]},{"name":"legal_members_user_id_idx","columns":["user_id"]},{"name":"legal_members_profile_id_idx","columns":["profile_id"]}],"version":"b05fd9f3"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:LegalMemberStatusHistoryCollection":{"name":"legalmemberstatushistorycollection","className":"LegalMemberStatusHistoryCollection","qualifiedName":"@happyvertical/smrt-users:LegalMemberStatusHistoryCollection","collection":"legalmemberstatushistories","filePath":"/home/runner/work/smrt/smrt/packages/users/src/member-register/models.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{},"decoratorConfig":{"api":{"include":[]},"mcp":{"include":[]},"cli":false,"tableName":"legal_member_status_history"},"extends":"SmrtCollection","extendsTypeArg":"LegalMemberStatusHistory","exportName":"LegalMemberStatusHistoryCollection","collectionExportName":"LegalMemberStatusHistoryCollectionCollection","schema":{"tableName":"legal_member_status_history","ddl":"CREATE TABLE IF NOT EXISTS \\"legal_member_status_history\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"member_id\\" UUID,\\n \\"status\\" TEXT,\\n \\"effective_on\\" TEXT,\\n \\"sequence\\" INTEGER,\\n \\"reason\\" TEXT,\\n \\"actor_ref\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"member_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"legal_members","column":"id","onDelete":"RESTRICT","onUpdate":"CASCADE"}},"status":{"type":"TEXT","notNull":false,"unique":false},"effective_on":{"type":"TEXT","notNull":false,"unique":false},"sequence":{"type":"INTEGER","notNull":false,"unique":false},"reason":{"type":"TEXT","notNull":false,"unique":false},"actor_ref":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"legal_member_status_history_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"legal_member_status_history_member_on_idx","columns":["tenant_id","member_id","effective_on"]},{"name":"legal_member_status_history_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"legal_member_status_history_member_id_idx","columns":["member_id"]}],"version":"3885f61f"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:LegalMemberReferenceCollection":{"name":"legalmemberreferencecollection","className":"LegalMemberReferenceCollection","qualifiedName":"@happyvertical/smrt-users:LegalMemberReferenceCollection","collection":"legalmemberreferences","filePath":"/home/runner/work/smrt/smrt/packages/users/src/member-register/models.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{},"decoratorConfig":{"api":{"include":[]},"mcp":{"include":[]},"cli":false,"tableName":"legal_member_references"},"extends":"SmrtCollection","extendsTypeArg":"LegalMemberReference","exportName":"LegalMemberReferenceCollection","collectionExportName":"LegalMemberReferenceCollectionCollection","schema":{"tableName":"legal_member_references","ddl":"CREATE TABLE IF NOT EXISTS \\"legal_member_references\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"member_id\\" UUID,\\n \\"kind\\" TEXT,\\n \\"source_type\\" TEXT,\\n \\"source_id\\" TEXT,\\n \\"authoritative\\" BOOLEAN,\\n \\"effective_from\\" TEXT,\\n \\"effective_to\\" TEXT,\\n \\"revokes_id\\" UUID\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"member_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"legal_members","column":"id","onDelete":"RESTRICT","onUpdate":"CASCADE"}},"kind":{"type":"TEXT","notNull":false,"unique":false},"source_type":{"type":"TEXT","notNull":false,"unique":false},"source_id":{"type":"TEXT","notNull":false,"unique":false},"authoritative":{"type":"BOOLEAN","notNull":false,"unique":false},"effective_from":{"type":"TEXT","notNull":false,"unique":false},"effective_to":{"type":"TEXT","notNull":false,"unique":false},"revokes_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"legal_member_references","column":"id","onDelete":"RESTRICT","onUpdate":"CASCADE"}}},"indexes":[{"name":"legal_member_references_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"legal_member_references_member_kind_idx","columns":["tenant_id","member_id","kind"]},{"name":"legal_member_references_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"legal_member_references_member_id_idx","columns":["member_id"]},{"name":"legal_member_references_revokes_id_idx","columns":["revokes_id"]}],"version":"30237bd4"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:MemberOfficerAppointmentCollection":{"name":"memberofficerappointmentcollection","className":"MemberOfficerAppointmentCollection","qualifiedName":"@happyvertical/smrt-users:MemberOfficerAppointmentCollection","collection":"memberofficerappointments","filePath":"/home/runner/work/smrt/smrt/packages/users/src/member-register/models.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{},"decoratorConfig":{"api":{"include":[]},"mcp":{"include":[]},"cli":false,"tableName":"member_officer_appointments"},"extends":"SmrtCollection","extendsTypeArg":"MemberOfficerAppointment","exportName":"MemberOfficerAppointmentCollection","collectionExportName":"MemberOfficerAppointmentCollectionCollection","schema":{"tableName":"member_officer_appointments","ddl":"CREATE TABLE IF NOT EXISTS \\"member_officer_appointments\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"member_id\\" UUID,\\n \\"role\\" TEXT,\\n \\"effective_from\\" TEXT,\\n \\"effective_to\\" TEXT,\\n \\"authority\\" JSON\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"member_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"legal_members","column":"id","onDelete":"RESTRICT","onUpdate":"CASCADE"}},"role":{"type":"TEXT","notNull":false,"unique":false},"effective_from":{"type":"TEXT","notNull":false,"unique":false},"effective_to":{"type":"TEXT","notNull":false,"unique":false},"authority":{"type":"JSON","notNull":false,"unique":false}},"indexes":[{"name":"member_officer_appointments_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"member_officer_appointments_member_term_idx","columns":["tenant_id","member_id","effective_from"]},{"name":"member_officer_appointments_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"member_officer_appointments_member_id_idx","columns":["member_id"]}],"version":"eed54759"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:MemberEligibilitySnapshotCollection":{"name":"membereligibilitysnapshotcollection","className":"MemberEligibilitySnapshotCollection","qualifiedName":"@happyvertical/smrt-users:MemberEligibilitySnapshotCollection","collection":"membereligibilitysnapshots","filePath":"/home/runner/work/smrt/smrt/packages/users/src/member-register/models.ts","packageName":"@happyvertical/smrt-users","fields":{},"methods":{},"decoratorConfig":{"api":{"include":[]},"mcp":{"include":[]},"cli":false,"tableName":"member_eligibility_snapshots"},"extends":"SmrtCollection","extendsTypeArg":"MemberEligibilitySnapshot","exportName":"MemberEligibilitySnapshotCollection","collectionExportName":"MemberEligibilitySnapshotCollectionCollection","schema":{"tableName":"member_eligibility_snapshots","ddl":"CREATE TABLE IF NOT EXISTS \\"member_eligibility_snapshots\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"member_id\\" UUID,\\n \\"record_date\\" TEXT,\\n \\"eligible\\" BOOLEAN,\\n \\"reason\\" TEXT,\\n \\"evidence\\" JSON\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"member_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"legal_members","column":"id","onDelete":"RESTRICT","onUpdate":"CASCADE"}},"record_date":{"type":"TEXT","notNull":false,"unique":false},"eligible":{"type":"BOOLEAN","notNull":false,"unique":false},"reason":{"type":"TEXT","notNull":false,"unique":false},"evidence":{"type":"JSON","notNull":false,"unique":false}},"indexes":[{"name":"member_eligibility_snapshots_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"member_eligibility_snapshots_tenant_date_idx","columns":["tenant_id","record_date"]},{"name":"member_eligibility_snapshots_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"member_eligibility_snapshots_member_id_idx","columns":["member_id"]}],"version":"f3899c14"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:AccessRequest":{"name":"accessrequest","className":"AccessRequest","qualifiedName":"@happyvertical/smrt-users:AccessRequest","collection":"accessrequests","description":"A prospective user's request for access, captured before they become a User.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/AccessRequest.ts","packageName":"@happyvertical/smrt-users","fields":{"email":{"type":"text","required":true,"default":"","_meta":{"required":true,"indexed":true}},"name":{"type":"text","required":false,"_meta":{"nullable":true}},"status":{"type":"text","required":false,"_meta":{"indexed":true}},"source":{"type":"text","required":false,"default":"","_meta":{"indexed":true}},"requestContext":{"type":"text","required":false,"default":"{}"},"note":{"type":"text","required":false,"_meta":{"nullable":true}},"requestedAt":{"type":"datetime","required":false},"decidedAt":{"type":"datetime","required":false,"_meta":{"nullable":true}},"decidedBy":{"type":"text","required":false,"_meta":{"nullable":true}},"resultingUserId":{"type":"text","required":false,"_meta":{"nullable":true}},"tenantHint":{"type":"text","required":false,"_meta":{"nullable":true}}},"methods":{"getRequestContext":{"name":"getRequestContext","async":false,"parameters":[],"returnType":"Record<string, unknown>","isStatic":false,"isPublic":true},"setRequestContext":{"name":"setRequestContext","async":false,"parameters":[{"name":"value","type":"Record<string, unknown>","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"getTenantHint":{"name":"getTenantHint","async":false,"parameters":[],"returnType":"Record<string, unknown> | null","isStatic":false,"isPublic":true},"setTenantHint":{"name":"setTenantHint","async":false,"parameters":[{"name":"value","type":"Record<string, unknown> | null","optional":false,"unionBranches":[{"type":"Record<string, unknown>"},{"type":"null"}]}],"returnType":"void","isStatic":false,"isPublic":true},"isOpen":{"name":"isOpen","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isApproved":{"name":"isApproved","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isTerminal":{"name":"isTerminal","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"access_requests","conflictColumns":["id"],"api":{"include":[]},"mcp":{"include":[]},"cli":false},"extends":"SmrtObject","exportName":"AccessRequest","collectionExportName":"AccessRequestCollection","displayLabelField":"name","validationRules":[{"field":"email","rule":"required","fieldType":"text"}],"schema":{"tableName":"access_requests","ddl":"CREATE TABLE IF NOT EXISTS \\"access_requests\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"email\\" TEXT NOT NULL DEFAULT '',\\n \\"name\\" TEXT,\\n \\"status\\" TEXT,\\n \\"source\\" TEXT DEFAULT '',\\n \\"request_context\\" TEXT DEFAULT '{}',\\n \\"note\\" TEXT,\\n \\"requested_at\\" TIMESTAMP,\\n \\"decided_at\\" TIMESTAMP,\\n \\"decided_by\\" TEXT,\\n \\"resulting_user_id\\" TEXT,\\n \\"tenant_hint\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"email":{"type":"TEXT","notNull":true,"unique":false,"default":""},"name":{"type":"TEXT","notNull":false,"unique":false},"status":{"type":"TEXT","notNull":false,"unique":false},"source":{"type":"TEXT","notNull":false,"unique":false,"default":""},"request_context":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"note":{"type":"TEXT","notNull":false,"unique":false},"requested_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"decided_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"decided_by":{"type":"TEXT","notNull":false,"unique":false},"resulting_user_id":{"type":"TEXT","notNull":false,"unique":false},"tenant_hint":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"access_requests_slug_context_idx","columns":["slug","context"]},{"name":"access_requests_email_idx","columns":["email"]},{"name":"access_requests_status_idx","columns":["status"]},{"name":"access_requests_source_idx","columns":["source"]},{"name":"access_requests_created_at_idx","columns":["created_at"]}],"version":"f396996f"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersCliAuthApproveLimit":{"name":"userscliauthapprovelimit","className":"UsersCliAuthApproveLimit","qualifiedName":"@happyvertical/smrt-users:UsersCliAuthApproveLimit","collection":"userscliauthapprovelimits","description":"Private database arbiter shared by every terminal-auth process.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/CliAuthApproveLimit.ts","packageName":"@happyvertical/smrt-users","fields":{"userId":{"type":"foreignKey","required":true,"related":"User","_meta":{"required":true,"unique":true}},"attemptCount":{"type":"integer","required":true,"default":0,"_meta":{"required":true,"default":0}},"windowStartedAt":{"type":"datetime","required":true,"_meta":{"required":true}}},"methods":{},"decoratorConfig":{"tableName":"users_cli_auth_approve_limits","api":false,"cli":false,"mcp":false},"extends":"SmrtObject","exportName":"UsersCliAuthApproveLimit","collectionExportName":"UsersCliAuthApproveLimitCollection","validationRules":[{"field":"userId","rule":"required","fieldType":"foreignKey"},{"field":"attemptCount","rule":"required","fieldType":"integer"},{"field":"windowStartedAt","rule":"required","fieldType":"datetime"}],"schema":{"tableName":"users_cli_auth_approve_limits","ddl":"CREATE TABLE IF NOT EXISTS \\"users_cli_auth_approve_limits\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"user_id\\" UUID NOT NULL UNIQUE,\\n \\"attempt_count\\" INTEGER NOT NULL DEFAULT 0,\\n \\"window_started_at\\" TIMESTAMP NOT NULL\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"user_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":true,"foreignKey":{"table":"users","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"attempt_count":{"type":"INTEGER","notNull":true,"unique":false,"default":0},"window_started_at":{"type":"TIMESTAMP","notNull":true,"unique":false}},"indexes":[{"name":"users_cli_auth_approve_limits_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_cli_auth_approve_limits_created_at_idx","columns":["created_at"]}],"version":"c45c02de"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersCliAuthRequest":{"name":"userscliauthrequest","className":"UsersCliAuthRequest","qualifiedName":"@happyvertical/smrt-users:UsersCliAuthRequest","collection":"userscliauthrequests","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/CliAuthRequest.ts","packageName":"@happyvertical/smrt-users","fields":{"userCode":{"type":"text","required":true,"_meta":{"required":true,"unique":true}},"deviceCodeHash":{"type":"text","required":true,"_meta":{"required":true,"unique":true}},"status":{"type":"text","required":false,"_meta":{},"enum":["pending","approved","consumed","expired"]},"userId":{"type":"foreignKey","required":false,"related":"User","_meta":{"nullable":true}},"tenantId":{"type":"foreignKey","required":false,"related":"Tenant","_meta":{"nullable":true}},"sessionId":{"type":"foreignKey","required":false,"related":"Session","_meta":{"nullable":true}},"expiresAt":{"type":"datetime","required":false,"_meta":{"indexed":true}},"approvedAt":{"type":"datetime","required":false,"_meta":{"nullable":true}}},"methods":{},"decoratorConfig":{"tableName":"users_cli_auth_requests","sensitive":true,"api":{"include":[]},"cli":false,"mcp":{"include":[]},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"UsersCliAuthRequest","collectionExportName":"UsersCliAuthRequestCollection","validationRules":[{"field":"userCode","rule":"required","fieldType":"text"},{"field":"deviceCodeHash","rule":"required","fieldType":"text"}],"schema":{"tableName":"users_cli_auth_requests","ddl":"CREATE TABLE IF NOT EXISTS \\"users_cli_auth_requests\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"user_code\\" TEXT NOT NULL UNIQUE,\\n \\"device_code_hash\\" TEXT NOT NULL UNIQUE,\\n \\"status\\" TEXT,\\n \\"user_id\\" UUID,\\n \\"tenant_id\\" UUID,\\n \\"session_id\\" UUID,\\n \\"expires_at\\" TIMESTAMP,\\n \\"approved_at\\" TIMESTAMP\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"user_code":{"type":"TEXT","notNull":true,"unique":true},"device_code_hash":{"type":"TEXT","notNull":true,"unique":true},"status":{"type":"TEXT","notNull":false,"unique":false},"user_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"users","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"tenant_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"tenants","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"session_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"sessions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"approved_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"users_cli_auth_requests_tenant_id_slug_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"users_cli_auth_requests_expires_at_idx","columns":["expires_at"]},{"name":"users_cli_auth_requests_created_at_idx","columns":["created_at"]},{"name":"users_cli_auth_requests_user_id_idx","columns":["user_id"]},{"name":"users_cli_auth_requests_session_id_idx","columns":["session_id"]}],"version":"713ae04c"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:Group":{"name":"group","className":"Group","qualifiedName":"@happyvertical/smrt-users:Group","collection":"groups","description":"Group represents a team or department within a tenant.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/Group.ts","packageName":"@happyvertical/smrt-users","fields":{"tenantId":{"type":"foreignKey","required":true,"related":"Tenant","_meta":{"required":true}},"name":{"type":"text","required":false,"default":""},"description":{"type":"text","required":false,"default":""}},"methods":{},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"Group","collectionExportName":"GroupCollection","displayLabelField":"name","validationRules":[{"field":"tenantId","rule":"required","fieldType":"foreignKey"}],"schema":{"tableName":"groups","ddl":"CREATE TABLE IF NOT EXISTS \\"groups\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"name\\" TEXT DEFAULT '',\\n \\"description\\" TEXT DEFAULT ''\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"tenants","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"description":{"type":"TEXT","notNull":false,"unique":false,"default":""}},"indexes":[{"name":"groups_tenant_id_slug_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"groups_created_at_idx","columns":["created_at"]}],"version":"1824c19b"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:GroupMember":{"name":"groupmember","className":"GroupMember","qualifiedName":"@happyvertical/smrt-users:GroupMember","collection":"groupmembers","description":"GroupMember is a join table linking Users to Groups.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/GroupMember.ts","packageName":"@happyvertical/smrt-users","fields":{"groupId":{"type":"foreignKey","required":true,"related":"Group","_meta":{"required":true,"onDelete":"NO ACTION"}},"userId":{"type":"foreignKey","required":true,"related":"User","_meta":{"required":true,"onDelete":"NO ACTION"}}},"methods":{},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]},"conflictColumns":["group_id","user_id"]},"extends":"SmrtObject","exportName":"GroupMember","collectionExportName":"GroupMemberCollection","validationRules":[{"field":"groupId","rule":"required","fieldType":"foreignKey"},{"field":"userId","rule":"required","fieldType":"foreignKey"}],"schema":{"tableName":"group_members","ddl":"CREATE TABLE IF NOT EXISTS \\"group_members\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"group_id\\" UUID NOT NULL,\\n \\"user_id\\" UUID NOT NULL\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"group_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"groups","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"user_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"users","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}}},"indexes":[{"name":"group_members_group_id_user_id_idx","columns":["group_id","user_id"],"unique":true},{"name":"group_members_slug_context_idx","columns":["slug","context"]},{"name":"group_members_created_at_idx","columns":["created_at"]},{"name":"group_members_user_id_idx","columns":["user_id"]}],"version":"ed4d1187"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:GroupRole":{"name":"grouprole","className":"GroupRole","qualifiedName":"@happyvertical/smrt-users:GroupRole","collection":"grouproles","description":"GroupRole is a join table linking Groups to Roles.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/GroupRole.ts","packageName":"@happyvertical/smrt-users","fields":{"groupId":{"type":"foreignKey","required":true,"related":"Group","_meta":{"required":true}},"roleId":{"type":"foreignKey","required":true,"related":"Role","_meta":{"required":true}}},"methods":{},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtObject","exportName":"GroupRole","collectionExportName":"GroupRoleCollection","validationRules":[{"field":"groupId","rule":"required","fieldType":"foreignKey"},{"field":"roleId","rule":"required","fieldType":"foreignKey"}],"schema":{"tableName":"group_roles","ddl":"CREATE TABLE IF NOT EXISTS \\"group_roles\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"group_id\\" UUID NOT NULL,\\n \\"role_id\\" UUID NOT NULL\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"group_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"groups","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"role_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"roles","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}}},"indexes":[{"name":"group_roles_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"group_roles_created_at_idx","columns":["created_at"]},{"name":"group_roles_group_id_idx","columns":["group_id"]},{"name":"group_roles_role_id_idx","columns":["role_id"]}],"version":"b1e35f93"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersLoginAttempt":{"name":"usersloginattempt","className":"UsersLoginAttempt","qualifiedName":"@happyvertical/smrt-users:UsersLoginAttempt","collection":"usersloginattempts","description":"Private database arbiter shared by every process that authenticates.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/LoginAttempt.ts","packageName":"@happyvertical/smrt-users","fields":{"limiterKey":{"type":"text","required":true,"_meta":{"required":true,"unique":true}},"scope":{"type":"text","required":true,"_meta":{"required":true},"enum":["subject","source"]},"attemptCount":{"type":"integer","required":true,"default":0,"_meta":{"required":true,"default":0}},"windowStartedAt":{"type":"datetime","required":true,"_meta":{"required":true}},"failureStreak":{"type":"integer","required":true,"default":0,"_meta":{"required":true,"default":0}},"lockedUntil":{"type":"datetime","required":false,"_meta":{"nullable":true,"indexed":true}},"lastFailedAt":{"type":"datetime","required":false,"_meta":{"nullable":true}},"retainUntil":{"type":"datetime","required":true,"_meta":{"required":true,"indexed":true}}},"methods":{},"decoratorConfig":{"tableName":"users_login_attempts","sensitive":true,"api":false,"cli":false,"mcp":false},"extends":"SmrtObject","exportName":"UsersLoginAttempt","collectionExportName":"UsersLoginAttemptCollection","validationRules":[{"field":"limiterKey","rule":"required","fieldType":"text"},{"field":"scope","rule":"required","fieldType":"text"},{"field":"attemptCount","rule":"required","fieldType":"integer"},{"field":"windowStartedAt","rule":"required","fieldType":"datetime"},{"field":"failureStreak","rule":"required","fieldType":"integer"},{"field":"retainUntil","rule":"required","fieldType":"datetime"}],"schema":{"tableName":"users_login_attempts","ddl":"CREATE TABLE IF NOT EXISTS \\"users_login_attempts\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"limiter_key\\" TEXT NOT NULL UNIQUE,\\n \\"scope\\" TEXT NOT NULL,\\n \\"attempt_count\\" INTEGER NOT NULL DEFAULT 0,\\n \\"window_started_at\\" TIMESTAMP NOT NULL,\\n \\"failure_streak\\" INTEGER NOT NULL DEFAULT 0,\\n \\"locked_until\\" TIMESTAMP,\\n \\"last_failed_at\\" TIMESTAMP,\\n \\"retain_until\\" TIMESTAMP NOT NULL\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"limiter_key":{"type":"TEXT","notNull":true,"unique":true},"scope":{"type":"TEXT","notNull":true,"unique":false},"attempt_count":{"type":"INTEGER","notNull":true,"unique":false,"default":0},"window_started_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"failure_streak":{"type":"INTEGER","notNull":true,"unique":false,"default":0},"locked_until":{"type":"TIMESTAMP","notNull":false,"unique":false},"last_failed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"retain_until":{"type":"TIMESTAMP","notNull":true,"unique":false}},"indexes":[{"name":"users_login_attempts_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_login_attempts_locked_until_idx","columns":["locked_until"]},{"name":"users_login_attempts_retain_until_idx","columns":["retain_until"]},{"name":"users_login_attempts_created_at_idx","columns":["created_at"]}],"version":"89dfe336"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersLoginAuditEvent":{"name":"usersloginauditevent","className":"UsersLoginAuditEvent","qualifiedName":"@happyvertical/smrt-users:UsersLoginAuditEvent","collection":"usersloginauditevents","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/LoginAuditEvent.ts","packageName":"@happyvertical/smrt-users","fields":{"kind":{"type":"text","required":true,"_meta":{"required":true}},"outcome":{"type":"text","required":true,"_meta":{"required":true},"enum":["denied","failed","succeeded","locked","source-locked","managed"]},"subjectKeyHash":{"type":"text","required":false,"_meta":{"nullable":true,"indexed":true}},"sourceKeyHash":{"type":"text","required":false,"_meta":{"nullable":true,"indexed":true}},"retryAfterSeconds":{"type":"integer","required":false,"_meta":{"nullable":true}},"occurredAt":{"type":"datetime","required":true,"_meta":{"required":true,"indexed":true}},"metadata":{"type":"text","required":false,"_meta":{}}},"methods":{"getMetadata":{"name":"getMetadata","async":false,"parameters":[],"returnType":"Record<string, unknown>","isStatic":false,"isPublic":true},"setMetadata":{"name":"setMetadata","async":false,"parameters":[{"name":"value","type":"Record<string, unknown>","optional":false}],"returnType":"void","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"users_login_audit_events","sensitive":true,"api":false,"cli":false,"mcp":false},"extends":"SmrtObject","exportName":"UsersLoginAuditEvent","collectionExportName":"UsersLoginAuditEventCollection","validationRules":[{"field":"kind","rule":"required","fieldType":"text"},{"field":"outcome","rule":"required","fieldType":"text"},{"field":"occurredAt","rule":"required","fieldType":"datetime"}],"schema":{"tableName":"users_login_audit_events","ddl":"CREATE TABLE IF NOT EXISTS \\"users_login_audit_events\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"kind\\" TEXT NOT NULL,\\n \\"outcome\\" TEXT NOT NULL,\\n \\"subject_key_hash\\" TEXT,\\n \\"source_key_hash\\" TEXT,\\n \\"retry_after_seconds\\" INTEGER,\\n \\"occurred_at\\" TIMESTAMP NOT NULL,\\n \\"metadata\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"kind":{"type":"TEXT","notNull":true,"unique":false},"outcome":{"type":"TEXT","notNull":true,"unique":false},"subject_key_hash":{"type":"TEXT","notNull":false,"unique":false},"source_key_hash":{"type":"TEXT","notNull":false,"unique":false},"retry_after_seconds":{"type":"INTEGER","notNull":false,"unique":false},"occurred_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"metadata":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"users_login_audit_events_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_login_audit_events_subject_key_hash_idx","columns":["subject_key_hash"]},{"name":"users_login_audit_events_source_key_hash_idx","columns":["source_key_hash"]},{"name":"users_login_audit_events_occurred_at_idx","columns":["occurred_at"]},{"name":"users_login_audit_events_created_at_idx","columns":["created_at"]}],"version":"485105a9"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersMagicLinkToken":{"name":"usersmagiclinktoken","className":"UsersMagicLinkToken","qualifiedName":"@happyvertical/smrt-users:UsersMagicLinkToken","collection":"usersmagiclinktokens","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/MagicLinkToken.ts","packageName":"@happyvertical/smrt-users","fields":{"nonce":{"type":"text","required":true,"default":"","_meta":{"required":true,"unique":true}},"email":{"type":"text","required":false,"default":""},"used":{"type":"boolean","required":false,"default":false},"expiresAt":{"type":"datetime","required":false,"_meta":{"indexed":true}}},"methods":{"isExpired":{"name":"isExpired","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isValid":{"name":"isValid","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"users_magic_link_tokens","sensitive":true,"api":{"include":[]},"mcp":{"include":[]},"cli":false},"extends":"SmrtObject","exportName":"UsersMagicLinkToken","collectionExportName":"UsersMagicLinkTokenCollection","validationRules":[{"field":"nonce","rule":"required","fieldType":"text"}],"schema":{"tableName":"users_magic_link_tokens","ddl":"CREATE TABLE IF NOT EXISTS \\"users_magic_link_tokens\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"nonce\\" TEXT NOT NULL UNIQUE DEFAULT '',\\n \\"email\\" TEXT DEFAULT '',\\n \\"used\\" BOOLEAN DEFAULT FALSE,\\n \\"expires_at\\" TIMESTAMP\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"nonce":{"type":"TEXT","notNull":true,"unique":true,"default":""},"email":{"type":"TEXT","notNull":false,"unique":false,"default":""},"used":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"users_magic_link_tokens_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_magic_link_tokens_expires_at_idx","columns":["expires_at"]},{"name":"users_magic_link_tokens_created_at_idx","columns":["created_at"]}],"version":"537853d3"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:Membership":{"name":"membership","className":"Membership","qualifiedName":"@happyvertical/smrt-users:Membership","collection":"memberships","description":"Membership represents a user's membership in a tenant with an assigned role.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/Membership.ts","packageName":"@happyvertical/smrt-users","fields":{"userId":{"type":"foreignKey","required":true,"related":"User","description":"The person who belongs to this organization.","_meta":{"description":"The person who belongs to this organization.","required":true}},"tenantId":{"type":"foreignKey","required":true,"related":"Tenant","_meta":{"required":true}},"roleId":{"type":"foreignKey","required":true,"related":"Role","description":"The role that determines this member's permissions.","_meta":{"description":"The role that determines this member's permissions.","required":true}},"status":{"type":"text","required":false,"description":"Whether this membership is active, pending, or inactive.","_meta":{"description":"Whether this membership is active, pending, or inactive."}}},"methods":{"isActive":{"name":"isActive","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isPending":{"name":"isPending","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]},"indexes":[{"name":"memberships_tenant_id_user_id_idx","columns":["tenantId","userId"]}],"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"Membership","collectionExportName":"MembershipCollection","validationRules":[{"field":"userId","rule":"required","fieldType":"foreignKey"},{"field":"tenantId","rule":"required","fieldType":"foreignKey"},{"field":"roleId","rule":"required","fieldType":"foreignKey"}],"schema":{"tableName":"memberships","ddl":"CREATE TABLE IF NOT EXISTS \\"memberships\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"user_id\\" UUID NOT NULL,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"role_id\\" UUID NOT NULL,\\n \\"status\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"user_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"users","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"tenant_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"tenants","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"role_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"roles","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"status":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"memberships_tenant_id_slug_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"memberships_tenant_id_user_id_idx","columns":["tenant_id","user_id"]},{"name":"memberships_created_at_idx","columns":["created_at"]},{"name":"memberships_user_id_idx","columns":["user_id"]},{"name":"memberships_role_id_idx","columns":["role_id"]}],"version":"ebfd11e0"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:MembershipOverride":{"name":"membershipoverride","className":"MembershipOverride","qualifiedName":"@happyvertical/smrt-users:MembershipOverride","collection":"membershipoverrides","description":"MembershipOverride allows granting or denying specific permissions to a user beyond what their role and groups provide.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/MembershipOverride.ts","packageName":"@happyvertical/smrt-users","fields":{"membershipId":{"type":"foreignKey","required":true,"related":"Membership","_meta":{"required":true,"onDelete":"NO ACTION"}},"permissionId":{"type":"foreignKey","required":true,"related":"Permission","_meta":{"required":true,"onDelete":"NO ACTION"}},"effect":{"type":"text","required":false,"_meta":{}}},"methods":{"isGrant":{"name":"isGrant","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isDeny":{"name":"isDeny","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]},"conflictColumns":["membership_id","permission_id"]},"extends":"SmrtObject","exportName":"MembershipOverride","collectionExportName":"MembershipOverrideCollection","validationRules":[{"field":"membershipId","rule":"required","fieldType":"foreignKey"},{"field":"permissionId","rule":"required","fieldType":"foreignKey"}],"schema":{"tableName":"membership_overrides","ddl":"CREATE TABLE IF NOT EXISTS \\"membership_overrides\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"membership_id\\" UUID NOT NULL,\\n \\"permission_id\\" UUID NOT NULL,\\n \\"effect\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"membership_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"memberships","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"permission_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"permissions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"effect":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"membership_overrides_membership_id_permission_id_idx","columns":["membership_id","permission_id"],"unique":true},{"name":"membership_overrides_slug_context_idx","columns":["slug","context"]},{"name":"membership_overrides_created_at_idx","columns":["created_at"]},{"name":"membership_overrides_permission_id_idx","columns":["permission_id"]}],"version":"25fe9da8"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersOAuthClient":{"name":"usersoauthclient","className":"UsersOAuthClient","qualifiedName":"@happyvertical/smrt-users:UsersOAuthClient","collection":"usersoauthclients","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/OAuthAuthorization.ts","packageName":"@happyvertical/smrt-users","fields":{"clientId":{"type":"text","required":true,"_meta":{"required":true,"unique":true}},"redirectUris":{"type":"text","required":false},"allowedScopes":{"type":"text","required":false},"tokenEndpointAuthMethod":{"type":"text","required":false,"default":"none","enum":["none","client_secret_post"]},"secretHash":{"type":"text","required":false,"_meta":{"nullable":true,"sensitive":true},"sensitive":true},"allowedResources":{"type":"text","required":false},"createdAt":{"type":"datetime","required":false,"_meta":{}}},"methods":{"getRedirectUris":{"name":"getRedirectUris","async":false,"parameters":[],"returnType":"string[]","isStatic":false,"isPublic":true},"getAllowedScopes":{"name":"getAllowedScopes","async":false,"parameters":[],"returnType":"string[]","isStatic":false,"isPublic":true},"getAllowedResources":{"name":"getAllowedResources","async":false,"parameters":[],"returnType":"string[] | undefined","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"users_oauth_clients","sensitive":true,"api":{"include":[]},"mcp":{"include":[]},"cli":false},"extends":"SmrtObject","exportName":"UsersOAuthClient","collectionExportName":"UsersOAuthClientCollection","validationRules":[{"field":"clientId","rule":"required","fieldType":"text"}],"schema":{"tableName":"users_oauth_clients","ddl":"CREATE TABLE IF NOT EXISTS \\"users_oauth_clients\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"client_id\\" TEXT NOT NULL UNIQUE,\\n \\"redirect_uris\\" TEXT,\\n \\"allowed_scopes\\" TEXT,\\n \\"token_endpoint_auth_method\\" TEXT DEFAULT 'none',\\n \\"secret_hash\\" TEXT,\\n \\"allowed_resources\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"client_id":{"type":"TEXT","notNull":true,"unique":true},"redirect_uris":{"type":"TEXT","notNull":false,"unique":false},"allowed_scopes":{"type":"TEXT","notNull":false,"unique":false},"token_endpoint_auth_method":{"type":"TEXT","notNull":false,"unique":false,"default":"none"},"secret_hash":{"type":"TEXT","notNull":false,"unique":false},"allowed_resources":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"users_oauth_clients_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_oauth_clients_created_at_idx","columns":["created_at"]}],"version":"0ecda18c"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersOAuthAuthorizationCode":{"name":"usersoauthauthorizationcode","className":"UsersOAuthAuthorizationCode","qualifiedName":"@happyvertical/smrt-users:UsersOAuthAuthorizationCode","collection":"usersoauthauthorizationcodes","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/OAuthAuthorization.ts","packageName":"@happyvertical/smrt-users","fields":{"authorizationId":{"type":"text","required":false,"_meta":{"nullable":true,"indexed":true}},"codeHash":{"type":"text","required":true,"_meta":{"required":true,"unique":true,"sensitive":true},"sensitive":true},"clientId":{"type":"text","required":false,"_meta":{"indexed":true}},"subject":{"type":"text","required":false,"_meta":{"indexed":true}},"tenantId":{"type":"text","required":false,"_meta":{"nullable":true,"indexed":true}},"claims":{"type":"text","required":false},"redirectUri":{"type":"text","required":false},"scopes":{"type":"text","required":false},"resource":{"type":"text","required":false,"_meta":{"nullable":true}},"codeChallenge":{"type":"text","required":false},"expiresAt":{"type":"datetime","required":false,"_meta":{"indexed":true}},"consumedAt":{"type":"datetime","required":false,"_meta":{"nullable":true}}},"methods":{"getScopes":{"name":"getScopes","async":false,"parameters":[],"returnType":"string[]","isStatic":false,"isPublic":true},"getClaims":{"name":"getClaims","async":false,"parameters":[],"returnType":"OAuthTokenClaims","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"users_oauth_authorization_codes","sensitive":true,"api":{"include":[]},"mcp":{"include":[]},"cli":false,"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"UsersOAuthAuthorizationCode","collectionExportName":"UsersOAuthAuthorizationCodeCollection","validationRules":[{"field":"codeHash","rule":"required","fieldType":"text"}],"schema":{"tableName":"users_oauth_authorization_codes","ddl":"CREATE TABLE IF NOT EXISTS \\"users_oauth_authorization_codes\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"authorization_id\\" TEXT,\\n \\"code_hash\\" TEXT NOT NULL UNIQUE,\\n \\"client_id\\" TEXT,\\n \\"subject\\" TEXT,\\n \\"tenant_id\\" TEXT,\\n \\"claims\\" TEXT,\\n \\"redirect_uri\\" TEXT,\\n \\"scopes\\" TEXT,\\n \\"resource\\" TEXT,\\n \\"code_challenge\\" TEXT,\\n \\"expires_at\\" TIMESTAMP,\\n \\"consumed_at\\" TIMESTAMP\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"authorization_id":{"type":"TEXT","notNull":false,"unique":false},"code_hash":{"type":"TEXT","notNull":true,"unique":true},"client_id":{"type":"TEXT","notNull":false,"unique":false},"subject":{"type":"TEXT","notNull":false,"unique":false},"tenant_id":{"type":"TEXT","notNull":false,"unique":false},"claims":{"type":"TEXT","notNull":false,"unique":false},"redirect_uri":{"type":"TEXT","notNull":false,"unique":false},"scopes":{"type":"TEXT","notNull":false,"unique":false},"resource":{"type":"TEXT","notNull":false,"unique":false},"code_challenge":{"type":"TEXT","notNull":false,"unique":false},"expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"consumed_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"users_oauth_authorization_codes_tenant_id_slug_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"users_oauth_authorization_codes_authorization_id_idx","columns":["authorization_id"]},{"name":"users_oauth_authorization_codes_client_id_idx","columns":["client_id"]},{"name":"users_oauth_authorization_codes_subject_idx","columns":["subject"]},{"name":"users_oauth_authorization_codes_tenant_id_idx","columns":["tenant_id"]},{"name":"users_oauth_authorization_codes_expires_at_idx","columns":["expires_at"]},{"name":"users_oauth_authorization_codes_created_at_idx","columns":["created_at"]}],"version":"f5c5d615"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersOAuthRefreshGrant":{"name":"usersoauthrefreshgrant","className":"UsersOAuthRefreshGrant","qualifiedName":"@happyvertical/smrt-users:UsersOAuthRefreshGrant","collection":"usersoauthrefreshgrants","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/OAuthAuthorization.ts","packageName":"@happyvertical/smrt-users","fields":{"authorizationId":{"type":"text","required":false,"_meta":{"nullable":true,"indexed":true}},"tokenHash":{"type":"text","required":true,"_meta":{"required":true,"unique":true,"sensitive":true},"sensitive":true},"familyId":{"type":"text","required":false,"_meta":{"indexed":true}},"clientId":{"type":"text","required":false,"_meta":{"indexed":true}},"subject":{"type":"text","required":false,"_meta":{"indexed":true}},"tenantId":{"type":"text","required":false,"_meta":{"nullable":true,"indexed":true}},"claims":{"type":"text","required":false},"scopes":{"type":"text","required":false},"resource":{"type":"text","required":false,"_meta":{"nullable":true}},"expiresAt":{"type":"datetime","required":false,"_meta":{"indexed":true}},"consumedAt":{"type":"datetime","required":false,"_meta":{"nullable":true}},"revokedAt":{"type":"datetime","required":false,"_meta":{"nullable":true,"indexed":true}}},"methods":{"getScopes":{"name":"getScopes","async":false,"parameters":[],"returnType":"string[]","isStatic":false,"isPublic":true},"getClaims":{"name":"getClaims","async":false,"parameters":[],"returnType":"OAuthTokenClaims","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"users_oauth_refresh_grants","sensitive":true,"api":{"include":[]},"mcp":{"include":[]},"cli":false,"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"UsersOAuthRefreshGrant","collectionExportName":"UsersOAuthRefreshGrantCollection","validationRules":[{"field":"tokenHash","rule":"required","fieldType":"text"}],"schema":{"tableName":"users_oauth_refresh_grants","ddl":"CREATE TABLE IF NOT EXISTS \\"users_oauth_refresh_grants\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"authorization_id\\" TEXT,\\n \\"token_hash\\" TEXT NOT NULL UNIQUE,\\n \\"family_id\\" TEXT,\\n \\"client_id\\" TEXT,\\n \\"subject\\" TEXT,\\n \\"tenant_id\\" TEXT,\\n \\"claims\\" TEXT,\\n \\"scopes\\" TEXT,\\n \\"resource\\" TEXT,\\n \\"expires_at\\" TIMESTAMP,\\n \\"consumed_at\\" TIMESTAMP,\\n \\"revoked_at\\" TIMESTAMP\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"authorization_id":{"type":"TEXT","notNull":false,"unique":false},"token_hash":{"type":"TEXT","notNull":true,"unique":true},"family_id":{"type":"TEXT","notNull":false,"unique":false},"client_id":{"type":"TEXT","notNull":false,"unique":false},"subject":{"type":"TEXT","notNull":false,"unique":false},"tenant_id":{"type":"TEXT","notNull":false,"unique":false},"claims":{"type":"TEXT","notNull":false,"unique":false},"scopes":{"type":"TEXT","notNull":false,"unique":false},"resource":{"type":"TEXT","notNull":false,"unique":false},"expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"consumed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"revoked_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"users_oauth_refresh_grants_tenant_id_slug_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"users_oauth_refresh_grants_authorization_id_idx","columns":["authorization_id"]},{"name":"users_oauth_refresh_grants_family_id_idx","columns":["family_id"]},{"name":"users_oauth_refresh_grants_client_id_idx","columns":["client_id"]},{"name":"users_oauth_refresh_grants_subject_idx","columns":["subject"]},{"name":"users_oauth_refresh_grants_tenant_id_idx","columns":["tenant_id"]},{"name":"users_oauth_refresh_grants_expires_at_idx","columns":["expires_at"]},{"name":"users_oauth_refresh_grants_revoked_at_idx","columns":["revoked_at"]},{"name":"users_oauth_refresh_grants_created_at_idx","columns":["created_at"]}],"version":"d332998e"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersOAuthAccessTokenRevocation":{"name":"usersoauthaccesstokenrevocation","className":"UsersOAuthAccessTokenRevocation","qualifiedName":"@happyvertical/smrt-users:UsersOAuthAccessTokenRevocation","collection":"usersoauthaccesstokenrevocations","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/OAuthAuthorization.ts","packageName":"@happyvertical/smrt-users","fields":{"jti":{"type":"text","required":true,"_meta":{"required":true,"unique":true,"sensitive":true},"sensitive":true},"expiresAt":{"type":"datetime","required":false,"_meta":{"indexed":true}}},"methods":{},"decoratorConfig":{"tableName":"users_oauth_access_token_revocations","sensitive":true,"api":{"include":[]},"mcp":{"include":[]},"cli":false},"extends":"SmrtObject","exportName":"UsersOAuthAccessTokenRevocation","collectionExportName":"UsersOAuthAccessTokenRevocationCollection","validationRules":[{"field":"jti","rule":"required","fieldType":"text"}],"schema":{"tableName":"users_oauth_access_token_revocations","ddl":"CREATE TABLE IF NOT EXISTS \\"users_oauth_access_token_revocations\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"jti\\" TEXT NOT NULL UNIQUE,\\n \\"expires_at\\" TIMESTAMP\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"jti":{"type":"TEXT","notNull":true,"unique":true},"expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"users_oauth_access_token_revocations_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_oauth_access_token_revocations_expires_at_idx","columns":["expires_at"]},{"name":"users_oauth_access_token_revocations_created_at_idx","columns":["created_at"]}],"version":"79147089"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersOAuthAuthorization":{"name":"usersoauthauthorization","className":"UsersOAuthAuthorization","qualifiedName":"@happyvertical/smrt-users:UsersOAuthAuthorization","collection":"usersoauthauthorizations","description":"A consent decision bound to a server-side session; never exposes its bearer.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/OAuthAuthorization.ts","packageName":"@happyvertical/smrt-users","fields":{"subject":{"type":"text","required":false,"_meta":{"indexed":true}},"sessionId":{"type":"text","required":false,"_meta":{"sensitive":true},"sensitive":true},"clientId":{"type":"text","required":false,"_meta":{"indexed":true}},"tenantId":{"type":"text","required":false,"_meta":{"nullable":true}},"scopes":{"type":"text","required":false},"permissionCeiling":{"type":"text","required":false},"resource":{"type":"text","required":false,"_meta":{"nullable":true}},"revokedAt":{"type":"datetime","required":false,"_meta":{"nullable":true}}},"methods":{"getPermissionCeiling":{"name":"getPermissionCeiling","async":false,"parameters":[],"returnType":"string[]","isStatic":false,"isPublic":true},"getScopes":{"name":"getScopes","async":false,"parameters":[],"returnType":"string[]","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"users_oauth_authorizations","sensitive":true,"api":{"include":[]},"mcp":{"include":[]},"cli":false,"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"UsersOAuthAuthorization","collectionExportName":"UsersOAuthAuthorizationCollection","schema":{"tableName":"users_oauth_authorizations","ddl":"CREATE TABLE IF NOT EXISTS \\"users_oauth_authorizations\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"subject\\" TEXT,\\n \\"session_id\\" TEXT,\\n \\"client_id\\" TEXT,\\n \\"tenant_id\\" TEXT,\\n \\"scopes\\" TEXT,\\n \\"permission_ceiling\\" TEXT,\\n \\"resource\\" TEXT,\\n \\"revoked_at\\" TIMESTAMP\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"subject":{"type":"TEXT","notNull":false,"unique":false},"session_id":{"type":"TEXT","notNull":false,"unique":false},"client_id":{"type":"TEXT","notNull":false,"unique":false},"tenant_id":{"type":"TEXT","notNull":false,"unique":false},"scopes":{"type":"TEXT","notNull":false,"unique":false},"permission_ceiling":{"type":"TEXT","notNull":false,"unique":false},"resource":{"type":"TEXT","notNull":false,"unique":false},"revoked_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"users_oauth_authorizations_tenant_id_slug_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"users_oauth_authorizations_subject_idx","columns":["subject"]},{"name":"users_oauth_authorizations_client_id_idx","columns":["client_id"]},{"name":"users_oauth_authorizations_created_at_idx","columns":["created_at"]}],"version":"291f8816"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersOAuthRefreshFamily":{"name":"usersoauthrefreshfamily","className":"UsersOAuthRefreshFamily","qualifiedName":"@happyvertical/smrt-users:UsersOAuthRefreshFamily","collection":"usersoauthrefreshfamilies","description":"Stable lock row: rotation and revocation always serialize on this family.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/OAuthAuthorization.ts","packageName":"@happyvertical/smrt-users","fields":{"authorizationId":{"type":"text","required":false,"_meta":{"nullable":true,"indexed":true}},"revokedAt":{"type":"datetime","required":false,"_meta":{"nullable":true}}},"methods":{},"decoratorConfig":{"tableName":"users_oauth_refresh_families","sensitive":true,"api":{"include":[]},"mcp":{"include":[]},"cli":false},"extends":"SmrtObject","exportName":"UsersOAuthRefreshFamily","collectionExportName":"UsersOAuthRefreshFamilyCollection","schema":{"tableName":"users_oauth_refresh_families","ddl":"CREATE TABLE IF NOT EXISTS \\"users_oauth_refresh_families\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"authorization_id\\" TEXT,\\n \\"revoked_at\\" TIMESTAMP\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"authorization_id":{"type":"TEXT","notNull":false,"unique":false},"revoked_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"users_oauth_refresh_families_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_oauth_refresh_families_authorization_id_idx","columns":["authorization_id"]},{"name":"users_oauth_refresh_families_created_at_idx","columns":["created_at"]}],"version":"37392f31"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersPasswordCredential":{"name":"userspasswordcredential","className":"UsersPasswordCredential","qualifiedName":"@happyvertical/smrt-users:UsersPasswordCredential","collection":"userspasswordcredentials","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/PasswordCredential.ts","packageName":"@happyvertical/smrt-users","fields":{"userId":{"type":"foreignKey","required":true,"related":"User","_meta":{"required":true,"unique":true}},"passwordHash":{"type":"text","required":true,"_meta":{"required":true,"sensitive":true},"sensitive":true},"version":{"type":"integer","required":true,"default":1,"_meta":{"required":true,"default":1}},"mustChange":{"type":"boolean","required":true,"default":false,"_meta":{"required":true,"default":false}},"rotatedAt":{"type":"datetime","required":false,"_meta":{"nullable":true}},"rotatedBy":{"type":"text","required":false,"_meta":{"nullable":true}}},"methods":{},"decoratorConfig":{"tableName":"users_password_credentials","sensitive":true,"api":false,"cli":false,"mcp":false},"extends":"SmrtObject","exportName":"UsersPasswordCredential","collectionExportName":"UsersPasswordCredentialCollection","validationRules":[{"field":"userId","rule":"required","fieldType":"foreignKey"},{"field":"passwordHash","rule":"required","fieldType":"text"},{"field":"version","rule":"required","fieldType":"integer"},{"field":"mustChange","rule":"required","fieldType":"boolean"}],"schema":{"tableName":"users_password_credentials","ddl":"CREATE TABLE IF NOT EXISTS \\"users_password_credentials\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"user_id\\" UUID NOT NULL UNIQUE,\\n \\"password_hash\\" TEXT NOT NULL,\\n \\"version\\" INTEGER NOT NULL DEFAULT 1,\\n \\"must_change\\" BOOLEAN NOT NULL DEFAULT FALSE,\\n \\"rotated_at\\" TIMESTAMP,\\n \\"rotated_by\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"user_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":true,"foreignKey":{"table":"users","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"password_hash":{"type":"TEXT","notNull":true,"unique":false},"version":{"type":"INTEGER","notNull":true,"unique":false,"default":1},"must_change":{"type":"BOOLEAN","notNull":true,"unique":false,"default":false},"rotated_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"rotated_by":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"users_password_credentials_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_password_credentials_created_at_idx","columns":["created_at"]}],"version":"9a828f77"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:Permission":{"name":"permission","className":"Permission","qualifiedName":"@happyvertical/smrt-users:Permission","collection":"permissions","description":"Permission represents a named capability in the system.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/Permission.ts","packageName":"@happyvertical/smrt-users","fields":{"name":{"type":"text","required":false,"default":"","description":"The name of an action people can be allowed to perform.","_meta":{"description":"The name of an action people can be allowed to perform."}},"description":{"type":"text","required":false,"default":"","description":"What this permission allows someone to do.","_meta":{"description":"What this permission allows someone to do."}},"category":{"type":"text","required":false,"default":"","description":"The area of the application this permission belongs to.","_meta":{"description":"The area of the application this permission belongs to."}}},"methods":{"parseSlug":{"name":"parseSlug","async":false,"parameters":[],"returnType":"ParsedPermissionSlug","isStatic":false,"isPublic":true},"getResource":{"name":"getResource","async":false,"parameters":[],"returnType":"string","isStatic":false,"isPublic":true},"getAction":{"name":"getAction","async":false,"parameters":[],"returnType":"string","isStatic":false,"isPublic":true},"isValidSlug":{"name":"isValidSlug","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtObject","exportName":"Permission","collectionExportName":"PermissionCollection","displayLabelField":"name","schema":{"tableName":"permissions","ddl":"CREATE TABLE IF NOT EXISTS \\"permissions\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"name\\" TEXT DEFAULT '',\\n \\"description\\" TEXT DEFAULT '',\\n \\"category\\" TEXT DEFAULT ''\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"description":{"type":"TEXT","notNull":false,"unique":false,"default":""},"category":{"type":"TEXT","notNull":false,"unique":false,"default":""}},"indexes":[{"name":"permissions_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"permissions_created_at_idx","columns":["created_at"]}],"version":"4c81b2af"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:UsersPinCredential":{"name":"userspincredential","className":"UsersPinCredential","qualifiedName":"@happyvertical/smrt-users:UsersPinCredential","collection":"userspincredentials","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/PinCredential.ts","packageName":"@happyvertical/smrt-users","fields":{"userId":{"type":"foreignKey","required":true,"related":"User","_meta":{"required":true,"unique":true}},"pinHash":{"type":"text","required":true,"_meta":{"required":true,"sensitive":true},"sensitive":true},"version":{"type":"integer","required":true,"default":1,"_meta":{"required":true,"default":1}},"mustReset":{"type":"boolean","required":true,"default":false,"_meta":{"required":true,"default":false}},"rotatedAt":{"type":"datetime","required":false,"_meta":{"nullable":true}},"rotatedBy":{"type":"text","required":false,"_meta":{"nullable":true}}},"methods":{},"decoratorConfig":{"tableName":"users_pin_credentials","sensitive":true,"api":false,"cli":false,"mcp":false},"extends":"SmrtObject","exportName":"UsersPinCredential","collectionExportName":"UsersPinCredentialCollection","validationRules":[{"field":"userId","rule":"required","fieldType":"foreignKey"},{"field":"pinHash","rule":"required","fieldType":"text"},{"field":"version","rule":"required","fieldType":"integer"},{"field":"mustReset","rule":"required","fieldType":"boolean"}],"schema":{"tableName":"users_pin_credentials","ddl":"CREATE TABLE IF NOT EXISTS \\"users_pin_credentials\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"user_id\\" UUID NOT NULL UNIQUE,\\n \\"pin_hash\\" TEXT NOT NULL,\\n \\"version\\" INTEGER NOT NULL DEFAULT 1,\\n \\"must_reset\\" BOOLEAN NOT NULL DEFAULT FALSE,\\n \\"rotated_at\\" TIMESTAMP,\\n \\"rotated_by\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"user_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":true,"foreignKey":{"table":"users","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"pin_hash":{"type":"TEXT","notNull":true,"unique":false},"version":{"type":"INTEGER","notNull":true,"unique":false,"default":1},"must_reset":{"type":"BOOLEAN","notNull":true,"unique":false,"default":false},"rotated_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"rotated_by":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"users_pin_credentials_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_pin_credentials_created_at_idx","columns":["created_at"]}],"version":"0e2fa003"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:ResourceGrant":{"name":"resourcegrant","className":"ResourceGrant","qualifiedName":"@happyvertical/smrt-users:ResourceGrant","collection":"resourcegrants","description":"An exact tenant/resource/user/permission decision. This deliberately does not replace tenant RBAC: ResourceGrantResolver only allows after the normal operation guard has allowed the same permission.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/ResourceGrant.ts","packageName":"@happyvertical/smrt-users","fields":{"tenantId":{"type":"foreignKey","required":true,"related":"Tenant","_meta":{"required":true,"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"mode":"required","field":"tenantId","autoFilter":true,"autoPopulate":true,"allowSuperAdminBypass":false}}},"userId":{"type":"foreignKey","required":true,"related":"User","description":"The person receiving this record-specific access rule.","_meta":{"description":"The person receiving this record-specific access rule.","required":true}},"resourceType":{"type":"text","required":false,"description":"The kind of record this access rule applies to.","_meta":{"description":"The kind of record this access rule applies to."}},"resourceId":{"type":"text","required":false,"description":"The specific record covered by this access rule.","_meta":{"description":"The specific record covered by this access rule."}},"permission":{"type":"text","required":false,"description":"The action this rule allows or denies for the record.","_meta":{"description":"The action this rule allows or denies for the record."}},"effect":{"type":"text","required":false,"description":"Whether this rule grants access or denies it. Denies take precedence.","_meta":{"description":"Whether this rule grants access or denies it. Denies take precedence."},"enum":["grant","deny"]},"canDelegate":{"type":"boolean","required":false,"default":false,"description":"Whether the recipient may pass this grant on to another person.","_meta":{"description":"Whether the recipient may pass this grant on to another person."}},"parentGrantId":{"type":"foreignKey","required":false,"related":"ResourceGrant","description":"The earlier grant from which this access was delegated.","_meta":{"description":"The earlier grant from which this access was delegated."}},"revokedAt":{"type":"text","required":false,"description":"When this access rule was revoked, if it has ended.","_meta":{"description":"When this access rule was revoked, if it has ended."}}},"methods":{"isActive":{"name":"isActive","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true}},"decoratorConfig":{"tenantScoped":true,"api":{"include":[]},"mcp":{"include":[]},"cli":false,"indexes":[{"name":"resource_grants_lookup_idx","columns":["tenantId","userId"]}],"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"ResourceGrant","collectionExportName":"ResourceGrantCollection","validationRules":[{"field":"userId","rule":"required","fieldType":"foreignKey"}],"schema":{"tableName":"resource_grants","ddl":"CREATE TABLE IF NOT EXISTS \\"resource_grants\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"user_id\\" UUID NOT NULL,\\n \\"resource_type\\" TEXT,\\n \\"resource_id\\" TEXT,\\n \\"permission\\" TEXT,\\n \\"effect\\" TEXT,\\n \\"can_delegate\\" BOOLEAN DEFAULT FALSE,\\n \\"parent_grant_id\\" UUID,\\n \\"revoked_at\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"user_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"users","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"resource_type":{"type":"TEXT","notNull":false,"unique":false},"resource_id":{"type":"TEXT","notNull":false,"unique":false},"permission":{"type":"TEXT","notNull":false,"unique":false},"effect":{"type":"TEXT","notNull":false,"unique":false},"can_delegate":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"parent_grant_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"resource_grants","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"revoked_at":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"resource_grants_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"resource_grants_lookup_idx","columns":["tenant_id","user_id"]},{"name":"resource_grants_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"resource_grants_user_id_idx","columns":["user_id"]},{"name":"resource_grants_parent_grant_id_idx","columns":["parent_grant_id"]}],"version":"52e03776"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:Role":{"name":"role","className":"Role","qualifiedName":"@happyvertical/smrt-users:Role","collection":"roles","description":"Role represents a permission template that can be assigned to users.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/Role.ts","packageName":"@happyvertical/smrt-users","fields":{"tenantId":{"type":"foreignKey","required":false,"related":"Tenant","_meta":{"nullable":true}},"name":{"type":"text","required":false,"default":"","description":"The name of this set of permissions.","_meta":{"description":"The name of this set of permissions."}},"description":{"type":"text","required":false,"default":"","description":"What this role allows and who should receive it.","_meta":{"description":"What this role allows and who should receive it."}},"isSystem":{"type":"boolean","required":false,"default":false,"description":"Whether this is a built-in role protected from deletion.","_meta":{"description":"Whether this is a built-in role protected from deletion."}},"inheritsToDescendants":{"type":"boolean","required":false,"default":false,"description":"Whether this role can give members access to organizations below theirs.","_meta":{"description":"Whether this role can give members access to organizations below theirs."}}},"methods":{"isSystemRole":{"name":"isSystemRole","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isTenantRole":{"name":"isTenantRole","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"canDelete":{"name":"canDelete","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"delete":{"name":"delete","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"Role","collectionExportName":"RoleCollection","displayLabelField":"name","schema":{"tableName":"roles","ddl":"CREATE TABLE IF NOT EXISTS \\"roles\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"name\\" TEXT DEFAULT '',\\n \\"description\\" TEXT DEFAULT '',\\n \\"is_system\\" BOOLEAN DEFAULT FALSE,\\n \\"inherits_to_descendants\\" BOOLEAN DEFAULT FALSE\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"tenants","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"description":{"type":"TEXT","notNull":false,"unique":false,"default":""},"is_system":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"inherits_to_descendants":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false}},"indexes":[{"name":"roles_tenant_id_slug_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"roles_created_at_idx","columns":["created_at"]}],"version":"47369d9d"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:RolePermission":{"name":"rolepermission","className":"RolePermission","qualifiedName":"@happyvertical/smrt-users:RolePermission","collection":"rolepermissions","description":"RolePermission is a join table linking Roles to Permissions.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/RolePermission.ts","packageName":"@happyvertical/smrt-users","fields":{"roleId":{"type":"foreignKey","required":true,"related":"Role","_meta":{"required":true,"onDelete":"NO ACTION"}},"permissionId":{"type":"foreignKey","required":true,"related":"Permission","_meta":{"required":true,"onDelete":"NO ACTION"}}},"methods":{},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]},"conflictColumns":["role_id","permission_id"]},"extends":"SmrtObject","exportName":"RolePermission","collectionExportName":"RolePermissionCollection","validationRules":[{"field":"roleId","rule":"required","fieldType":"foreignKey"},{"field":"permissionId","rule":"required","fieldType":"foreignKey"}],"schema":{"tableName":"role_permissions","ddl":"CREATE TABLE IF NOT EXISTS \\"role_permissions\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"role_id\\" UUID NOT NULL,\\n \\"permission_id\\" UUID NOT NULL\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"role_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"roles","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"permission_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"permissions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}}},"indexes":[{"name":"role_permissions_role_id_permission_id_idx","columns":["role_id","permission_id"],"unique":true},{"name":"role_permissions_slug_context_idx","columns":["slug","context"]},{"name":"role_permissions_created_at_idx","columns":["created_at"]},{"name":"role_permissions_permission_id_idx","columns":["permission_id"]}],"version":"4dfed3ac"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:Session":{"name":"session","className":"Session","qualifiedName":"@happyvertical/smrt-users:Session","collection":"sessions","description":"Session represents an authenticated user session.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/Session.ts","packageName":"@happyvertical/smrt-users","fields":{"userId":{"type":"foreignKey","required":false,"related":"User","description":"The person signed in through this session.","_meta":{"description":"The person signed in through this session."}},"tenantId":{"type":"foreignKey","required":false,"related":"Tenant","_meta":{"nullable":true}},"status":{"type":"text","required":false,"description":"Whether this sign-in session is active or has ended.","_meta":{"description":"Whether this sign-in session is active or has ended."}},"expiresAt":{"type":"datetime","required":false,"description":"When this session expires unless renewed within its allowed limits.","_meta":{"description":"When this session expires unless renewed within its allowed limits.","indexed":true}},"userAgent":{"type":"text","required":false,"default":"","description":"The browser or device reported when this session was created.","_meta":{"description":"The browser or device reported when this session was created."}},"ipAddress":{"type":"text","required":false,"default":"","description":"The network address reported for this session.","_meta":{"description":"The network address reported for this session."}},"lastAccessedAt":{"type":"datetime","required":false,"description":"When this session was last used.","_meta":{"description":"When this session was last used."}},"data":{"type":"json","required":false,"default":{},"description":"Additional session details maintained by your application.","_meta":{"description":"Additional session details maintained by your application."}},"authMethod":{"type":"text","required":false,"description":"The sign-in method used to establish this session.","_meta":{"description":"The sign-in method used to establish this session.","nullable":true}},"parentSessionId":{"type":"text","required":false,"_meta":{"sqlType":"UUID","nullable":true,"indexed":true,"sensitive":true},"sensitive":true}},"methods":{"isLayered":{"name":"isLayered","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"getAbsoluteExpiry":{"name":"getAbsoluteExpiry","async":false,"parameters":[],"returnType":"Date | null","isStatic":false,"isPublic":true},"getIdleSeconds":{"name":"getIdleSeconds","async":false,"parameters":[],"returnType":"number | null","isStatic":false,"isPublic":true},"getPermissionCeiling":{"name":"getPermissionCeiling","async":false,"parameters":[],"returnType":"string[] | null","isStatic":false,"isPublic":true},"isValid":{"name":"isValid","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isExpired":{"name":"isExpired","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isRevoked":{"name":"isRevoked","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"touch":{"name":"touch","async":false,"parameters":[],"returnType":"void","isStatic":false,"isPublic":true},"extend":{"name":"extend","async":false,"parameters":[{"name":"ttlSeconds","type":"number","optional":true}],"returnType":"void","isStatic":false,"isPublic":true},"recordActivity":{"name":"recordActivity","async":true,"parameters":[{"name":"extendTtl","type":"any","optional":true},{"name":"ttlSeconds","type":"number","optional":true}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"revoke":{"name":"revoke","async":false,"parameters":[],"returnType":"void","isStatic":false,"isPublic":true},"setTenant":{"name":"setTenant","async":false,"parameters":[{"name":"tenantId","type":"string | null","optional":false,"unionBranches":[{"type":"string"},{"type":"null"}]}],"returnType":"void","isStatic":false,"isPublic":true},"getData":{"name":"getData","async":false,"parameters":[{"name":"key","type":"string","optional":false}],"returnType":"T | undefined","isStatic":false,"isPublic":true},"setData":{"name":"setData","async":false,"parameters":[{"name":"key","type":"string","optional":false},{"name":"value","type":"unknown","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"removeData":{"name":"removeData","async":false,"parameters":[{"name":"key","type":"string","optional":false}],"returnType":"void","isStatic":false,"isPublic":true}},"decoratorConfig":{"sensitive":true,"api":{"include":["get","delete"]},"mcp":{"include":[]},"cli":false,"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"Session","collectionExportName":"SessionCollection","schema":{"tableName":"sessions","ddl":"CREATE TABLE IF NOT EXISTS \\"sessions\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"user_id\\" UUID,\\n \\"tenant_id\\" UUID,\\n \\"status\\" TEXT,\\n \\"expires_at\\" TIMESTAMP,\\n \\"user_agent\\" TEXT DEFAULT '',\\n \\"ip_address\\" TEXT DEFAULT '',\\n \\"last_accessed_at\\" TIMESTAMP,\\n \\"data\\" JSON DEFAULT '{}',\\n \\"auth_method\\" TEXT,\\n \\"parent_session_id\\" UUID\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"user_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"users","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"tenant_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"tenants","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"status":{"type":"TEXT","notNull":false,"unique":false},"expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"user_agent":{"type":"TEXT","notNull":false,"unique":false,"default":""},"ip_address":{"type":"TEXT","notNull":false,"unique":false,"default":""},"last_accessed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"data":{"type":"JSON","notNull":false,"unique":false,"default":{}},"auth_method":{"type":"TEXT","notNull":false,"unique":false},"parent_session_id":{"type":"UUID","notNull":false,"unique":false}},"indexes":[{"name":"sessions_tenant_id_slug_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"sessions_expires_at_idx","columns":["expires_at"]},{"name":"sessions_parent_session_id_idx","columns":["parent_session_id"]},{"name":"sessions_created_at_idx","columns":["created_at"]},{"name":"sessions_user_id_idx","columns":["user_id"]}],"version":"b4260a0f"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:Tenant":{"name":"tenant","className":"Tenant","qualifiedName":"@happyvertical/smrt-users:Tenant","collection":"tenants","description":"Tenant represents an organizational boundary in the multi-tenant system.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/Tenant.ts","packageName":"@happyvertical/smrt-users","fields":{"created_at":{"type":"datetime","required":false},"updated_at":{"type":"datetime","required":false},"name":{"type":"text","required":false,"default":""},"status":{"type":"text","required":false,"_meta":{}},"description":{"type":"text","required":false,"default":""},"parentTenantId":{"type":"foreignKey","required":false,"related":"Tenant","_meta":{"nullable":true}},"hierarchyLevel":{"type":"integer","required":false,"default":0},"hierarchyPath":{"type":"text","required":false,"default":""},"cascadePermissions":{"type":"boolean","required":false,"default":true},"inheritPermissions":{"type":"boolean","required":false,"default":true}},"methods":{"isActive":{"name":"isActive","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isSuspended":{"name":"isSuspended","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isRoot":{"name":"isRoot","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"canCascadeToChildren":{"name":"canCascadeToChildren","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"acceptsInheritance":{"name":"acceptsInheritance","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"save":{"name":"save","async":true,"parameters":[{"name":"options","type":"SmrtSaveOptions","optional":true}],"returnType":"Promise<this>","isStatic":false,"isPublic":true},"getAncestorIds":{"name":"getAncestorIds","async":false,"parameters":[],"returnType":"string[]","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableStrategy":"sti","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtObject","exportName":"Tenant","collectionExportName":"TenantCollection","displayLabelField":"name","schema":{"tableName":"tenants","ddl":"CREATE TABLE IF NOT EXISTS \\"tenants\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"_meta_type\\" TEXT NOT NULL,\\n \\"_meta_data\\" JSON,\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"name\\" TEXT DEFAULT '',\\n \\"status\\" TEXT,\\n \\"description\\" TEXT DEFAULT '',\\n \\"parent_tenant_id\\" UUID,\\n \\"hierarchy_level\\" INTEGER DEFAULT 0,\\n \\"hierarchy_path\\" TEXT DEFAULT '',\\n \\"cascade_permissions\\" BOOLEAN DEFAULT TRUE,\\n \\"inherit_permissions\\" BOOLEAN DEFAULT TRUE\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"_meta_type":{"type":"TEXT","notNull":true},"_meta_data":{"type":"JSON","notNull":false},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"name":{"type":"TEXT","notNull":false,"default":""},"status":{"type":"TEXT","notNull":false},"description":{"type":"TEXT","notNull":false,"default":""},"parent_tenant_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"foreignKey":{"table":"tenants","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"hierarchy_level":{"type":"INTEGER","notNull":false,"default":0},"hierarchy_path":{"type":"TEXT","notNull":false,"default":""},"cascade_permissions":{"type":"BOOLEAN","notNull":false,"default":true},"inherit_permissions":{"type":"BOOLEAN","notNull":false,"default":true}},"indexes":[{"name":"tenants_slug_context_meta_type_idx","columns":["slug","context","_meta_type"],"unique":true},{"name":"tenants_meta_type_idx","columns":["_meta_type"]},{"name":"tenants_created_at_idx","columns":["created_at"]},{"name":"tenants_parent_tenant_id_idx","columns":["parent_tenant_id"]}],"version":"934f7025"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:TenantIntegration":{"name":"tenantintegration","className":"TenantIntegration","qualifiedName":"@happyvertical/smrt-users:TenantIntegration","collection":"tenantintegrations","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/TenantIntegration.ts","packageName":"@happyvertical/smrt-users","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"provider":{"type":"text","required":false,"default":"aws"},"externalIds":{"type":"text","required":false},"status":{"type":"text","required":false,"default":"unprovisioned","enum":["unprovisioned","provisioning","active","drifted","failed"]},"lastCheckedAt":{"type":"datetime","required":false},"lastCheckSummary":{"type":"text","required":false},"lastError":{"type":"text","required":false}},"methods":{"initialize":{"name":"initialize","async":true,"parameters":[],"returnType":"Promise<this>","isStatic":false,"isPublic":true},"getExternalIds":{"name":"getExternalIds","async":false,"parameters":[],"returnType":"Record<string, string>","isStatic":false,"isPublic":true},"setExternalIds":{"name":"setExternalIds","async":false,"parameters":[{"name":"externalIds","type":"Record<string, string> | string","optional":false,"unionBranches":[{"type":"Record<string, string>"},{"type":"string"}]}],"returnType":"void","isStatic":false,"isPublic":true},"getExternalId":{"name":"getExternalId","async":false,"parameters":[{"name":"key","type":"string","optional":false}],"returnType":"string | undefined","isStatic":false,"isPublic":true},"setExternalId":{"name":"setExternalId","async":false,"parameters":[{"name":"key","type":"string","optional":false},{"name":"value","type":"string | undefined","optional":false,"unionBranches":[{"type":"string"},{"type":"undefined"}]}],"returnType":"void","isStatic":false,"isPublic":true},"getLastCheckSummary":{"name":"getLastCheckSummary","async":false,"parameters":[],"returnType":"TenantIntegrationCheckSummary[]","isStatic":false,"isPublic":true},"setLastCheckSummary":{"name":"setLastCheckSummary","async":false,"parameters":[{"name":"summary","type":"TenantIntegrationCheckSummary[] | string","optional":false,"unionBranches":[{"type":"TenantIntegrationCheckSummary[]"},{"type":"string"}]}],"returnType":"void","isStatic":false,"isPublic":true},"recordDoctorRun":{"name":"recordDoctorRun","async":false,"parameters":[{"name":"outcome","type":"object","optional":false,"memberTypes":["TenantIntegrationStatus","TenantIntegrationCheckSummary[]","string | null"]}],"returnType":"void","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"tenant_integrations","conflictColumns":["tenant_id","provider"],"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]},"tenantScoped":{"mode":"required"}},"extends":"SmrtObject","exportName":"TenantIntegration","collectionExportName":"TenantIntegrationCollection","validationRules":[],"schema":{"tableName":"tenant_integrations","ddl":"CREATE TABLE IF NOT EXISTS \\"tenant_integrations\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"provider\\" TEXT DEFAULT 'aws',\\n \\"external_ids\\" TEXT,\\n \\"status\\" TEXT DEFAULT 'unprovisioned',\\n \\"last_checked_at\\" TIMESTAMP,\\n \\"last_check_summary\\" TEXT,\\n \\"last_error\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"provider":{"type":"TEXT","notNull":false,"unique":false,"default":"aws"},"external_ids":{"type":"TEXT","notNull":false,"unique":false},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"unprovisioned"},"last_checked_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"last_check_summary":{"type":"TEXT","notNull":false,"unique":false},"last_error":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"tenant_integrations_tenant_id_provider_idx","columns":["tenant_id","provider"],"unique":true,"nullsNotDistinct":true},{"name":"tenant_integrations_slug_context_idx","columns":["slug","context"]},{"name":"tenant_integrations_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"3ed31966"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:TenantPermissionOverride":{"name":"tenantpermissionoverride","className":"TenantPermissionOverride","qualifiedName":"@happyvertical/smrt-users:TenantPermissionOverride","collection":"tenantpermissionoverrides","description":"TenantPermissionOverride allows setting explicit permission values at the tenant level.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/TenantPermissionOverride.ts","packageName":"@happyvertical/smrt-users","fields":{"tenantId":{"type":"foreignKey","required":true,"related":"Tenant","_meta":{"required":true,"onDelete":"NO ACTION"}},"permissionId":{"type":"foreignKey","required":true,"related":"Permission","_meta":{"required":true,"onDelete":"NO ACTION"}},"effect":{"type":"text","required":false,"_meta":{}}},"methods":{"isInherit":{"name":"isInherit","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isGrant":{"name":"isGrant","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isDeny":{"name":"isDeny","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"hasExplicitEffect":{"name":"hasExplicitEffect","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]},"conflictColumns":["tenant_id","permission_id"]},"extends":"SmrtObject","exportName":"TenantPermissionOverride","collectionExportName":"TenantPermissionOverrideCollection","validationRules":[{"field":"tenantId","rule":"required","fieldType":"foreignKey"},{"field":"permissionId","rule":"required","fieldType":"foreignKey"}],"schema":{"tableName":"tenant_permission_overrides","ddl":"CREATE TABLE IF NOT EXISTS \\"tenant_permission_overrides\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"permission_id\\" UUID NOT NULL,\\n \\"effect\\" TEXT\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"tenants","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"permission_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"permissions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"effect":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"tenant_permission_overrides_tenant_id_permission_id_idx","columns":["tenant_id","permission_id"],"unique":true},{"name":"tenant_permission_overrides_slug_context_idx","columns":["slug","context"]},{"name":"tenant_permission_overrides_created_at_idx","columns":["created_at"]},{"name":"tenant_permission_overrides_permission_id_idx","columns":["permission_id"]}],"version":"95b78bdd"},"importPath":"@happyvertical/smrt-users"},"@happyvertical/smrt-users:User":{"name":"user","className":"User","qualifiedName":"@happyvertical/smrt-users:User","collection":"users","description":"User represents an authenticated identity in the system.","filePath":"/home/runner/work/smrt/smrt/packages/users/src/models/User.ts","packageName":"@happyvertical/smrt-users","fields":{"profileId":{"type":"crossPackageRef","required":false,"related":"@happyvertical/smrt-profiles:Profile","description":"The personal profile linked to this account.","_meta":{"description":"The personal profile linked to this account.","unique":true}},"email":{"type":"text","required":false,"default":"","description":"The email address used for this account.","_meta":{"description":"The email address used for this account.","indexed":true}},"emailKey":{"type":"text","required":false,"description":"The standardized email address used to recognize this account; maintained automatically.","_meta":{"description":"The standardized email address used to recognize this account; maintained automatically.","nullable":true,"unique":true,"readonly":true},"readonly":true},"username":{"type":"text","required":false,"description":"Optional username used to sign in; lowercase and globally unique.","_meta":{"description":"Optional username used to sign in; lowercase and globally unique.","nullable":true,"indexed":true}},"usernameKey":{"type":"text","required":false,"description":"The standardized username used to recognize this account; maintained automatically.","_meta":{"description":"The standardized username used to recognize this account; maintained automatically.","nullable":true,"unique":true,"readonly":true},"readonly":true},"status":{"type":"text","required":false,"description":"Whether this account is active, inactive, pending, or suspended.","_meta":{"description":"Whether this account is active, inactive, pending, or suspended."}},"lastLoginAt":{"type":"datetime","required":false,"description":"When this person most recently signed in.","_meta":{"description":"When this person most recently signed in."}}},"methods":{"hasValidEmail":{"name":"hasValidEmail","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isActive":{"name":"isActive","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isSuspended":{"name":"isSuspended","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isPending":{"name":"isPending","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"recordLogin":{"name":"recordLogin","async":false,"parameters":[],"returnType":"void","isStatic":false,"isPublic":true},"save":{"name":"save","async":true,"parameters":[],"returnType":"Promise<this>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtObject","exportName":"User","collectionExportName":"UserCollection","schema":{"tableName":"users","ddl":"CREATE TABLE IF NOT EXISTS \\"users\\" (\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"profile_id\\" UUID UNIQUE,\\n \\"email\\" TEXT DEFAULT '',\\n \\"email_key\\" TEXT UNIQUE,\\n \\"username\\" TEXT,\\n \\"username_key\\" TEXT UNIQUE,\\n \\"status\\" TEXT,\\n \\"last_login_at\\" TIMESTAMP\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":true},"email":{"type":"TEXT","notNull":false,"unique":false,"default":""},"email_key":{"type":"TEXT","notNull":false,"unique":true},"username":{"type":"TEXT","notNull":false,"unique":false},"username_key":{"type":"TEXT","notNull":false,"unique":true},"status":{"type":"TEXT","notNull":false,"unique":false},"last_login_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"users_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"users_email_idx","columns":["email"]},{"name":"users_username_idx","columns":["username"]},{"name":"users_created_at_idx","columns":["created_at"]}],"version":"3ee8f0f4"},"importPath":"@happyvertical/smrt-users"}},"moduleType":"smrt","recipes":[{"id":"users.roles-and-permissions","className":"UsersRolesAndPermissionsRecipe","label":"Roles and permissions","summary":"Manage tenant roles, memberships, permissions, and controlled sharing.","synonyms":["access control","rbac","sharing"],"models":["@happyvertical/smrt-users:Role","@happyvertical/smrt-users:Permission","@happyvertical/smrt-users:Membership","@happyvertical/smrt-users:ResourceGrant"],"nav":[{"label":"Roles","model":"@happyvertical/smrt-users:Role","icon":"users","description":"Define tenant permission bundles.","noun":"role"},{"label":"Permissions","model":"@happyvertical/smrt-users:Permission","icon":"settings","description":"Review operations available to roles.","noun":"permission"}],"requires":[],"group":{"id":"account-access","label":"Account access","summary":"Sign in and manage account sessions."},"section":{"id":"access-control","label":"Access control","icon":"users","description":"Manage tenant roles, permissions, and reviewed sharing."},"options":{"@happyvertical/smrt-users:ResourceGrant":{"exposure":{"api":false,"mcp":false,"cli":false}}},"help":{"markdown":"## Overview\\n\\nRoles and permissions control access to your organization. Denies take precedence, and role changes should be reviewed before they are applied.\\n\\n## Tasks\\n\\n- Ask an authorized administrator to create a role and assign only the permissions required for its work.\\n- Add a member to the correct organization through your approved membership settings and assign a role through {field:Membership.roleId}.\\n- Use a resource grant only when a record needs a reviewed exception to its ordinary role rules.\\n","fieldRefs":["Membership.roleId"]},"demo":{"mode":"server","reasons":["Needs a server because its package does not build for a browser: node:crypto/async_hooks; core migrations; and its package depends on @happyvertical/smrt-profiles, @happyvertical/smrt-tenancy, which do not build for a browser (#3617, #3624, #3626)."]}},{"id":"users.sign-in","className":"UsersSignInRecipe","label":"Sign in","summary":"Access an account through an application-authorized sign-in flow.","synonyms":["log in","authentication","single sign-on"],"models":["@happyvertical/smrt-users:User","@happyvertical/smrt-users:Session"],"nav":[{"label":"Security sessions","model":"@happyvertical/smrt-users:Session","icon":"settings","description":"Review active sessions and sign out unrecognized devices.","noun":"security session"}],"requires":[],"group":{"id":"account-access","label":"Account access","summary":"Sign in and manage account sessions."},"section":{"id":"account-security","label":"Account security","icon":"settings","description":"Review account access and active sessions."},"options":{"@happyvertical/smrt-users:Session":{"exposure":{"api":false,"mcp":false,"cli":false}}},"help":{"markdown":"## Overview\\n\\nUse your organization\u2019s approved sign-in method. Review your signed-in devices on your account security page.\\n\\n## Tasks\\n\\n- Review active sign-in sessions from your account security page and end sessions you no longer recognize.\\n- Ask an administrator for recovery help if you lose access to every available credential.\\n","fieldRefs":[]},"surfaces":[{"kind":"settings-panel","export":"@happyvertical/smrt-users/svelte#AccountSecurityPanel","label":"Account security"}],"providers":[{"id":"oidc","kind":"oauth","options":["oidc"],"required":false}],"demo":{"mode":"server","reasons":["Needs a server because its package does not build for a browser: node:crypto/async_hooks; core migrations; and its package depends on @happyvertical/smrt-profiles, @happyvertical/smrt-tenancy, which do not build for a browser (#3617, #3624, #3626)."]}}],"smrtDependencies":["@happyvertical/smrt-core","@happyvertical/smrt-mobile-contract","@happyvertical/smrt-profiles","@happyvertical/smrt-tenancy"],"browser":{"status":"server-only","issues":["#3617","#3624","#3626"],"reason":"node:crypto/async_hooks; core migrations","via":["@happyvertical/smrt-profiles","@happyvertical/smrt-tenancy"]},"stampsConstructors":true}`));
|
|
10
|
-
//#endregion
|
|
11
|
-
//#region src/models/CliAuthRequest.ts
|
|
12
|
-
var __defProp$1 = Object.defineProperty;
|
|
13
|
-
var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
|
|
14
|
-
var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, {
|
|
15
|
-
enumerable: true,
|
|
16
|
-
configurable: true,
|
|
17
|
-
writable: true,
|
|
18
|
-
value
|
|
19
|
-
}) : obj[key] = value;
|
|
20
|
-
var __decorateClass$1 = (decorators, target, key, kind) => {
|
|
21
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
|
|
22
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
23
|
-
if (kind && result) __defProp$1(target, key, result);
|
|
24
|
-
return result;
|
|
25
|
-
};
|
|
26
|
-
var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
27
|
-
var UsersCliAuthRequest = class extends SmrtObject {
|
|
28
|
-
userCode = "";
|
|
29
|
-
deviceCodeHash = "";
|
|
30
|
-
status = "pending";
|
|
31
|
-
userId = null;
|
|
32
|
-
tenantId = null;
|
|
33
|
-
sessionId = null;
|
|
34
|
-
expiresAt = /* @__PURE__ */ new Date();
|
|
35
|
-
approvedAt = null;
|
|
36
|
-
};
|
|
37
|
-
__publicField$1(UsersCliAuthRequest, "__smrtPackage__", "@happyvertical/smrt-users");
|
|
38
|
-
__decorateClass$1([field({
|
|
39
|
-
type: "text",
|
|
40
|
-
required: true,
|
|
41
|
-
unique: true
|
|
42
|
-
})], UsersCliAuthRequest.prototype, "userCode", 2);
|
|
43
|
-
__decorateClass$1([field({
|
|
44
|
-
type: "text",
|
|
45
|
-
required: true,
|
|
46
|
-
unique: true
|
|
47
|
-
})], UsersCliAuthRequest.prototype, "deviceCodeHash", 2);
|
|
48
|
-
__decorateClass$1([field({ type: "text" })], UsersCliAuthRequest.prototype, "status", 2);
|
|
49
|
-
__decorateClass$1([foreignKey("User", { nullable: true })], UsersCliAuthRequest.prototype, "userId", 2);
|
|
50
|
-
__decorateClass$1([foreignKey("Tenant", { nullable: true })], UsersCliAuthRequest.prototype, "tenantId", 2);
|
|
51
|
-
__decorateClass$1([foreignKey("Session", { nullable: true })], UsersCliAuthRequest.prototype, "sessionId", 2);
|
|
52
|
-
__decorateClass$1([field({
|
|
53
|
-
type: "datetime",
|
|
54
|
-
indexed: true
|
|
55
|
-
})], UsersCliAuthRequest.prototype, "expiresAt", 2);
|
|
56
|
-
__decorateClass$1([field({
|
|
57
|
-
type: "datetime",
|
|
58
|
-
nullable: true
|
|
59
|
-
})], UsersCliAuthRequest.prototype, "approvedAt", 2);
|
|
60
|
-
UsersCliAuthRequest = __decorateClass$1([smrt({
|
|
61
|
-
tableName: "users_cli_auth_requests",
|
|
62
|
-
sensitive: true,
|
|
63
|
-
api: { include: [] },
|
|
64
|
-
cli: false,
|
|
65
|
-
mcp: { include: [] }
|
|
66
|
-
})], UsersCliAuthRequest);
|
|
67
|
-
//#endregion
|
|
68
|
-
//#region src/collections/CliAuthRequestCollection.ts
|
|
69
|
-
var CliAuthApprovalLostError = class extends Error {};
|
|
70
|
-
var UsersCliAuthRequestCollection = class extends SmrtCollection {
|
|
71
|
-
static _itemClass = UsersCliAuthRequest;
|
|
72
|
-
/**
|
|
73
|
-
* Atomically approve one pending request and mint its bearer session.
|
|
74
|
-
*
|
|
75
|
-
* The session is created inside the same transaction as the conditional
|
|
76
|
-
* pending-to-approved transition. If another approver wins, or persisting
|
|
77
|
-
* the approval fails, throwing rolls the losing session back with the
|
|
78
|
-
* request write so no usable orphan credential can remain.
|
|
79
|
-
*/
|
|
80
|
-
async approvePendingRequest(input) {
|
|
81
|
-
const transaction = this.db.transaction?.bind(this.db);
|
|
82
|
-
if (!transaction) throw new Error("Terminal approval requires database transaction support.");
|
|
83
|
-
try {
|
|
84
|
-
return await transaction(async (tx) => {
|
|
85
|
-
const createdSessionId = (await (await SessionCollection.create({ db: tx })).createSession({
|
|
86
|
-
authMethod: "terminal",
|
|
87
|
-
data: {
|
|
88
|
-
approvedBy: input.approvedBy,
|
|
89
|
-
kind: "terminal"
|
|
90
|
-
},
|
|
91
|
-
ipAddress: input.ipAddress,
|
|
92
|
-
tenantId: input.tenantId,
|
|
93
|
-
ttl: input.sessionTtlSeconds,
|
|
94
|
-
userAgent: input.userAgent,
|
|
95
|
-
userId: input.userId
|
|
96
|
-
})).id;
|
|
97
|
-
if (!createdSessionId) throw new Error("Terminal approval failed to mint a session.");
|
|
98
|
-
const approvedAt = /* @__PURE__ */ new Date();
|
|
99
|
-
const now = approvedAt.toISOString();
|
|
100
|
-
const approved = await tx.query(`UPDATE ${this.tableName}
|
|
101
|
-
SET approved_at = ?, session_id = ?, status = 'approved',
|
|
102
|
-
tenant_id = ?, user_id = ?, updated_at = ?
|
|
103
|
-
WHERE user_code = ? AND status = 'pending' AND expires_at > ?
|
|
104
|
-
RETURNING id`, now, createdSessionId, input.tenantId, input.userId, now, input.userCode.trim().toUpperCase(), now);
|
|
105
|
-
if (approved.rows?.length !== 1) throw new CliAuthApprovalLostError();
|
|
106
|
-
const id = approved.rows[0]?.id;
|
|
107
|
-
if (typeof id !== "string") throw new Error("Terminal approval did not return its request id.");
|
|
108
|
-
return {
|
|
109
|
-
approvedAt,
|
|
110
|
-
id,
|
|
111
|
-
sessionId: createdSessionId,
|
|
112
|
-
tenantId: input.tenantId,
|
|
113
|
-
userId: input.userId
|
|
114
|
-
};
|
|
115
|
-
});
|
|
116
|
-
} catch (error) {
|
|
117
|
-
if (error instanceof CliAuthApprovalLostError) return null;
|
|
118
|
-
throw error;
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
/**
|
|
122
|
-
* Atomically consume the bearer session attached to an approved request.
|
|
123
|
-
*
|
|
124
|
-
* The conditional update is the arbiter: concurrent exchangers may observe
|
|
125
|
-
* the same candidate, but only one can change `approved` to `consumed` while
|
|
126
|
-
* matching the same session id. The winning transaction returns the token
|
|
127
|
-
* from its locked candidate and clears it from durable storage.
|
|
128
|
-
*/
|
|
129
|
-
async consumeApprovedSession(deviceCodeHash) {
|
|
130
|
-
const transaction = this.db.transaction?.bind(this.db);
|
|
131
|
-
if (!transaction) throw new Error("Terminal device exchange requires database transaction support.");
|
|
132
|
-
return transaction(async (tx) => {
|
|
133
|
-
const candidate = (await tx.query(`SELECT id, session_id FROM ${this.tableName}
|
|
134
|
-
WHERE device_code_hash = ? AND status = 'approved' AND session_id IS NOT NULL
|
|
135
|
-
LIMIT 1`, deviceCodeHash)).rows?.[0];
|
|
136
|
-
const id = typeof candidate?.id === "string" ? candidate.id : null;
|
|
137
|
-
const sessionId = typeof candidate?.session_id === "string" ? candidate.session_id : null;
|
|
138
|
-
if (!id || !sessionId) return null;
|
|
139
|
-
return (await tx.query(`UPDATE ${this.tableName}
|
|
140
|
-
SET status = 'consumed', session_id = NULL, updated_at = ?
|
|
141
|
-
WHERE id = ? AND status = 'approved' AND session_id = ?
|
|
142
|
-
RETURNING id`, (/* @__PURE__ */ new Date()).toISOString(), id, sessionId)).rows?.length === 1 ? sessionId : null;
|
|
143
|
-
});
|
|
144
|
-
}
|
|
145
|
-
/**
|
|
146
|
-
* Look up a pending or completed request by the short user code shown in the CLI.
|
|
147
|
-
*/
|
|
148
|
-
async findByUserCode(userCode) {
|
|
149
|
-
const [request] = await this.list({
|
|
150
|
-
limit: 1,
|
|
151
|
-
where: { userCode: userCode.trim().toUpperCase() }
|
|
152
|
-
});
|
|
153
|
-
return request ?? null;
|
|
154
|
-
}
|
|
155
|
-
/**
|
|
156
|
-
* Look up a request by the hash of its device code (the CLI's polling key).
|
|
157
|
-
*/
|
|
158
|
-
async findByDeviceCodeHash(deviceCodeHash) {
|
|
159
|
-
const [request] = await this.list({
|
|
160
|
-
limit: 1,
|
|
161
|
-
where: { deviceCodeHash }
|
|
162
|
-
});
|
|
163
|
-
return request ?? null;
|
|
164
|
-
}
|
|
165
|
-
/**
|
|
166
|
-
* Delete expired pending, lazily-expired, or already-consumed requests.
|
|
167
|
-
*
|
|
168
|
-
* Scheduled by the framework retention sweep (#2375); `expiresAt` carries an
|
|
169
|
-
* index for this predicate.
|
|
170
|
-
*
|
|
171
|
-
* @param options.dryRun - Count the requests the predicate selects without
|
|
172
|
-
* deleting them.
|
|
173
|
-
* @returns Number of requests deleted (or, under `dryRun`, matched)
|
|
174
|
-
*/
|
|
175
|
-
async deleteExpired(options = {}) {
|
|
176
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
177
|
-
const predicate = "status IN ('pending', 'expired', 'consumed') AND expires_at < ?";
|
|
178
|
-
const counted = await this.db.query(`SELECT COUNT(*) AS total FROM ${this.tableName} WHERE ${predicate}`, now);
|
|
179
|
-
const total = Number(counted.rows?.[0]?.total ?? 0);
|
|
180
|
-
if (!Number.isFinite(total) || total <= 0) return 0;
|
|
181
|
-
if (!options.dryRun) await this.db.query(`DELETE FROM ${this.tableName} WHERE ${predicate}`, now);
|
|
182
|
-
return total;
|
|
183
|
-
}
|
|
184
|
-
};
|
|
185
|
-
//#endregion
|
|
186
|
-
//#region src/models/PinCredential.ts
|
|
187
|
-
var __defProp = Object.defineProperty;
|
|
188
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
189
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
|
|
190
|
-
enumerable: true,
|
|
191
|
-
configurable: true,
|
|
192
|
-
writable: true,
|
|
193
|
-
value
|
|
194
|
-
}) : obj[key] = value;
|
|
195
|
-
var __decorateClass = (decorators, target, key, kind) => {
|
|
196
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
197
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
198
|
-
if (kind && result) __defProp(target, key, result);
|
|
199
|
-
return result;
|
|
200
|
-
};
|
|
201
|
-
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
202
|
-
var UsersPinCredential = class extends SmrtObject {
|
|
203
|
-
userId = "";
|
|
204
|
-
pinHash = "";
|
|
205
|
-
version = 1;
|
|
206
|
-
mustReset = false;
|
|
207
|
-
rotatedAt = null;
|
|
208
|
-
rotatedBy = null;
|
|
209
|
-
};
|
|
210
|
-
__publicField(UsersPinCredential, "__smrtPackage__", "@happyvertical/smrt-users");
|
|
211
|
-
__decorateClass([foreignKey("User", {
|
|
212
|
-
required: true,
|
|
213
|
-
unique: true
|
|
214
|
-
})], UsersPinCredential.prototype, "userId", 2);
|
|
215
|
-
__decorateClass([field({
|
|
216
|
-
type: "text",
|
|
217
|
-
required: true,
|
|
218
|
-
sensitive: true
|
|
219
|
-
})], UsersPinCredential.prototype, "pinHash", 2);
|
|
220
|
-
__decorateClass([field({
|
|
221
|
-
type: "integer",
|
|
222
|
-
required: true,
|
|
223
|
-
default: 1
|
|
224
|
-
})], UsersPinCredential.prototype, "version", 2);
|
|
225
|
-
__decorateClass([field({
|
|
226
|
-
type: "boolean",
|
|
227
|
-
required: true,
|
|
228
|
-
default: false
|
|
229
|
-
})], UsersPinCredential.prototype, "mustReset", 2);
|
|
230
|
-
__decorateClass([field({
|
|
231
|
-
type: "datetime",
|
|
232
|
-
nullable: true
|
|
233
|
-
})], UsersPinCredential.prototype, "rotatedAt", 2);
|
|
234
|
-
__decorateClass([field({
|
|
235
|
-
type: "text",
|
|
236
|
-
nullable: true
|
|
237
|
-
})], UsersPinCredential.prototype, "rotatedBy", 2);
|
|
238
|
-
UsersPinCredential = __decorateClass([smrt({
|
|
239
|
-
tableName: "users_pin_credentials",
|
|
240
|
-
sensitive: true,
|
|
241
|
-
api: false,
|
|
242
|
-
cli: false,
|
|
243
|
-
mcp: false
|
|
244
|
-
})], UsersPinCredential);
|
|
245
|
-
//#endregion
|
|
246
|
-
//#region src/collections/PinCredentialCollection.ts
|
|
247
|
-
var UsersPinCredentialCollection = class extends SmrtCollection {
|
|
248
|
-
static _itemClass = UsersPinCredential;
|
|
249
|
-
async findByUserId(userId) {
|
|
250
|
-
const [credential] = await this.list({
|
|
251
|
-
limit: 1,
|
|
252
|
-
where: { userId }
|
|
253
|
-
});
|
|
254
|
-
return credential ?? null;
|
|
255
|
-
}
|
|
256
|
-
/**
|
|
257
|
-
* Create or replace the one credential row for `userId`, bumping `version`
|
|
258
|
-
* on replace. Save conflicts from a concurrent set are retried once by
|
|
259
|
-
* re-reading; the last writer wins, which is the intended semantics for a
|
|
260
|
-
* credential rotation.
|
|
261
|
-
*/
|
|
262
|
-
async upsertForUser(userId, write) {
|
|
263
|
-
for (let attempt = 0; attempt < 2; attempt++) {
|
|
264
|
-
const existing = await this.findByUserId(userId);
|
|
265
|
-
if (!existing) {
|
|
266
|
-
const created = await this.create({
|
|
267
|
-
userId,
|
|
268
|
-
pinHash: write.pinHash,
|
|
269
|
-
mustReset: write.mustReset,
|
|
270
|
-
rotatedAt: write.rotatedAt,
|
|
271
|
-
rotatedBy: write.rotatedBy,
|
|
272
|
-
version: 1
|
|
273
|
-
});
|
|
274
|
-
try {
|
|
275
|
-
await created.save();
|
|
276
|
-
return created;
|
|
277
|
-
} catch (error) {
|
|
278
|
-
if (attempt === 0) continue;
|
|
279
|
-
throw error;
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
existing.pinHash = write.pinHash;
|
|
283
|
-
existing.mustReset = write.mustReset;
|
|
284
|
-
existing.rotatedAt = write.rotatedAt;
|
|
285
|
-
existing.rotatedBy = write.rotatedBy;
|
|
286
|
-
existing.version = (existing.version ?? 0) + 1;
|
|
287
|
-
try {
|
|
288
|
-
await existing.save();
|
|
289
|
-
return existing;
|
|
290
|
-
} catch (error) {
|
|
291
|
-
if (attempt === 0) continue;
|
|
292
|
-
throw error;
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
throw new Error("Unable to persist PIN credential.");
|
|
296
|
-
}
|
|
297
|
-
async deleteByUserId(userId) {
|
|
298
|
-
const existing = await this.findByUserId(userId);
|
|
299
|
-
if (!existing) return false;
|
|
300
|
-
await existing.delete();
|
|
301
|
-
return true;
|
|
302
|
-
}
|
|
303
|
-
};
|
|
304
|
-
//#endregion
|
|
305
|
-
//#region src/services/DeviceCredentialService.ts
|
|
306
|
-
var logger = createLogger({ level: "info" });
|
|
307
|
-
var DEFAULT_DEVICE_PERSON_IDLE_SECONDS = 480 * 60;
|
|
308
|
-
var DEFAULT_PIN_MANAGE_PERMISSION = "users.pin.manage";
|
|
309
|
-
var PIN_LOGIN_KIND = "pin";
|
|
310
|
-
var PIN_PERMISSION_DEFINITIONS = [{
|
|
311
|
-
slug: DEFAULT_PIN_MANAGE_PERMISSION,
|
|
312
|
-
category: "users",
|
|
313
|
-
name: "Manage device PINs",
|
|
314
|
-
description: "Set, reset, or clear another person's device PIN"
|
|
315
|
-
}];
|
|
316
|
-
var pinPermissionsRegistered = false;
|
|
317
|
-
function ensurePinPermissionsRegistered() {
|
|
318
|
-
if (pinPermissionsRegistered) return;
|
|
319
|
-
pinPermissionsRegistered = true;
|
|
320
|
-
registerPermissionDefinitions(PIN_PERMISSION_DEFINITIONS);
|
|
321
|
-
}
|
|
322
|
-
var DeviceCredentialError = class extends InvalidCredentialsError {
|
|
323
|
-
constructor(message = "Invalid credentials.") {
|
|
324
|
-
super(message);
|
|
325
|
-
this.name = "DeviceCredentialError";
|
|
326
|
-
}
|
|
327
|
-
};
|
|
328
|
-
var DeviceCredentialForbiddenError = class extends Error {
|
|
329
|
-
constructor(message = "Not permitted to manage this credential.") {
|
|
330
|
-
super(message);
|
|
331
|
-
this.name = "DeviceCredentialForbiddenError";
|
|
332
|
-
}
|
|
333
|
-
};
|
|
334
|
-
var DeviceCredentialPolicyError = class extends Error {
|
|
335
|
-
constructor(message) {
|
|
336
|
-
super(message);
|
|
337
|
-
this.name = "DeviceCredentialPolicyError";
|
|
338
|
-
}
|
|
339
|
-
};
|
|
340
|
-
var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
|
|
341
|
-
var DEFAULT_SCRYPT = {
|
|
342
|
-
N: 2 ** 15,
|
|
343
|
-
r: 8,
|
|
344
|
-
p: 1
|
|
345
|
-
};
|
|
346
|
-
var hashPin = hashSecret;
|
|
347
|
-
var verifyPinHash = verifySecretHash;
|
|
348
|
-
function isTrivialPin(pin) {
|
|
349
|
-
if (/^(\d)\1+$/u.test(pin)) return true;
|
|
350
|
-
let ascending = true;
|
|
351
|
-
let descending = true;
|
|
352
|
-
for (let i = 1; i < pin.length; i++) {
|
|
353
|
-
const diff = pin.charCodeAt(i) - pin.charCodeAt(i - 1);
|
|
354
|
-
if (diff !== 1) ascending = false;
|
|
355
|
-
if (diff !== -1) descending = false;
|
|
356
|
-
}
|
|
357
|
-
return ascending || descending;
|
|
358
|
-
}
|
|
359
|
-
var PinVerifier = class {
|
|
360
|
-
constructor(credentials, pepper, dummyHash) {
|
|
361
|
-
this.credentials = credentials;
|
|
362
|
-
this.pepper = pepper;
|
|
363
|
-
this.dummyHash = dummyHash;
|
|
364
|
-
}
|
|
365
|
-
credentials;
|
|
366
|
-
pepper;
|
|
367
|
-
dummyHash;
|
|
368
|
-
kind = "pin";
|
|
369
|
-
subjectKey(input) {
|
|
370
|
-
return input.userId;
|
|
371
|
-
}
|
|
372
|
-
async verify(input) {
|
|
373
|
-
const credential = UUID_PATTERN.test(input.userId) ? await this.credentials.findByUserId(input.userId) : null;
|
|
374
|
-
const encoded = credential?.pinHash || this.dummyHash;
|
|
375
|
-
if (!await verifyPinHash(input.pin, this.pepper, encoded) || !credential) return null;
|
|
376
|
-
const { userId, pinHash } = credential;
|
|
377
|
-
return {
|
|
378
|
-
userId,
|
|
379
|
-
stillValid: async () => (await this.credentials.findByUserId(userId))?.pinHash === pinHash
|
|
380
|
-
};
|
|
381
|
-
}
|
|
382
|
-
};
|
|
383
|
-
var DeviceCredentialService = class DeviceCredentialService {
|
|
384
|
-
options;
|
|
385
|
-
personIdleSeconds;
|
|
386
|
-
personMaxSeconds;
|
|
387
|
-
singleOccupant;
|
|
388
|
-
deviceAuthMethods;
|
|
389
|
-
managePermission;
|
|
390
|
-
pinPolicy;
|
|
391
|
-
sessionService;
|
|
392
|
-
/**
|
|
393
|
-
* Resolves *other* sessions (the device bearer, an actor) without touching
|
|
394
|
-
* their expiry: `sessionService` auto-extends with the person idle timeout,
|
|
395
|
-
* which must never be applied to a device session with its own lifetime.
|
|
396
|
-
*/
|
|
397
|
-
readonlySessionService;
|
|
398
|
-
memberships;
|
|
399
|
-
users;
|
|
400
|
-
pinCredentials;
|
|
401
|
-
limiter;
|
|
402
|
-
pinVerifier;
|
|
403
|
-
constructor(options) {
|
|
404
|
-
if (typeof options.assertEnrolledDevice !== "function") throw new Error("DeviceCredentialService requires an assertEnrolledDevice hook.");
|
|
405
|
-
this.options = options;
|
|
406
|
-
ensurePinPermissionsRegistered();
|
|
407
|
-
this.personIdleSeconds = options.personIdleSeconds ?? 28800;
|
|
408
|
-
this.personMaxSeconds = options.personMaxSeconds ?? null;
|
|
409
|
-
for (const [name, value] of [["personIdleSeconds", this.personIdleSeconds], ["personMaxSeconds", this.personMaxSeconds]]) if (value !== null && !(Number.isFinite(value) && value > 0)) throw new Error(`DeviceCredentialService ${name} must be a positive number.`);
|
|
410
|
-
this.singleOccupant = options.singleOccupant ?? true;
|
|
411
|
-
this.deviceAuthMethods = new Set(options.deviceAuthMethods ?? ["terminal"]);
|
|
412
|
-
this.managePermission = options.managePermission ?? "users.pin.manage";
|
|
413
|
-
this.pinPolicy = {
|
|
414
|
-
minLength: options.pin?.minLength ?? 4,
|
|
415
|
-
maxLength: options.pin?.maxLength ?? 8,
|
|
416
|
-
rejectTrivial: options.pin?.rejectTrivial ?? true,
|
|
417
|
-
pepper: options.pin?.pepper ?? "",
|
|
418
|
-
scrypt: {
|
|
419
|
-
...DEFAULT_SCRYPT,
|
|
420
|
-
...options.pin?.scrypt
|
|
421
|
-
}
|
|
422
|
-
};
|
|
423
|
-
}
|
|
424
|
-
static async create(options) {
|
|
425
|
-
const service = new DeviceCredentialService(options);
|
|
426
|
-
await service.initialize();
|
|
427
|
-
return service;
|
|
428
|
-
}
|
|
429
|
-
async initialize() {
|
|
430
|
-
this.sessionService = await SessionService.create({
|
|
431
|
-
...this.options,
|
|
432
|
-
autoExtend: true,
|
|
433
|
-
cookieName: this.options.sessionCookieName,
|
|
434
|
-
defaultTTL: this.personIdleSeconds
|
|
435
|
-
});
|
|
436
|
-
this.readonlySessionService = await SessionService.create({
|
|
437
|
-
...this.options,
|
|
438
|
-
autoExtend: false,
|
|
439
|
-
cookieName: this.options.sessionCookieName
|
|
440
|
-
});
|
|
441
|
-
this.memberships = await MembershipCollection.create(withoutListBounds(this.options));
|
|
442
|
-
this.users = await UserCollection.create(this.options);
|
|
443
|
-
this.pinCredentials = await UsersPinCredentialCollection.create(this.options);
|
|
444
|
-
this.limiter = this.options.loginLimiter ?? await LoginAttemptLimiter.create({
|
|
445
|
-
...this.options,
|
|
446
|
-
...this.options.limiter
|
|
447
|
-
});
|
|
448
|
-
if (!this.pinPolicy.pepper) logger.warn("DeviceCredentialService: no pin.pepper configured. PIN hashes are only as strong as scrypt over a 4-8 digit space if the table leaks; set a server-side pepper in production.");
|
|
449
|
-
const dummy = await hashPin(randomBytes(8).toString("hex"), this.pinPolicy.pepper, this.pinPolicy.scrypt);
|
|
450
|
-
this.pinVerifier = new PinVerifier(this.pinCredentials, this.pinPolicy.pepper, dummy);
|
|
451
|
-
}
|
|
452
|
-
/** The reference PIN verifier bound to this service's policy. */
|
|
453
|
-
get pin() {
|
|
454
|
-
return this.pinVerifier;
|
|
455
|
-
}
|
|
456
|
-
/** The limiter in use (shared or private), for hosts that add verifiers. */
|
|
457
|
-
get loginLimiter() {
|
|
458
|
-
return this.limiter;
|
|
459
|
-
}
|
|
460
|
-
/** PIN sign-in: {@link signIn} with the built-in {@link PinVerifier}. */
|
|
461
|
-
async signInWithPin(input) {
|
|
462
|
-
return this.signIn(this.pinVerifier, input);
|
|
463
|
-
}
|
|
464
|
-
/**
|
|
465
|
-
* Generic sign-in pipeline. See the module docs for the sequence. Throws
|
|
466
|
-
* {@link DeviceCredentialError} for every refusal that is not a rate limit
|
|
467
|
-
* (not a device, inactive device, unknown user, wrong credential, no
|
|
468
|
-
* membership) and {@link LoginRateLimitError} when the budget is exhausted.
|
|
469
|
-
*/
|
|
470
|
-
async signIn(verifier, input) {
|
|
471
|
-
const { device } = await this.resolveEnrolledDevice(input.deviceToken);
|
|
472
|
-
if (!device) throw new DeviceCredentialError();
|
|
473
|
-
const lease = await this.limiter.reserve({
|
|
474
|
-
kind: String(verifier.kind),
|
|
475
|
-
subject: verifier.subjectKey(input),
|
|
476
|
-
source: device.user.id ?? void 0,
|
|
477
|
-
metadata: { tenantId: device.tenantId ?? null }
|
|
478
|
-
});
|
|
479
|
-
if (!lease.allowed) throw new LoginRateLimitError(lease);
|
|
480
|
-
let verified = null;
|
|
481
|
-
let credentialFailed = false;
|
|
482
|
-
let mintedSessionId = null;
|
|
483
|
-
try {
|
|
484
|
-
verified = await verifier.verify(input, { device });
|
|
485
|
-
if (!verified) {
|
|
486
|
-
credentialFailed = true;
|
|
487
|
-
throw new DeviceCredentialError();
|
|
488
|
-
}
|
|
489
|
-
if (!(await this.users.get(verified.userId))?.isActive()) {
|
|
490
|
-
credentialFailed = true;
|
|
491
|
-
throw new DeviceCredentialError();
|
|
492
|
-
}
|
|
493
|
-
const tenantId = device.tenantId;
|
|
494
|
-
if (tenantId) {
|
|
495
|
-
if (!(await this.memberships.findByUserAndTenant(verified.userId, tenantId))?.isActive()) {
|
|
496
|
-
credentialFailed = true;
|
|
497
|
-
throw new DeviceCredentialError();
|
|
498
|
-
}
|
|
499
|
-
}
|
|
500
|
-
let mustReset = false;
|
|
501
|
-
if (verifier.kind === "pin") mustReset = (await this.pinCredentials.findByUserId(verified.userId))?.mustReset ?? false;
|
|
502
|
-
const permissionCeiling = mustReset ? [] : await this.resolveDeviceCeiling(device);
|
|
503
|
-
const now = Date.now();
|
|
504
|
-
const absoluteExpiresAt = this.personMaxSeconds === null ? null : new Date(now + this.personMaxSeconds * 1e3).toISOString();
|
|
505
|
-
const sessionId = await this.sessionService.createSession(verified.userId, tenantId ?? void 0, {
|
|
506
|
-
ttl: this.personIdleSeconds,
|
|
507
|
-
ipAddress: input.ipAddress,
|
|
508
|
-
userAgent: input.userAgent,
|
|
509
|
-
authMethod: verifier.kind,
|
|
510
|
-
parentSessionId: device.sessionId,
|
|
511
|
-
data: {
|
|
512
|
-
deviceUserId: device.user.id,
|
|
513
|
-
[SESSION_DATA_KEYS.idleSeconds]: this.personIdleSeconds,
|
|
514
|
-
...absoluteExpiresAt && { [SESSION_DATA_KEYS.absoluteExpiresAt]: absoluteExpiresAt },
|
|
515
|
-
...permissionCeiling && { [SESSION_DATA_KEYS.permissionCeiling]: permissionCeiling }
|
|
516
|
-
}
|
|
517
|
-
});
|
|
518
|
-
mintedSessionId = sessionId;
|
|
519
|
-
if (verified.stillValid && !await verified.stillValid()) {
|
|
520
|
-
credentialFailed = true;
|
|
521
|
-
throw new DeviceCredentialError();
|
|
522
|
-
}
|
|
523
|
-
if (this.singleOccupant) {
|
|
524
|
-
await this.sessionService.destroyChildSessions(device.sessionId, { exceptSessionId: sessionId });
|
|
525
|
-
if (!await this.readonlySessionService.getParentSessionId(sessionId)) throw new DeviceCredentialError();
|
|
526
|
-
}
|
|
527
|
-
await lease.succeed();
|
|
528
|
-
return {
|
|
529
|
-
sessionId,
|
|
530
|
-
userId: verified.userId,
|
|
531
|
-
tenantId: tenantId ?? null,
|
|
532
|
-
authMethod: verifier.kind,
|
|
533
|
-
expiresAt: new Date(Math.min(now + this.personIdleSeconds * 1e3, absoluteExpiresAt ? Date.parse(absoluteExpiresAt) : Infinity)).toISOString(),
|
|
534
|
-
absoluteExpiresAt,
|
|
535
|
-
mustReset
|
|
536
|
-
};
|
|
537
|
-
} catch (error) {
|
|
538
|
-
if (credentialFailed) await lease.fail().catch(() => void 0);
|
|
539
|
-
else await lease.release().catch(() => void 0);
|
|
540
|
-
if (mintedSessionId) await this.sessionService.destroySession(mintedSessionId).catch(() => void 0);
|
|
541
|
-
throw error;
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
/**
|
|
545
|
-
* Sign the person out. Ends only the person's layered session; the device
|
|
546
|
-
* session is untouched. Returns false for anything that is not a live
|
|
547
|
-
* layered session (never reveals which).
|
|
548
|
-
*/
|
|
549
|
-
async signOut(personToken) {
|
|
550
|
-
const token = personToken?.trim();
|
|
551
|
-
if (!token) return false;
|
|
552
|
-
if (!await this.readonlySessionService.getParentSessionId(token)) return false;
|
|
553
|
-
return this.sessionService.destroySession(token);
|
|
554
|
-
}
|
|
555
|
-
/**
|
|
556
|
-
* Resolve a person's bearer. Returns null unless it is a live layered
|
|
557
|
-
* session whose parent is still an enrolled device — the host's
|
|
558
|
-
* `assertEnrolledDevice` is consulted on every call, and a person session
|
|
559
|
-
* on a device that fails it is revoked. Hosts that resolve person bearers
|
|
560
|
-
* through their own `SessionService` instead must revoke the device's
|
|
561
|
-
* bearer session when they un-enrol it.
|
|
562
|
-
*/
|
|
563
|
-
async loadPersonSession(personToken) {
|
|
564
|
-
const token = personToken?.trim();
|
|
565
|
-
if (!token) return null;
|
|
566
|
-
const parentSessionId = await this.readonlySessionService.getParentSessionId(token);
|
|
567
|
-
if (!parentSessionId) return null;
|
|
568
|
-
const enrolled = await this.resolveEnrolledDevice(parentSessionId);
|
|
569
|
-
if (!enrolled.device) {
|
|
570
|
-
if (enrolled.unenrolled) await this.sessionService.destroySession(token).catch(() => false);
|
|
571
|
-
return null;
|
|
572
|
-
}
|
|
573
|
-
const context = await this.sessionService.loadSessionContext(token);
|
|
574
|
-
if (!context?.parent) return null;
|
|
575
|
-
return context;
|
|
576
|
-
}
|
|
577
|
-
/**
|
|
578
|
-
* Resolve any bearer or cookie session id to its context without applying
|
|
579
|
-
* this service's person TTL to it — for handlers that need the acting
|
|
580
|
-
* session (`setPin` and friends) when the host's hook has not already
|
|
581
|
-
* resolved it into `locals`. A person (layered) session goes through
|
|
582
|
-
* {@link loadPersonSession}: the device's enrollment is re-checked, and
|
|
583
|
-
* resolving it is activity, so it slides by its own idle timeout.
|
|
584
|
-
*/
|
|
585
|
-
async resolveActor(sessionToken) {
|
|
586
|
-
const token = sessionToken?.trim();
|
|
587
|
-
if (!token) return null;
|
|
588
|
-
if (await this.readonlySessionService.getParentSessionId(token)) return this.loadPersonSession(token);
|
|
589
|
-
return this.readonlySessionService.loadSessionContext(token);
|
|
590
|
-
}
|
|
591
|
-
/**
|
|
592
|
-
* A person sets or changes their own PIN, or an administrator sets one for
|
|
593
|
-
* them. A person acting from a PIN session must supply their current PIN
|
|
594
|
-
* (checked through the limiter, so it cannot be used as an oracle); a
|
|
595
|
-
* person acting from any first-class session (browser, mobile) may set it
|
|
596
|
-
* outright, and so may an administrator holding `managePermission`.
|
|
597
|
-
*/
|
|
598
|
-
async setPin(input) {
|
|
599
|
-
this.assertPinPolicy(input.pin);
|
|
600
|
-
const self = input.actor.user.id === input.userId;
|
|
601
|
-
if (!self) await this.assertCanManage(input.actor, input.userId);
|
|
602
|
-
let endResetSessions = false;
|
|
603
|
-
if (self && (input.actor.authMethod === "pin" || input.actor.parent)) {
|
|
604
|
-
const existing = await this.pinCredentials.findByUserId(input.userId);
|
|
605
|
-
if (existing) {
|
|
606
|
-
if (!input.currentPin) throw new DeviceCredentialForbiddenError();
|
|
607
|
-
const lease = await this.limiter.reserve({
|
|
608
|
-
kind: "pin",
|
|
609
|
-
subject: input.userId,
|
|
610
|
-
source: input.actor.parent?.userId ?? input.ipAddress,
|
|
611
|
-
metadata: { purpose: "change-pin" }
|
|
612
|
-
});
|
|
613
|
-
if (!lease.allowed) throw new LoginRateLimitError(lease);
|
|
614
|
-
if (!await verifyPinHash(input.currentPin, this.pinPolicy.pepper, existing.pinHash)) {
|
|
615
|
-
await lease.fail().catch(() => void 0);
|
|
616
|
-
throw new DeviceCredentialError();
|
|
617
|
-
}
|
|
618
|
-
await lease.succeed().catch(() => void 0);
|
|
619
|
-
endResetSessions = existing.mustReset;
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
await this.writePin(input.userId, input.pin, {
|
|
623
|
-
mustReset: false,
|
|
624
|
-
rotatedBy: self ? "self" : input.actor.user.id ?? "admin"
|
|
625
|
-
});
|
|
626
|
-
await this.sessionService.destroyUserSessionsByAuthMethod(input.userId, "pin", { exceptSessionId: self && !endResetSessions ? input.actor.sessionId : void 0 });
|
|
627
|
-
await this.limiter.recordManagement({
|
|
628
|
-
kind: "pin",
|
|
629
|
-
subject: input.userId,
|
|
630
|
-
source: input.ipAddress,
|
|
631
|
-
metadata: {
|
|
632
|
-
action: "set",
|
|
633
|
-
self,
|
|
634
|
-
...self ? {} : { actorId: input.actor.user.id }
|
|
635
|
-
}
|
|
636
|
-
});
|
|
637
|
-
}
|
|
638
|
-
/**
|
|
639
|
-
* Administrative reset: writes a temporary PIN the person must change on
|
|
640
|
-
* next use, and revokes every live PIN session the person holds.
|
|
641
|
-
*/
|
|
642
|
-
async resetPin(input) {
|
|
643
|
-
await this.assertCanManage(input.actor, input.userId);
|
|
644
|
-
this.assertPinPolicy(input.pin);
|
|
645
|
-
await this.writePin(input.userId, input.pin, {
|
|
646
|
-
mustReset: true,
|
|
647
|
-
rotatedBy: input.actor.user.id ?? "admin"
|
|
648
|
-
});
|
|
649
|
-
const revokedSessions = await this.sessionService.destroyUserSessionsByAuthMethod(input.userId, "pin");
|
|
650
|
-
await this.limiter.recordManagement({
|
|
651
|
-
kind: "pin",
|
|
652
|
-
subject: input.userId,
|
|
653
|
-
source: input.ipAddress,
|
|
654
|
-
metadata: {
|
|
655
|
-
action: "reset",
|
|
656
|
-
actorId: input.actor.user.id,
|
|
657
|
-
revokedSessions
|
|
658
|
-
}
|
|
659
|
-
});
|
|
660
|
-
return { revokedSessions };
|
|
661
|
-
}
|
|
662
|
-
/** Remove a person's PIN entirely and revoke their live PIN sessions. */
|
|
663
|
-
async clearPin(input) {
|
|
664
|
-
const self = input.actor.user.id === input.userId;
|
|
665
|
-
if (!self || input.actor.authMethod === "pin" || input.actor.parent) await this.assertCanManage(input.actor, input.userId);
|
|
666
|
-
await this.pinCredentials.deleteByUserId(input.userId);
|
|
667
|
-
const revokedSessions = await this.sessionService.destroyUserSessionsByAuthMethod(input.userId, "pin");
|
|
668
|
-
await this.limiter.recordManagement({
|
|
669
|
-
kind: "pin",
|
|
670
|
-
subject: input.userId,
|
|
671
|
-
source: input.ipAddress,
|
|
672
|
-
metadata: {
|
|
673
|
-
action: "clear",
|
|
674
|
-
self,
|
|
675
|
-
...self ? {} : { actorId: input.actor.user.id },
|
|
676
|
-
revokedSessions
|
|
677
|
-
}
|
|
678
|
-
});
|
|
679
|
-
return { revokedSessions };
|
|
680
|
-
}
|
|
681
|
-
/** Whether the person has a PIN enrolled (for admin UIs; never for login responses). */
|
|
682
|
-
async hasPin(userId) {
|
|
683
|
-
return await this.pinCredentials.findByUserId(userId) !== null;
|
|
684
|
-
}
|
|
685
|
-
async resolveEnrolledDevice(deviceToken) {
|
|
686
|
-
const refused = { device: null };
|
|
687
|
-
const token = deviceToken?.trim();
|
|
688
|
-
if (!token) return refused;
|
|
689
|
-
const device = await this.readonlySessionService.loadSessionContext(token);
|
|
690
|
-
if (!device) return refused;
|
|
691
|
-
if (device.parent) return refused;
|
|
692
|
-
if (!this.deviceAuthMethods.has(String(device.authMethod ?? ""))) return refused;
|
|
693
|
-
try {
|
|
694
|
-
if (await this.options.assertEnrolledDevice(device) === false) return {
|
|
695
|
-
device: null,
|
|
696
|
-
unenrolled: true
|
|
697
|
-
};
|
|
698
|
-
} catch {
|
|
699
|
-
return refused;
|
|
700
|
-
}
|
|
701
|
-
return { device };
|
|
702
|
-
}
|
|
703
|
-
async resolveDeviceCeiling(device) {
|
|
704
|
-
if (!this.options.deviceCeiling) return null;
|
|
705
|
-
const ceiling = await this.options.deviceCeiling(device);
|
|
706
|
-
if (ceiling === null || ceiling === void 0) return null;
|
|
707
|
-
if (!Array.isArray(ceiling) || ceiling.some((slug) => typeof slug !== "string")) throw new Error("DeviceCredentialService deviceCeiling must resolve to an array of permission slugs or null.");
|
|
708
|
-
return [...new Set(ceiling)];
|
|
709
|
-
}
|
|
710
|
-
async assertCanManage(actor, targetUserId) {
|
|
711
|
-
if (actor.authMethod === "pin" || actor.parent) throw new DeviceCredentialForbiddenError();
|
|
712
|
-
if (!actor.permissions.includes(this.managePermission)) throw new DeviceCredentialForbiddenError();
|
|
713
|
-
const active = actor.tenantId && UUID_PATTERN.test(targetUserId) ? (await withSystemContext(() => this.memberships.findByUser(targetUserId))).filter((membership) => membership.isActive()) : [];
|
|
714
|
-
if (active.length === 0 || active.some((membership) => membership.tenantId !== actor.tenantId)) throw new DeviceCredentialForbiddenError();
|
|
715
|
-
}
|
|
716
|
-
assertPinPolicy(pin) {
|
|
717
|
-
if (typeof pin !== "string" || !/^\d+$/u.test(pin)) throw new DeviceCredentialPolicyError("PIN must contain only digits.");
|
|
718
|
-
if (pin.length < this.pinPolicy.minLength || pin.length > this.pinPolicy.maxLength) throw new DeviceCredentialPolicyError(`PIN must be ${this.pinPolicy.minLength}\u2013${this.pinPolicy.maxLength} digits.`);
|
|
719
|
-
if (this.pinPolicy.rejectTrivial && isTrivialPin(pin)) throw new DeviceCredentialPolicyError("PIN must not be a repeated or sequential run of digits.");
|
|
720
|
-
}
|
|
721
|
-
async writePin(userId, pin, meta) {
|
|
722
|
-
if (!await this.users.get(userId)) throw new DeviceCredentialForbiddenError("Unknown user.");
|
|
723
|
-
const pinHash = await hashPin(pin, this.pinPolicy.pepper, this.pinPolicy.scrypt);
|
|
724
|
-
return this.pinCredentials.upsertForUser(userId, {
|
|
725
|
-
pinHash,
|
|
726
|
-
mustReset: meta.mustReset,
|
|
727
|
-
rotatedAt: /* @__PURE__ */ new Date(),
|
|
728
|
-
rotatedBy: meta.rotatedBy
|
|
729
|
-
});
|
|
730
|
-
}
|
|
731
|
-
};
|
|
732
|
-
//#endregion
|
|
733
|
-
//#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js
|
|
734
|
-
var encoder = new TextEncoder();
|
|
735
|
-
var decoder = new TextDecoder();
|
|
736
|
-
var strictDecoder = new TextDecoder("utf-8", { fatal: !0 });
|
|
737
|
-
function concat(...buffers) {
|
|
738
|
-
const size = buffers.reduce((acc, { length }) => acc + length, 0), buf = new Uint8Array(size);
|
|
739
|
-
let i = 0;
|
|
740
|
-
for (const buffer of buffers) buf.set(buffer, i), i += buffer.length;
|
|
741
|
-
return buf;
|
|
742
|
-
}
|
|
743
|
-
var NON_ASCII = /[^\x00-\x7f]/;
|
|
744
|
-
function encode$1(string) {
|
|
745
|
-
if (typeof string == "string" && string.length >= 128) {
|
|
746
|
-
if (NON_ASCII.test(string)) throw new TypeError("non-ASCII string encountered in encode()");
|
|
747
|
-
return encoder.encode(string);
|
|
748
|
-
}
|
|
749
|
-
const bytes = new Uint8Array(string.length);
|
|
750
|
-
for (let i = 0; i < string.length; i++) {
|
|
751
|
-
const code = string.charCodeAt(i);
|
|
752
|
-
if (code > 127) throw new TypeError("non-ASCII string encountered in encode()");
|
|
753
|
-
bytes[i] = code;
|
|
754
|
-
}
|
|
755
|
-
return bytes;
|
|
756
|
-
}
|
|
757
|
-
function encodeBase64(input, url = !1) {
|
|
758
|
-
if (Uint8Array.prototype.toBase64) return input.toBase64({
|
|
759
|
-
alphabet: url ? "base64url" : "base64",
|
|
760
|
-
omitPadding: url
|
|
761
|
-
});
|
|
762
|
-
const CHUNK_SIZE = 32768, arr = [];
|
|
763
|
-
for (let i = 0; i < input.length; i += CHUNK_SIZE) arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
|
|
764
|
-
const encoded = btoa(arr.join(""));
|
|
765
|
-
return url ? encoded.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_") : encoded;
|
|
766
|
-
}
|
|
767
|
-
function decodeBase64(encoded, url = !1) {
|
|
768
|
-
if (Uint8Array.fromBase64) return Uint8Array.fromBase64(encoded, { alphabet: url ? "base64url" : "base64" });
|
|
769
|
-
if (url) {
|
|
770
|
-
if (encoded.includes("+") || encoded.includes("/")) throw new TypeError("Invalid base64url");
|
|
771
|
-
encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
|
|
772
|
-
}
|
|
773
|
-
const binary = atob(encoded), bytes = new Uint8Array(binary.length);
|
|
774
|
-
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
775
|
-
return bytes;
|
|
776
|
-
}
|
|
777
|
-
//#endregion
|
|
778
|
-
//#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/errors.js
|
|
779
|
-
var errors_exports = /* @__PURE__ */ __exportAll({
|
|
780
|
-
JOSEAlgNotAllowed: () => JOSEAlgNotAllowed,
|
|
781
|
-
JOSEError: () => JOSEError,
|
|
782
|
-
JOSENotSupported: () => JOSENotSupported,
|
|
783
|
-
JWEDecryptionFailed: () => JWEDecryptionFailed,
|
|
784
|
-
JWEInvalid: () => JWEInvalid,
|
|
785
|
-
JWKInvalid: () => JWKInvalid,
|
|
786
|
-
JWKSInvalid: () => JWKSInvalid,
|
|
787
|
-
JWKSMultipleMatchingKeys: () => JWKSMultipleMatchingKeys,
|
|
788
|
-
JWKSNoMatchingKey: () => JWKSNoMatchingKey,
|
|
789
|
-
JWKSTimeout: () => JWKSTimeout,
|
|
790
|
-
JWSInvalid: () => JWSInvalid,
|
|
791
|
-
JWSSignatureVerificationFailed: () => JWSSignatureVerificationFailed,
|
|
792
|
-
JWTClaimValidationFailed: () => JWTClaimValidationFailed,
|
|
793
|
-
JWTExpired: () => JWTExpired,
|
|
794
|
-
JWTInvalid: () => JWTInvalid
|
|
795
|
-
});
|
|
796
|
-
var JOSEError = class extends Error {
|
|
797
|
-
static code = "ERR_JOSE_GENERIC";
|
|
798
|
-
code = "ERR_JOSE_GENERIC";
|
|
799
|
-
constructor(message, options) {
|
|
800
|
-
super(message, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);
|
|
801
|
-
}
|
|
802
|
-
};
|
|
803
|
-
var JWTClaimValidationFailed = class extends JOSEError {
|
|
804
|
-
static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
|
|
805
|
-
code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
|
|
806
|
-
claim;
|
|
807
|
-
reason;
|
|
808
|
-
payload;
|
|
809
|
-
constructor(message, payload, claim = "unspecified", reason = "unspecified") {
|
|
810
|
-
super(message, { cause: {
|
|
811
|
-
claim,
|
|
812
|
-
reason,
|
|
813
|
-
payload
|
|
814
|
-
} }), this.claim = claim, this.reason = reason, this.payload = payload;
|
|
815
|
-
}
|
|
816
|
-
};
|
|
817
|
-
var JWTExpired = class extends JOSEError {
|
|
818
|
-
static code = "ERR_JWT_EXPIRED";
|
|
819
|
-
code = "ERR_JWT_EXPIRED";
|
|
820
|
-
claim;
|
|
821
|
-
reason;
|
|
822
|
-
payload;
|
|
823
|
-
constructor(message, payload, claim = "unspecified", reason = "unspecified") {
|
|
824
|
-
super(message, { cause: {
|
|
825
|
-
claim,
|
|
826
|
-
reason,
|
|
827
|
-
payload
|
|
828
|
-
} }), this.claim = claim, this.reason = reason, this.payload = payload;
|
|
829
|
-
}
|
|
830
|
-
};
|
|
831
|
-
var JOSEAlgNotAllowed = class extends JOSEError {
|
|
832
|
-
static code = "ERR_JOSE_ALG_NOT_ALLOWED";
|
|
833
|
-
code = "ERR_JOSE_ALG_NOT_ALLOWED";
|
|
834
|
-
};
|
|
835
|
-
var JOSENotSupported = class extends JOSEError {
|
|
836
|
-
static code = "ERR_JOSE_NOT_SUPPORTED";
|
|
837
|
-
code = "ERR_JOSE_NOT_SUPPORTED";
|
|
838
|
-
};
|
|
839
|
-
var JWEDecryptionFailed = class extends JOSEError {
|
|
840
|
-
static code = "ERR_JWE_DECRYPTION_FAILED";
|
|
841
|
-
code = "ERR_JWE_DECRYPTION_FAILED";
|
|
842
|
-
constructor(message = "decryption operation failed", options) {
|
|
843
|
-
super(message, options);
|
|
844
|
-
}
|
|
845
|
-
};
|
|
846
|
-
var JWEInvalid = class extends JOSEError {
|
|
847
|
-
static code = "ERR_JWE_INVALID";
|
|
848
|
-
code = "ERR_JWE_INVALID";
|
|
849
|
-
};
|
|
850
|
-
var JWSInvalid = class extends JOSEError {
|
|
851
|
-
static code = "ERR_JWS_INVALID";
|
|
852
|
-
code = "ERR_JWS_INVALID";
|
|
853
|
-
};
|
|
854
|
-
var JWTInvalid = class extends JOSEError {
|
|
855
|
-
static code = "ERR_JWT_INVALID";
|
|
856
|
-
code = "ERR_JWT_INVALID";
|
|
857
|
-
};
|
|
858
|
-
var JWKInvalid = class extends JOSEError {
|
|
859
|
-
static code = "ERR_JWK_INVALID";
|
|
860
|
-
code = "ERR_JWK_INVALID";
|
|
861
|
-
};
|
|
862
|
-
var JWKSInvalid = class extends JOSEError {
|
|
863
|
-
static code = "ERR_JWKS_INVALID";
|
|
864
|
-
code = "ERR_JWKS_INVALID";
|
|
865
|
-
};
|
|
866
|
-
var JWKSNoMatchingKey = class extends JOSEError {
|
|
867
|
-
static code = "ERR_JWKS_NO_MATCHING_KEY";
|
|
868
|
-
code = "ERR_JWKS_NO_MATCHING_KEY";
|
|
869
|
-
constructor(message = "no applicable key found in the JSON Web Key Set", options) {
|
|
870
|
-
super(message, options);
|
|
871
|
-
}
|
|
872
|
-
};
|
|
873
|
-
var JWKSMultipleMatchingKeys = class extends JOSEError {
|
|
874
|
-
[Symbol.asyncIterator] = async function* () {};
|
|
875
|
-
static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
|
|
876
|
-
code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
|
|
877
|
-
constructor(message = "multiple matching keys found in the JSON Web Key Set", options) {
|
|
878
|
-
super(message, options);
|
|
879
|
-
}
|
|
880
|
-
};
|
|
881
|
-
var JWKSTimeout = class extends JOSEError {
|
|
882
|
-
static code = "ERR_JWKS_TIMEOUT";
|
|
883
|
-
code = "ERR_JWKS_TIMEOUT";
|
|
884
|
-
constructor(message = "request timed out", options) {
|
|
885
|
-
super(message, options);
|
|
886
|
-
}
|
|
887
|
-
};
|
|
888
|
-
var JWSSignatureVerificationFailed = class extends JOSEError {
|
|
889
|
-
static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
|
|
890
|
-
code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
|
|
891
|
-
constructor(message = "signature verification failed", options) {
|
|
892
|
-
super(message, options);
|
|
893
|
-
}
|
|
894
|
-
};
|
|
895
|
-
//#endregion
|
|
896
|
-
//#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/base64url.js
|
|
897
|
-
var invalid = "The input to be decoded is not correctly encoded.";
|
|
898
|
-
function decode(input) {
|
|
899
|
-
try {
|
|
900
|
-
return decodeBase64(typeof input == "string" ? input : decoder.decode(input), !0);
|
|
901
|
-
} catch (cause) {
|
|
902
|
-
throw new TypeError(invalid, { cause });
|
|
903
|
-
}
|
|
904
|
-
}
|
|
905
|
-
function encode(input) {
|
|
906
|
-
return encodeBase64(typeof input == "string" ? encoder.encode(input) : input, !0);
|
|
907
|
-
}
|
|
908
|
-
//#endregion
|
|
909
|
-
//#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/validate.js
|
|
910
|
-
function isObject(input) {
|
|
911
|
-
if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") return !1;
|
|
912
|
-
const prototype = Object.getPrototypeOf(input);
|
|
913
|
-
return prototype === null || Object.getPrototypeOf(prototype) === null;
|
|
914
|
-
}
|
|
915
|
-
function isJwkSet(input) {
|
|
916
|
-
return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject);
|
|
917
|
-
}
|
|
918
|
-
function isDisjoint(...headers) {
|
|
919
|
-
const parameters = /* @__PURE__ */ new Set();
|
|
920
|
-
for (const header of headers) if (header) for (const parameter of Object.keys(header)) {
|
|
921
|
-
if (parameters.has(parameter)) return !1;
|
|
922
|
-
parameters.add(parameter);
|
|
923
|
-
}
|
|
924
|
-
return !0;
|
|
925
|
-
}
|
|
926
|
-
function assertNotSet(value, name) {
|
|
927
|
-
if (value !== void 0) throw new TypeError(`${name} can only be called once`);
|
|
928
|
-
}
|
|
929
|
-
function decodeBase64url(value, label, ErrorClass) {
|
|
930
|
-
try {
|
|
931
|
-
return decode(value);
|
|
932
|
-
} catch {
|
|
933
|
-
throw new ErrorClass(`Failed to base64url decode the ${label}`);
|
|
934
|
-
}
|
|
935
|
-
}
|
|
936
|
-
function encodeBase64url(value, label, ErrorClass) {
|
|
937
|
-
try {
|
|
938
|
-
return encode$1(value);
|
|
939
|
-
} catch {
|
|
940
|
-
throw new ErrorClass(`The ${label} is not a valid base64url string`);
|
|
941
|
-
}
|
|
942
|
-
}
|
|
943
|
-
function parseJoseHeader(b64, ErrorClass, message) {
|
|
944
|
-
let parsed;
|
|
945
|
-
try {
|
|
946
|
-
parsed = JSON.parse(strictDecoder.decode(decode(b64)));
|
|
947
|
-
} catch {
|
|
948
|
-
throw new ErrorClass(message);
|
|
949
|
-
}
|
|
950
|
-
if (!isObject(parsed)) throw new ErrorClass(message);
|
|
951
|
-
return parsed;
|
|
952
|
-
}
|
|
953
|
-
var JWS_RECOGNIZED = {
|
|
954
|
-
__proto__: null,
|
|
955
|
-
b64: !0
|
|
956
|
-
};
|
|
957
|
-
function validateAlgorithms(option, algorithms) {
|
|
958
|
-
if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != "string"))) throw new TypeError(`"${option}" option must be an array of strings`);
|
|
959
|
-
return algorithms === void 0 ? void 0 : new Set(algorithms);
|
|
960
|
-
}
|
|
961
|
-
function validateCritDuplicates(Err, protectedHeader) {
|
|
962
|
-
const { crit } = protectedHeader ?? {};
|
|
963
|
-
if (Array.isArray(crit) && new Set(crit).size !== crit.length) throw new Err("\"crit\" (Critical) Header Parameter MUST NOT contain duplicate values");
|
|
964
|
-
}
|
|
965
|
-
function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
|
|
966
|
-
if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) throw new Err("\"crit\" (Critical) Header Parameter MUST be integrity protected");
|
|
967
|
-
if (!protectedHeader || protectedHeader.crit === void 0) return [];
|
|
968
|
-
if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != "string" || input.length === 0)) throw new Err("\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present");
|
|
969
|
-
const recognized = recognizedOption === void 0 ? recognizedDefault : {
|
|
970
|
-
__proto__: null,
|
|
971
|
-
...recognizedOption,
|
|
972
|
-
...recognizedDefault
|
|
973
|
-
};
|
|
974
|
-
for (const parameter of protectedHeader.crit) {
|
|
975
|
-
if (!(parameter in recognized)) throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
|
|
976
|
-
if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" is missing`);
|
|
977
|
-
if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0)) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
|
|
978
|
-
}
|
|
979
|
-
return protectedHeader.crit;
|
|
980
|
-
}
|
|
981
|
-
function validateB64(protectedHeader, extensions) {
|
|
982
|
-
if (extensions.includes("b64")) {
|
|
983
|
-
const b64 = protectedHeader.b64;
|
|
984
|
-
if (typeof b64 != "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
|
|
985
|
-
return b64;
|
|
986
|
-
}
|
|
987
|
-
return !0;
|
|
988
|
-
}
|
|
989
|
-
function serializeJoseHeader(Err, header) {
|
|
990
|
-
let serialized, parsed;
|
|
991
|
-
try {
|
|
992
|
-
serialized = JSON.stringify(header), parsed = JSON.parse(serialized);
|
|
993
|
-
} catch (cause) {
|
|
994
|
-
throw new Err("JOSE Header is not valid JSON", { cause });
|
|
995
|
-
}
|
|
996
|
-
if (!isObject(parsed)) throw new Err("JOSE Header is not a JSON object");
|
|
997
|
-
return [parsed, serialized];
|
|
998
|
-
}
|
|
999
|
-
//#endregion
|
|
1000
|
-
//#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/key.js
|
|
1001
|
-
var tag = (key) => key[Symbol.toStringTag];
|
|
1002
|
-
var jwkMatchesOp = (entry, key, usage) => {
|
|
1003
|
-
const { alg } = entry;
|
|
1004
|
-
if (key.use !== void 0) {
|
|
1005
|
-
const expected = usage === "sign" || usage === "verify" ? "sig" : "enc";
|
|
1006
|
-
if (key.use !== expected) throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
|
|
1007
|
-
}
|
|
1008
|
-
if (key.alg !== void 0 && key.alg !== alg) throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
|
|
1009
|
-
if (Array.isArray(key.key_ops)) {
|
|
1010
|
-
const expectedKeyOp = usage === "encrypt" || usage === "decrypt" ? entry.ops?.[usage === "encrypt" ? 0 : 1] : usage;
|
|
1011
|
-
if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp)) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
|
|
1012
|
-
}
|
|
1013
|
-
};
|
|
1014
|
-
async function prepareKey(entry, key, usage) {
|
|
1015
|
-
const { alg, secret } = entry, privateKey = usage === "decrypt" || usage === "sign";
|
|
1016
|
-
if (secret && key instanceof Uint8Array) return key;
|
|
1017
|
-
let normalized, keyObject;
|
|
1018
|
-
if (isObject(key)) {
|
|
1019
|
-
if (normalized = normalizeJwk(key), typeof normalized.kty != "string") throw invalidKeyType(alg, key, secret);
|
|
1020
|
-
if (!(secret ? normalized.kty === "oct" && typeof normalized.k == "string" : normalized.kty !== "oct" && (privateKey ? normalized.kty === "AKP" && typeof normalized.priv == "string" || typeof normalized.d == "string" : normalized.d === void 0 && normalized.priv === void 0))) throw new TypeError(secret ? "JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present" : `JSON Web Key for this operation must be a ${privateKey ? "private" : "public"} JWK`);
|
|
1021
|
-
if (jwkMatchesOp(entry, normalized, usage), normalized.kty === "oct") return decode(normalized.k);
|
|
1022
|
-
if (!Object.isFrozen(key)) {
|
|
1023
|
-
const { key_ops } = key;
|
|
1024
|
-
Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key);
|
|
1025
|
-
}
|
|
1026
|
-
} else {
|
|
1027
|
-
if (!isKeyLike(key)) throw invalidKeyType(alg, key, secret);
|
|
1028
|
-
const expectedType = secret ? "secret" : privateKey ? "private" : "public";
|
|
1029
|
-
if (key.type !== expectedType && (secret || [
|
|
1030
|
-
"secret",
|
|
1031
|
-
"public",
|
|
1032
|
-
"private"
|
|
1033
|
-
].includes(key.type))) throw new TypeError(`${tag(key)} instances must be of type "${expectedType}" for the ${alg} algorithm`);
|
|
1034
|
-
if (isCryptoKey(key)) return key;
|
|
1035
|
-
if (keyObject = key, keyObject.type === "secret") return keyObject.export();
|
|
1036
|
-
}
|
|
1037
|
-
cache ||= /* @__PURE__ */ new WeakMap();
|
|
1038
|
-
const cacheKey = key;
|
|
1039
|
-
let cached = cache.get(cacheKey);
|
|
1040
|
-
if (cached?.[alg]) return cached[alg];
|
|
1041
|
-
if (cached || cache.set(cacheKey, cached = {}), keyObject && typeof keyObject.toCryptoKey == "function") {
|
|
1042
|
-
const isPublic = keyObject.type === "public", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({
|
|
1043
|
-
crv,
|
|
1044
|
-
asymmetricKeyType: keyObject.asymmetricKeyType
|
|
1045
|
-
}) ?? entry.subtle;
|
|
1046
|
-
return cached[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]);
|
|
1047
|
-
}
|
|
1048
|
-
return normalized ??= keyObject.export({ format: "jwk" }), normalized.alg = alg, cached[alg] = await jwkToKey(entry, normalized);
|
|
1049
|
-
}
|
|
1050
|
-
var cache;
|
|
1051
|
-
var nist = {
|
|
1052
|
-
__proto__: null,
|
|
1053
|
-
prime256v1: "P-256",
|
|
1054
|
-
secp384r1: "P-384",
|
|
1055
|
-
secp521r1: "P-521"
|
|
1056
|
-
};
|
|
1057
|
-
var isCryptoKey = (key) => {
|
|
1058
|
-
if (key?.[Symbol.toStringTag] === "CryptoKey") return !0;
|
|
1059
|
-
try {
|
|
1060
|
-
return key instanceof CryptoKey;
|
|
1061
|
-
} catch {
|
|
1062
|
-
return !1;
|
|
1063
|
-
}
|
|
1064
|
-
};
|
|
1065
|
-
var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
|
|
1066
|
-
var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
|
|
1067
|
-
function message(msg, actual, ...types) {
|
|
1068
|
-
if (types.length > 2) {
|
|
1069
|
-
const last = types.pop();
|
|
1070
|
-
msg += `one of type ${types.join(", ")}, or ${last}.`;
|
|
1071
|
-
} else types.length === 2 ? msg += `one of type ${types[0]} or ${types[1]}.` : msg += `of type ${types[0]}.`;
|
|
1072
|
-
return actual == null ? msg += ` Received ${actual}` : typeof actual == "function" && actual.name ? msg += ` Received function ${actual.name}` : typeof actual == "object" && actual != null && actual.constructor?.name && (msg += ` Received an instance of ${actual.constructor.name}`), msg;
|
|
1073
|
-
}
|
|
1074
|
-
function invalidKeyType(alg, actual, secret) {
|
|
1075
|
-
const types = [
|
|
1076
|
-
"CryptoKey",
|
|
1077
|
-
"KeyObject",
|
|
1078
|
-
"JSON Web Key"
|
|
1079
|
-
];
|
|
1080
|
-
return secret && types.push("Uint8Array"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types));
|
|
1081
|
-
}
|
|
1082
|
-
var unusable = (name, prop = "algorithm.name") => /* @__PURE__ */ new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
|
|
1083
|
-
function checkUsage(key, usage) {
|
|
1084
|
-
if (usage && !key.usages.includes(usage)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
|
|
1085
|
-
}
|
|
1086
|
-
function checkModulusLength(alg, key) {
|
|
1087
|
-
const { modulusLength } = key.algorithm;
|
|
1088
|
-
if (typeof modulusLength != "number" || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
|
|
1089
|
-
}
|
|
1090
|
-
function checkCryptoKey(key, expected, usage) {
|
|
1091
|
-
const algorithm = key.algorithm;
|
|
1092
|
-
if (algorithm.name !== expected.name) throw unusable(expected.name);
|
|
1093
|
-
if (expected.hash && algorithm.hash?.name !== expected.hash) throw unusable(expected.hash, "algorithm.hash");
|
|
1094
|
-
if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve) throw unusable(expected.namedCurve, "algorithm.namedCurve");
|
|
1095
|
-
if (expected.length !== void 0 && algorithm.length !== expected.length) throw unusable(expected.length, "algorithm.length");
|
|
1096
|
-
checkUsage(key, usage);
|
|
1097
|
-
}
|
|
1098
|
-
function snapshotJwk(jwk) {
|
|
1099
|
-
return {
|
|
1100
|
-
__proto__: null,
|
|
1101
|
-
...jwk
|
|
1102
|
-
};
|
|
1103
|
-
}
|
|
1104
|
-
function normalizeJwk(jwk) {
|
|
1105
|
-
const normalized = snapshotJwk(jwk);
|
|
1106
|
-
if (normalized.ext !== void 0 && typeof normalized.ext != "boolean") throw new TypeError("\"ext\" (Extractable) Parameter must be a boolean");
|
|
1107
|
-
if (normalized.key_ops !== void 0) {
|
|
1108
|
-
const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0;
|
|
1109
|
-
if (!keyOps || keyOps.some((operation) => typeof operation != "string") || new Set(keyOps).size !== keyOps.length) throw new TypeError("\"key_ops\" (Key Operations) Parameter must be an array of unique strings");
|
|
1110
|
-
normalized.key_ops = keyOps;
|
|
1111
|
-
}
|
|
1112
|
-
return normalized;
|
|
1113
|
-
}
|
|
1114
|
-
async function jwkToKey(entry, jwk, extractable) {
|
|
1115
|
-
if (!entry.kty.includes(jwk.kty)) throw new JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
|
|
1116
|
-
const algorithm = entry.resolve?.({
|
|
1117
|
-
kty: jwk.kty,
|
|
1118
|
-
crv: jwk.crv
|
|
1119
|
-
}) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = {
|
|
1120
|
-
...jwk,
|
|
1121
|
-
ext: extractable ?? jwk.ext
|
|
1122
|
-
};
|
|
1123
|
-
return keyData.kty !== "AKP" && delete keyData.alg, delete keyData.use, crypto.subtle.importKey("jwk", keyData, algorithm, keyData.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);
|
|
1124
|
-
}
|
|
1125
|
-
async function rawKey(key, expected, usage, extractable = !1) {
|
|
1126
|
-
return key instanceof Uint8Array && (key = await crypto.subtle.importKey("raw", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key;
|
|
1127
|
-
}
|
|
1128
|
-
//#endregion
|
|
1129
|
-
//#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/key_descriptor.js
|
|
1130
|
-
function table(entries) {
|
|
1131
|
-
const out = { __proto__: null };
|
|
1132
|
-
for (const alg in entries) out[alg] = {
|
|
1133
|
-
...entries[alg],
|
|
1134
|
-
alg
|
|
1135
|
-
};
|
|
1136
|
-
return out;
|
|
1137
|
-
}
|
|
1138
|
-
//#endregion
|
|
1139
|
-
//#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jws_algorithms.js
|
|
1140
|
-
var sig = [["verify"], ["sign"]];
|
|
1141
|
-
function hmac(bits) {
|
|
1142
|
-
const subtle = {
|
|
1143
|
-
name: "HMAC",
|
|
1144
|
-
hash: `SHA-${bits}`
|
|
1145
|
-
};
|
|
1146
|
-
return {
|
|
1147
|
-
kty: ["oct"],
|
|
1148
|
-
secret: !0,
|
|
1149
|
-
subtle,
|
|
1150
|
-
signing: subtle,
|
|
1151
|
-
usages: sig
|
|
1152
|
-
};
|
|
1153
|
-
}
|
|
1154
|
-
function rsa(bits, saltLength) {
|
|
1155
|
-
const subtle = {
|
|
1156
|
-
name: saltLength ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
|
|
1157
|
-
hash: `SHA-${bits}`
|
|
1158
|
-
};
|
|
1159
|
-
return {
|
|
1160
|
-
kty: ["RSA"],
|
|
1161
|
-
subtle,
|
|
1162
|
-
signing: saltLength ? {
|
|
1163
|
-
...subtle,
|
|
1164
|
-
saltLength
|
|
1165
|
-
} : subtle,
|
|
1166
|
-
usages: sig,
|
|
1167
|
-
minRsaBits: 2048
|
|
1168
|
-
};
|
|
1169
|
-
}
|
|
1170
|
-
function ecdsa(crv, bits) {
|
|
1171
|
-
return {
|
|
1172
|
-
kty: ["EC"],
|
|
1173
|
-
crv,
|
|
1174
|
-
subtle: {
|
|
1175
|
-
name: "ECDSA",
|
|
1176
|
-
namedCurve: crv
|
|
1177
|
-
},
|
|
1178
|
-
signing: {
|
|
1179
|
-
name: "ECDSA",
|
|
1180
|
-
hash: `SHA-${bits}`
|
|
1181
|
-
},
|
|
1182
|
-
usages: sig
|
|
1183
|
-
};
|
|
1184
|
-
}
|
|
1185
|
-
function eddsa() {
|
|
1186
|
-
const subtle = { name: "Ed25519" };
|
|
1187
|
-
return {
|
|
1188
|
-
kty: ["OKP"],
|
|
1189
|
-
crv: "Ed25519",
|
|
1190
|
-
subtle,
|
|
1191
|
-
signing: subtle,
|
|
1192
|
-
usages: sig
|
|
1193
|
-
};
|
|
1194
|
-
}
|
|
1195
|
-
function mldsa(bits) {
|
|
1196
|
-
const subtle = { name: `ML-DSA-${bits}` };
|
|
1197
|
-
return {
|
|
1198
|
-
kty: ["AKP"],
|
|
1199
|
-
subtle,
|
|
1200
|
-
signing: subtle,
|
|
1201
|
-
usages: sig
|
|
1202
|
-
};
|
|
1203
|
-
}
|
|
1204
|
-
var JWS = table({
|
|
1205
|
-
HS256: hmac(256),
|
|
1206
|
-
HS384: hmac(384),
|
|
1207
|
-
HS512: hmac(512),
|
|
1208
|
-
RS256: rsa(256),
|
|
1209
|
-
RS384: rsa(384),
|
|
1210
|
-
RS512: rsa(512),
|
|
1211
|
-
PS256: rsa(256, 32),
|
|
1212
|
-
PS384: rsa(384, 48),
|
|
1213
|
-
PS512: rsa(512, 64),
|
|
1214
|
-
ES256: ecdsa("P-256", 256),
|
|
1215
|
-
ES384: ecdsa("P-384", 384),
|
|
1216
|
-
ES512: ecdsa("P-521", 512),
|
|
1217
|
-
EdDSA: eddsa(),
|
|
1218
|
-
Ed25519: eddsa(),
|
|
1219
|
-
"ML-DSA-44": mldsa(44),
|
|
1220
|
-
"ML-DSA-65": mldsa(65),
|
|
1221
|
-
"ML-DSA-87": mldsa(87)
|
|
1222
|
-
});
|
|
1223
|
-
function jwsAlgorithm(alg) {
|
|
1224
|
-
const entry = typeof alg == "string" ? JWS[alg] : void 0;
|
|
1225
|
-
if (!entry) throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
|
|
1226
|
-
return entry;
|
|
1227
|
-
}
|
|
1228
|
-
//#endregion
|
|
1229
|
-
//#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jws_verify.js
|
|
1230
|
-
function prepareVerify(options) {
|
|
1231
|
-
return [options && validateAlgorithms("algorithms", options.algorithms), options?.crit];
|
|
1232
|
-
}
|
|
1233
|
-
function parseProtectedHeader(encodedProtected) {
|
|
1234
|
-
return encodedProtected === void 0 ? {} : parseJoseHeader(encodedProtected, JWSInvalid, "JWS Protected Header is invalid");
|
|
1235
|
-
}
|
|
1236
|
-
function encodeCompactUnencodedPayload(payload) {
|
|
1237
|
-
try {
|
|
1238
|
-
return encode$1(payload);
|
|
1239
|
-
} catch {
|
|
1240
|
-
throw new JWSInvalid("JWS Compact Serialization payload must use only ASCII characters");
|
|
1241
|
-
}
|
|
1242
|
-
}
|
|
1243
|
-
async function verifySignature(jws, shared, key, encodeUnencodedPayload, parsedProtected) {
|
|
1244
|
-
const { protected: encodedProtected, header, payload: inputPayload } = jws, parsedProt = parsedProtected ?? parseProtectedHeader(encodedProtected);
|
|
1245
|
-
if (!isDisjoint(parsedProt, header)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
|
|
1246
|
-
const joseHeader = {
|
|
1247
|
-
...parsedProt,
|
|
1248
|
-
...header
|
|
1249
|
-
}, b64 = validateB64(parsedProt, validateCrit(JWSInvalid, JWS_RECOGNIZED, shared[1], parsedProt, joseHeader)), { alg } = joseHeader;
|
|
1250
|
-
if (typeof alg != "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
|
|
1251
|
-
if (shared[0] && !shared[0].has(alg)) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed");
|
|
1252
|
-
if (b64) {
|
|
1253
|
-
if (typeof inputPayload != "string") throw new JWSInvalid("JWS Payload must be a string");
|
|
1254
|
-
} else if (typeof inputPayload != "string" && !(inputPayload instanceof Uint8Array)) throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
|
|
1255
|
-
const signingPayload = b64 || typeof inputPayload != "string" ? inputPayload : encodeUnencodedPayload(inputPayload);
|
|
1256
|
-
let resolvedKey = !1;
|
|
1257
|
-
typeof key == "function" && (key = await key(parsedProt, jws), resolvedKey = !0);
|
|
1258
|
-
const entry = jwsAlgorithm(alg), data = concat(encodedProtected !== void 0 ? encode$1(encodedProtected) : /* @__PURE__ */ new Uint8Array(), encode$1("."), typeof signingPayload == "string" ? shared[2] ??= encodeBase64url(signingPayload, "payload", JWSInvalid) : signingPayload), signature = decodeBase64url(jws.signature, "signature", JWSInvalid), k = await prepareKey(entry, key, "verify"), cryptoKey = await rawKey(k, entry.subtle, "verify");
|
|
1259
|
-
entry.minRsaBits && checkModulusLength(entry.alg, cryptoKey);
|
|
1260
|
-
let verified = !1;
|
|
1261
|
-
try {
|
|
1262
|
-
verified = await crypto.subtle.verify(entry.signing, cryptoKey, signature, data);
|
|
1263
|
-
} catch {}
|
|
1264
|
-
if (!verified) throw new JWSSignatureVerificationFailed();
|
|
1265
|
-
const result = { payload: typeof signingPayload == "string" ? decodeBase64url(signingPayload, "payload", JWSInvalid) : signingPayload };
|
|
1266
|
-
return encodedProtected !== void 0 && (result.protectedHeader = parsedProt), header !== void 0 && (result.unprotectedHeader = header), resolvedKey ? [{
|
|
1267
|
-
...result,
|
|
1268
|
-
key: k
|
|
1269
|
-
}, b64] : [result, b64];
|
|
1270
|
-
}
|
|
1271
|
-
async function verifyCompact(jws, shared, key) {
|
|
1272
|
-
if (jws instanceof Uint8Array && (jws = decoder.decode(jws)), typeof jws != "string") throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
|
|
1273
|
-
const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
|
|
1274
|
-
if (length !== 3) throw new JWSInvalid("Invalid Compact JWS");
|
|
1275
|
-
return verifySignature({
|
|
1276
|
-
payload,
|
|
1277
|
-
protected: protectedHeader,
|
|
1278
|
-
signature
|
|
1279
|
-
}, shared, key, encodeCompactUnencodedPayload);
|
|
1280
|
-
}
|
|
1281
|
-
//#endregion
|
|
1282
|
-
//#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jwt_claims_set.js
|
|
1283
|
-
var epoch = (date) => Math.floor(date.getTime() / 1e3);
|
|
1284
|
-
var multipliers = {
|
|
1285
|
-
s: 1,
|
|
1286
|
-
m: 60,
|
|
1287
|
-
h: 3600,
|
|
1288
|
-
d: 86400,
|
|
1289
|
-
w: 604800,
|
|
1290
|
-
y: 31557600
|
|
1291
|
-
};
|
|
1292
|
-
var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
|
|
1293
|
-
var checkFailed = "check_failed";
|
|
1294
|
-
function invalidDuration() {
|
|
1295
|
-
throw new TypeError("Invalid time period format");
|
|
1296
|
-
}
|
|
1297
|
-
function secs(str) {
|
|
1298
|
-
typeof str != "string" && invalidDuration();
|
|
1299
|
-
const matched = REGEX.exec(str);
|
|
1300
|
-
(!matched || matched[4] && matched[1]) && invalidDuration();
|
|
1301
|
-
const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]);
|
|
1302
|
-
return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -numericDate2 : numericDate2;
|
|
1303
|
-
}
|
|
1304
|
-
function validateInput(label, input) {
|
|
1305
|
-
if (!Number.isFinite(input)) throw new TypeError(`Invalid ${label} input`);
|
|
1306
|
-
return input;
|
|
1307
|
-
}
|
|
1308
|
-
function validateStringClaim(claim, value) {
|
|
1309
|
-
if (typeof value != "string") throw new TypeError(`"${claim}" claim must be a string`);
|
|
1310
|
-
}
|
|
1311
|
-
function validateAudienceClaim(value) {
|
|
1312
|
-
if (typeof value != "string" && (!Array.isArray(value) || Array.from(value).some((member) => typeof member != "string"))) throw new TypeError("\"aud\" claim must be a string or an array of strings");
|
|
1313
|
-
}
|
|
1314
|
-
function numericDate(value, label) {
|
|
1315
|
-
return typeof value == "number" ? validateInput(label, value) : value instanceof Date ? validateInput(label, epoch(value)) : epoch(/* @__PURE__ */ new Date()) + secs(value);
|
|
1316
|
-
}
|
|
1317
|
-
var normalizeTyp = (value) => {
|
|
1318
|
-
const normalized = value.toLowerCase();
|
|
1319
|
-
return value.includes("/") ? normalized : `application/${normalized}`;
|
|
1320
|
-
};
|
|
1321
|
-
var checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : !1;
|
|
1322
|
-
function validateNumericDate(payload, claim, required = !1) {
|
|
1323
|
-
const value = payload[claim];
|
|
1324
|
-
if (!(value === void 0 && !required)) {
|
|
1325
|
-
if (typeof value != "number") throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, payload, claim, "invalid");
|
|
1326
|
-
return value;
|
|
1327
|
-
}
|
|
1328
|
-
}
|
|
1329
|
-
function unexpectedClaim(payload, claim) {
|
|
1330
|
-
throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, payload, claim, checkFailed);
|
|
1331
|
-
}
|
|
1332
|
-
function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
|
|
1333
|
-
let payload;
|
|
1334
|
-
try {
|
|
1335
|
-
payload = JSON.parse(strictDecoder.decode(encodedPayload));
|
|
1336
|
-
} catch {}
|
|
1337
|
-
if (!isObject(payload)) throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
|
|
1338
|
-
const { typ } = options;
|
|
1339
|
-
if (typ !== void 0 && (typeof protectedHeader.typ != "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new JWTClaimValidationFailed("unexpected \"typ\" JWT header value", payload, "typ", checkFailed);
|
|
1340
|
-
const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims];
|
|
1341
|
-
maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss");
|
|
1342
|
-
for (const claim of new Set(presenceCheck.reverse())) if (!Object.hasOwn(payload, claim)) throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
|
|
1343
|
-
issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, "iss"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, "sub"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == "string" ? [audience] : audience) && unexpectedClaim(payload, "aud");
|
|
1344
|
-
const { clockTolerance } = options;
|
|
1345
|
-
let tolerance = 0;
|
|
1346
|
-
if (typeof clockTolerance == "string") tolerance = secs(clockTolerance);
|
|
1347
|
-
else if (clockTolerance !== void 0) {
|
|
1348
|
-
if (typeof clockTolerance != "number") throw new TypeError("Invalid clockTolerance option type");
|
|
1349
|
-
tolerance = clockTolerance;
|
|
1350
|
-
}
|
|
1351
|
-
validateInput("clockTolerance option", tolerance);
|
|
1352
|
-
const { currentDate } = options, now = validateInput("currentDate option", epoch(currentDate === void 0 ? /* @__PURE__ */ new Date() : currentDate)), iat = validateNumericDate(payload, "iat", maxTokenAge !== void 0), nbf = validateNumericDate(payload, "nbf");
|
|
1353
|
-
if (nbf !== void 0 && nbf > now + tolerance) throw new JWTClaimValidationFailed("\"nbf\" claim timestamp check failed", payload, "nbf", checkFailed);
|
|
1354
|
-
const exp = validateNumericDate(payload, "exp");
|
|
1355
|
-
if (exp !== void 0 && exp <= now - tolerance) throw new JWTExpired("\"exp\" claim timestamp check failed", payload, "exp", checkFailed);
|
|
1356
|
-
if (maxTokenAge !== void 0) {
|
|
1357
|
-
const age = now - iat, max = validateInput("maxTokenAge option", typeof maxTokenAge == "number" ? maxTokenAge : secs(maxTokenAge));
|
|
1358
|
-
if (age - tolerance > max) throw new JWTExpired("\"iat\" claim timestamp check failed (too far in the past)", payload, "iat", checkFailed);
|
|
1359
|
-
if (age < -tolerance) throw new JWTClaimValidationFailed("\"iat\" claim timestamp check failed (it should be in the past)", payload, "iat", checkFailed);
|
|
1360
|
-
}
|
|
1361
|
-
return payload;
|
|
1362
|
-
}
|
|
1363
|
-
var producerPayloads;
|
|
1364
|
-
function producerPayload(producer) {
|
|
1365
|
-
return producerPayloads.get(producer);
|
|
1366
|
-
}
|
|
1367
|
-
function jwtData(producer) {
|
|
1368
|
-
const payload = producerPayload(producer);
|
|
1369
|
-
for (const claim of [
|
|
1370
|
-
"iat",
|
|
1371
|
-
"nbf",
|
|
1372
|
-
"exp"
|
|
1373
|
-
]) {
|
|
1374
|
-
const value = payload[claim];
|
|
1375
|
-
if (typeof value == "number" && !Number.isFinite(value)) throw new TypeError(`"${claim}" claim must be a finite number`);
|
|
1376
|
-
}
|
|
1377
|
-
return encoder.encode(JSON.stringify(payload));
|
|
1378
|
-
}
|
|
1379
|
-
var JWTClaimsBuilder = class {
|
|
1380
|
-
constructor(payload = {}) {
|
|
1381
|
-
if (!isObject(payload)) throw new TypeError("JWT Claims Set MUST be an object");
|
|
1382
|
-
(producerPayloads ||= /* @__PURE__ */ new WeakMap()).set(this, structuredClone(payload));
|
|
1383
|
-
}
|
|
1384
|
-
setIssuer(value) {
|
|
1385
|
-
return validateStringClaim("iss", value), producerPayload(this).iss = value, this;
|
|
1386
|
-
}
|
|
1387
|
-
setSubject(value) {
|
|
1388
|
-
return validateStringClaim("sub", value), producerPayload(this).sub = value, this;
|
|
1389
|
-
}
|
|
1390
|
-
setAudience(value) {
|
|
1391
|
-
return validateAudienceClaim(value), producerPayload(this).aud = value, this;
|
|
1392
|
-
}
|
|
1393
|
-
setJti(value) {
|
|
1394
|
-
return validateStringClaim("jti", value), producerPayload(this).jti = value, this;
|
|
1395
|
-
}
|
|
1396
|
-
setNotBefore(value) {
|
|
1397
|
-
return producerPayload(this).nbf = numericDate(value, "setNotBefore"), this;
|
|
1398
|
-
}
|
|
1399
|
-
setExpirationTime(value) {
|
|
1400
|
-
return producerPayload(this).exp = numericDate(value, "setExpirationTime"), this;
|
|
1401
|
-
}
|
|
1402
|
-
setIssuedAt(value) {
|
|
1403
|
-
const payload = producerPayload(this);
|
|
1404
|
-
return value === void 0 ? payload.iat = epoch(/* @__PURE__ */ new Date()) : typeof value == "string" ? payload.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value)) : payload.iat = numericDate(value, "setIssuedAt"), this;
|
|
1405
|
-
}
|
|
1406
|
-
};
|
|
1407
|
-
//#endregion
|
|
1408
|
-
//#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwt/verify.js
|
|
1409
|
-
async function jwtVerify(jwt, key, options) {
|
|
1410
|
-
const [verified, b64] = await verifyCompact(jwt, prepareVerify(options), key);
|
|
1411
|
-
if (!b64) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
|
|
1412
|
-
const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
|
|
1413
|
-
return {
|
|
1414
|
-
...verified,
|
|
1415
|
-
payload
|
|
1416
|
-
};
|
|
1417
|
-
}
|
|
1418
|
-
//#endregion
|
|
1419
|
-
//#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jws_sign.js
|
|
1420
|
-
async function createSignature(input, key, rejectUnencoded) {
|
|
1421
|
-
let [payload, protectedHeader, unprotectedHeader, crit] = input, protectedHeaderString = "";
|
|
1422
|
-
if (protectedHeader !== void 0) {
|
|
1423
|
-
const normalized = serializeJoseHeader(JWSInvalid, protectedHeader);
|
|
1424
|
-
protectedHeader = normalized[0], protectedHeaderString = encode(normalized[1]);
|
|
1425
|
-
}
|
|
1426
|
-
if (unprotectedHeader !== void 0 && (unprotectedHeader = serializeJoseHeader(JWSInvalid, unprotectedHeader)[0]), !protectedHeader && !unprotectedHeader) throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
|
|
1427
|
-
if (!isDisjoint(protectedHeader, unprotectedHeader)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
|
|
1428
|
-
const joseHeader = {
|
|
1429
|
-
...protectedHeader,
|
|
1430
|
-
...unprotectedHeader
|
|
1431
|
-
};
|
|
1432
|
-
validateCritDuplicates(JWSInvalid, protectedHeader);
|
|
1433
|
-
const b64 = validateB64(protectedHeader, validateCrit(JWSInvalid, JWS_RECOGNIZED, crit, protectedHeader, joseHeader));
|
|
1434
|
-
b64 || rejectUnencoded?.();
|
|
1435
|
-
const { alg } = joseHeader;
|
|
1436
|
-
if (typeof alg != "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
|
|
1437
|
-
const entry = jwsAlgorithm(alg);
|
|
1438
|
-
let payloadS = "", payloadB = payload, data;
|
|
1439
|
-
if (b64) {
|
|
1440
|
-
const encoded = input[4];
|
|
1441
|
-
encoded ? (payloadS = encoded[0] ??= encode(payload), payloadB = encoded[1] ??= encode$1(payloadS)) : (payloadS = encode(payload), data = encoder.encode(`${protectedHeaderString}.${payloadS}`));
|
|
1442
|
-
}
|
|
1443
|
-
data ??= concat(encode$1(protectedHeaderString), encode$1("."), payloadB);
|
|
1444
|
-
const k = await rawKey(await prepareKey(entry, key, "sign"), entry.subtle, "sign");
|
|
1445
|
-
entry.minRsaBits && checkModulusLength(entry.alg, k);
|
|
1446
|
-
const jws = {
|
|
1447
|
-
signature: encode(new Uint8Array(await crypto.subtle.sign(entry.signing, k, data))),
|
|
1448
|
-
payload: payloadS
|
|
1449
|
-
};
|
|
1450
|
-
return protectedHeader && (jws.protected = protectedHeaderString), unprotectedHeader && (jws.header = unprotectedHeader), [jws, b64];
|
|
1451
|
-
}
|
|
1452
|
-
async function createCompactSignature(payload, protectedHeader, crit, key, rejectUnencoded) {
|
|
1453
|
-
const [jws] = await createSignature([
|
|
1454
|
-
payload,
|
|
1455
|
-
protectedHeader,
|
|
1456
|
-
void 0,
|
|
1457
|
-
crit
|
|
1458
|
-
], key, rejectUnencoded);
|
|
1459
|
-
return `${jws.protected}.${jws.payload}.${jws.signature}`;
|
|
1460
|
-
}
|
|
1461
|
-
//#endregion
|
|
1462
|
-
//#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwt/sign.js
|
|
1463
|
-
var SignJWT_base = JWTClaimsBuilder;
|
|
1464
|
-
var SignJWT = class extends SignJWT_base {
|
|
1465
|
-
#protectedHeader;
|
|
1466
|
-
setProtectedHeader(protectedHeader) {
|
|
1467
|
-
return assertNotSet(this.#protectedHeader, "setProtectedHeader"), this.#protectedHeader = protectedHeader, this;
|
|
1468
|
-
}
|
|
1469
|
-
async sign(key, options) {
|
|
1470
|
-
return createCompactSignature(jwtData(this), this.#protectedHeader, options?.crit, key, () => {
|
|
1471
|
-
throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
|
|
1472
|
-
});
|
|
1473
|
-
}
|
|
1474
|
-
};
|
|
1475
|
-
//#endregion
|
|
1476
|
-
//#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwks/local.js
|
|
1477
|
-
function isUsableJWK(jwk, entry, alg, kid) {
|
|
1478
|
-
const { kty, key_ops: keyOps, ext, kid: jwkKid, alg: jwkAlg, use, crv } = jwk;
|
|
1479
|
-
return (ext === void 0 || typeof ext == "boolean") && (keyOps === void 0 || Array.isArray(keyOps) && keyOps.every((operation, index) => typeof operation == "string" && keyOps.indexOf(operation) === index) && keyOps.includes("verify")) && entry.kty.includes(kty) && (kid === void 0 || typeof kid == "string" && kid === jwkKid) && (jwkAlg === void 0 ? kty !== "AKP" : alg === jwkAlg) && (use === void 0 || use === "sig") && (!entry.crv || crv === entry.crv);
|
|
1480
|
-
}
|
|
1481
|
-
async function importWithAlgCache(cache, jwk, entry) {
|
|
1482
|
-
const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk), { alg } = entry;
|
|
1483
|
-
if (cached[alg] === void 0) {
|
|
1484
|
-
const pending = jwkToKey(entry, jwk, !0).then((key) => {
|
|
1485
|
-
if (key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys");
|
|
1486
|
-
return cached[alg] = key, key;
|
|
1487
|
-
}).catch((error) => {
|
|
1488
|
-
throw cached[alg] === pending && delete cached[alg], error;
|
|
1489
|
-
});
|
|
1490
|
-
cached[alg] = pending;
|
|
1491
|
-
}
|
|
1492
|
-
return cached[alg];
|
|
1493
|
-
}
|
|
1494
|
-
function createLocalJWKSet(jwks) {
|
|
1495
|
-
let snapshot;
|
|
1496
|
-
try {
|
|
1497
|
-
snapshot = structuredClone(jwks);
|
|
1498
|
-
} catch {}
|
|
1499
|
-
if (!isJwkSet(snapshot)) throw new JWKSInvalid("JSON Web Key Set malformed");
|
|
1500
|
-
const metadata = snapshot.keys.map((jwk) => {
|
|
1501
|
-
const normalized = snapshotJwk(jwk);
|
|
1502
|
-
return Array.isArray(normalized.key_ops) && (normalized.key_ops = [...normalized.key_ops]), normalized;
|
|
1503
|
-
}), cached = /* @__PURE__ */ new WeakMap();
|
|
1504
|
-
return Object.defineProperty(async (protectedHeader, token) => {
|
|
1505
|
-
const { alg, kid } = {
|
|
1506
|
-
...protectedHeader,
|
|
1507
|
-
...token?.header
|
|
1508
|
-
}, entry = typeof alg == "string" ? JWS[alg] : void 0;
|
|
1509
|
-
if (!entry || entry.secret) throw new JOSENotSupported("Unsupported \"alg\" value for a JSON Web Key Set");
|
|
1510
|
-
const candidates = snapshot.keys.filter((_, index) => isUsableJWK(metadata[index], entry, alg, kid)), { 0: jwk, length } = candidates;
|
|
1511
|
-
if (!length) throw new JWKSNoMatchingKey();
|
|
1512
|
-
if (length !== 1) {
|
|
1513
|
-
const error = new JWKSMultipleMatchingKeys();
|
|
1514
|
-
throw error[Symbol.asyncIterator] = async function* () {
|
|
1515
|
-
for (const jwk2 of candidates) try {
|
|
1516
|
-
yield await importWithAlgCache(cached, jwk2, entry);
|
|
1517
|
-
} catch {}
|
|
1518
|
-
}, error;
|
|
1519
|
-
}
|
|
1520
|
-
return importWithAlgCache(cached, jwk, entry);
|
|
1521
|
-
}, "jwks", { value: () => structuredClone(snapshot) });
|
|
1522
|
-
}
|
|
1523
|
-
//#endregion
|
|
1524
|
-
//#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwks/remote.js
|
|
1525
|
-
function isCloudflareWorkers() {
|
|
1526
|
-
return typeof WebSocketPair < "u" || typeof navigator < "u" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime < "u" && EdgeRuntime === "vercel";
|
|
1527
|
-
}
|
|
1528
|
-
var USER_AGENT;
|
|
1529
|
-
(typeof navigator > "u" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) && (USER_AGENT = "jose/v6.2.12");
|
|
1530
|
-
var customFetch = /* @__PURE__ */ Symbol();
|
|
1531
|
-
async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
|
|
1532
|
-
const response = await fetchImpl(url, {
|
|
1533
|
-
method: "GET",
|
|
1534
|
-
signal,
|
|
1535
|
-
redirect: "manual",
|
|
1536
|
-
headers
|
|
1537
|
-
}).catch((err) => {
|
|
1538
|
-
throw err.name === "TimeoutError" ? new JWKSTimeout() : err;
|
|
1539
|
-
});
|
|
1540
|
-
if (response.status !== 200) throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");
|
|
1541
|
-
try {
|
|
1542
|
-
return await response.json();
|
|
1543
|
-
} catch {
|
|
1544
|
-
throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON");
|
|
1545
|
-
}
|
|
1546
|
-
}
|
|
1547
|
-
var jwksCache = /* @__PURE__ */ Symbol();
|
|
1548
|
-
function isFreshFor(timestamp, duration) {
|
|
1549
|
-
return Number.isFinite(timestamp) && Date.now() < timestamp + duration;
|
|
1550
|
-
}
|
|
1551
|
-
function validateDuration(value, fallback, option) {
|
|
1552
|
-
if (Number.isNaN(value)) throw new TypeError(`"${option}" option must not be NaN`);
|
|
1553
|
-
return typeof value == "number" ? value : fallback;
|
|
1554
|
-
}
|
|
1555
|
-
function createRemoteJWKSet(url, options) {
|
|
1556
|
-
if (!(url instanceof URL)) throw new TypeError("url must be an instance of URL");
|
|
1557
|
-
const href = new URL(url.href).href, opts = options ?? {}, timeoutOption = opts.timeoutDuration;
|
|
1558
|
-
if (typeof timeoutOption == "number" && (!Number.isInteger(timeoutOption) || timeoutOption < 0)) throw new TypeError("\"timeoutDuration\" option must be a non-negative integer");
|
|
1559
|
-
const timeoutDuration = typeof timeoutOption == "number" ? timeoutOption : 5e3, cooldownDuration = validateDuration(opts.cooldownDuration, 3e4, "cooldownDuration"), cacheMaxAge = validateDuration(opts.cacheMaxAge, 6e5, "cacheMaxAge"), headers = new Headers(opts.headers);
|
|
1560
|
-
USER_AGENT && !headers.has("User-Agent") && headers.set("User-Agent", USER_AGENT), headers.has("accept") || headers.set("accept", "application/json, application/jwk-set+json");
|
|
1561
|
-
const fetchImpl = opts[customFetch], cache = opts[jwksCache];
|
|
1562
|
-
let jwksTimestamp, pendingFetch, reloadSequence = 0, appliedSequence = 0, local;
|
|
1563
|
-
if (cache && typeof cache == "object") {
|
|
1564
|
-
const { uat, jwks } = cache;
|
|
1565
|
-
isFreshFor(uat, cacheMaxAge) && isJwkSet(jwks) && (jwksTimestamp = uat, local = createLocalJWKSet(jwks));
|
|
1566
|
-
}
|
|
1567
|
-
const reload = async () => {
|
|
1568
|
-
if (pendingFetch && isCloudflareWorkers() && (pendingFetch = void 0), !pendingFetch) {
|
|
1569
|
-
const sequence = ++reloadSequence, current = pendingFetch = fetchJwks(href, headers, AbortSignal.timeout(timeoutDuration), fetchImpl).then((json) => {
|
|
1570
|
-
const next = createLocalJWKSet(json);
|
|
1571
|
-
if (sequence <= appliedSequence) return;
|
|
1572
|
-
local = next;
|
|
1573
|
-
const updatedAt = Date.now();
|
|
1574
|
-
cache && (cache.uat = updatedAt, cache.jwks = json), jwksTimestamp = updatedAt, appliedSequence = sequence;
|
|
1575
|
-
}).finally(() => {
|
|
1576
|
-
pendingFetch === current && (pendingFetch = void 0);
|
|
1577
|
-
});
|
|
1578
|
-
}
|
|
1579
|
-
await pendingFetch;
|
|
1580
|
-
};
|
|
1581
|
-
return Object.defineProperties(async (protectedHeader, token) => {
|
|
1582
|
-
(!local || !isFreshFor(jwksTimestamp, cacheMaxAge)) && await reload();
|
|
1583
|
-
try {
|
|
1584
|
-
return await local(protectedHeader, token);
|
|
1585
|
-
} catch (err) {
|
|
1586
|
-
if (err instanceof JWKSNoMatchingKey && !isFreshFor(jwksTimestamp, cooldownDuration)) return await reload(), local(protectedHeader, token);
|
|
1587
|
-
throw err;
|
|
1588
|
-
}
|
|
1589
|
-
}, {
|
|
1590
|
-
coolingDown: {
|
|
1591
|
-
get: () => isFreshFor(jwksTimestamp, cooldownDuration),
|
|
1592
|
-
enumerable: !0
|
|
1593
|
-
},
|
|
1594
|
-
fresh: {
|
|
1595
|
-
get: () => isFreshFor(jwksTimestamp, cacheMaxAge),
|
|
1596
|
-
enumerable: !0
|
|
1597
|
-
},
|
|
1598
|
-
reload: {
|
|
1599
|
-
value: reload,
|
|
1600
|
-
enumerable: !0
|
|
1601
|
-
},
|
|
1602
|
-
reloading: {
|
|
1603
|
-
get: () => !!pendingFetch,
|
|
1604
|
-
enumerable: !0
|
|
1605
|
-
},
|
|
1606
|
-
jwks: {
|
|
1607
|
-
value: () => local?.jwks(),
|
|
1608
|
-
enumerable: !0
|
|
1609
|
-
}
|
|
1610
|
-
});
|
|
1611
|
-
}
|
|
1612
|
-
//#endregion
|
|
1613
|
-
//#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/index.js
|
|
1614
|
-
var webapi_exports = /* @__PURE__ */ __exportAll({
|
|
1615
|
-
SignJWT: () => SignJWT,
|
|
1616
|
-
cryptoRuntime: () => cryptoRuntime,
|
|
1617
|
-
errors: () => errors_exports,
|
|
1618
|
-
jwtVerify: () => jwtVerify
|
|
1619
|
-
});
|
|
1620
|
-
//#endregion
|
|
1621
|
-
//#region src/services/OidcLoginService.ts
|
|
1622
|
-
var DEFAULT_SCOPES = [
|
|
1623
|
-
"openid",
|
|
1624
|
-
"profile",
|
|
1625
|
-
"email"
|
|
1626
|
-
];
|
|
1627
|
-
var DEFAULT_CLOCK_TOLERANCE_SECONDS = 15;
|
|
1628
|
-
var DEFAULT_METADATA_CACHE_TTL_MS = 300 * 1e3;
|
|
1629
|
-
var WELL_KNOWN_PATH = "/.well-known/openid-configuration";
|
|
1630
|
-
var OidcLoginError = class extends Error {
|
|
1631
|
-
constructor(message) {
|
|
1632
|
-
super(message);
|
|
1633
|
-
this.name = "OidcLoginError";
|
|
1634
|
-
}
|
|
1635
|
-
};
|
|
1636
|
-
function getUsersOidcConfig() {
|
|
1637
|
-
return getPackageConfig("users", {}).auth?.oidc ?? {};
|
|
1638
|
-
}
|
|
1639
|
-
function normalizeIssuer(issuer) {
|
|
1640
|
-
return issuer.replace(/\/+$/u, "");
|
|
1641
|
-
}
|
|
1642
|
-
function resolveDiscoveryUrl(provider) {
|
|
1643
|
-
if (provider.discoveryUrl) return provider.discoveryUrl;
|
|
1644
|
-
return `${normalizeIssuer(provider.issuer)}${WELL_KNOWN_PATH}`;
|
|
1645
|
-
}
|
|
1646
|
-
function bytesToBase64Url$1(bytes) {
|
|
1647
|
-
let binary = "";
|
|
1648
|
-
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
1649
|
-
return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
|
|
1650
|
-
}
|
|
1651
|
-
function base64UrlToBytes$1(value) {
|
|
1652
|
-
const normalized = value.replaceAll("-", "+").replaceAll("_", "/");
|
|
1653
|
-
const padded = normalized.padEnd(normalized.length + (4 - normalized.length % 4) % 4, "=");
|
|
1654
|
-
const binary = atob(padded);
|
|
1655
|
-
const bytes = new Uint8Array(binary.length);
|
|
1656
|
-
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
|
|
1657
|
-
return bytes;
|
|
1658
|
-
}
|
|
1659
|
-
function randomBase64Url$1(byteLength = 32) {
|
|
1660
|
-
const bytes = new Uint8Array(byteLength);
|
|
1661
|
-
crypto.getRandomValues(bytes);
|
|
1662
|
-
return bytesToBase64Url$1(bytes);
|
|
1663
|
-
}
|
|
1664
|
-
async function pkceChallenge(codeVerifier) {
|
|
1665
|
-
const bytes = new TextEncoder().encode(codeVerifier);
|
|
1666
|
-
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
1667
|
-
return bytesToBase64Url$1(new Uint8Array(digest));
|
|
1668
|
-
}
|
|
1669
|
-
function bytesToBase64(bytes) {
|
|
1670
|
-
let binary = "";
|
|
1671
|
-
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
1672
|
-
return btoa(binary);
|
|
1673
|
-
}
|
|
1674
|
-
function formUrlEncode(value) {
|
|
1675
|
-
const params = new URLSearchParams();
|
|
1676
|
-
params.set("value", value);
|
|
1677
|
-
return params.toString().slice(6);
|
|
1678
|
-
}
|
|
1679
|
-
function encodeBasicAuth(clientId, clientSecret) {
|
|
1680
|
-
const credentials = `${formUrlEncode(clientId)}:${formUrlEncode(clientSecret)}`;
|
|
1681
|
-
return bytesToBase64(new TextEncoder().encode(credentials));
|
|
1682
|
-
}
|
|
1683
|
-
function asString(value) {
|
|
1684
|
-
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
1685
|
-
}
|
|
1686
|
-
function asBoolean(value) {
|
|
1687
|
-
if (typeof value === "boolean") return value;
|
|
1688
|
-
if (value === "true") return true;
|
|
1689
|
-
if (value === "false") return false;
|
|
1690
|
-
}
|
|
1691
|
-
function ensureFetch(fetchOverride) {
|
|
1692
|
-
const runtimeFetch = fetchOverride ?? globalThis.fetch;
|
|
1693
|
-
if (!runtimeFetch) throw new OidcLoginError("OIDC login requires a fetch implementation.");
|
|
1694
|
-
return runtimeFetch;
|
|
1695
|
-
}
|
|
1696
|
-
function requireString(value, field) {
|
|
1697
|
-
if (typeof value !== "string" || value.length === 0) throw new OidcLoginError(`OIDC provider metadata missing "${field}".`);
|
|
1698
|
-
return value;
|
|
1699
|
-
}
|
|
1700
|
-
async function readJsonResponse(response, context) {
|
|
1701
|
-
try {
|
|
1702
|
-
return await response.json();
|
|
1703
|
-
} catch {
|
|
1704
|
-
throw new OidcLoginError(`${context} returned invalid JSON.`);
|
|
1705
|
-
}
|
|
1706
|
-
}
|
|
1707
|
-
function normalizeClaims(payload, issuer, sourceName = "OIDC claims") {
|
|
1708
|
-
const sub = asString(payload.sub);
|
|
1709
|
-
if (!sub) throw new OidcLoginError(`${sourceName} missing required "sub" claim.`);
|
|
1710
|
-
return {
|
|
1711
|
-
sub,
|
|
1712
|
-
iss: asString(payload.iss) ?? issuer,
|
|
1713
|
-
email: asString(payload.email),
|
|
1714
|
-
email_verified: asBoolean(payload.email_verified),
|
|
1715
|
-
name: asString(payload.name),
|
|
1716
|
-
preferred_username: asString(payload.preferred_username)
|
|
1717
|
-
};
|
|
1718
|
-
}
|
|
1719
|
-
function mergeClaims(idTokenClaims, userInfoClaims) {
|
|
1720
|
-
if (userInfoClaims.sub !== idTokenClaims.sub) throw new OidcLoginError("OIDC userinfo subject does not match ID token.");
|
|
1721
|
-
const useIdTokenEmail = idTokenClaims.email !== void 0;
|
|
1722
|
-
return {
|
|
1723
|
-
...idTokenClaims,
|
|
1724
|
-
email: useIdTokenEmail ? idTokenClaims.email : userInfoClaims.email,
|
|
1725
|
-
email_verified: useIdTokenEmail ? idTokenClaims.email_verified : userInfoClaims.email_verified,
|
|
1726
|
-
name: idTokenClaims.name ?? userInfoClaims.name,
|
|
1727
|
-
preferred_username: idTokenClaims.preferred_username ?? userInfoClaims.preferred_username
|
|
1728
|
-
};
|
|
1729
|
-
}
|
|
1730
|
-
function validateAuthorizedParty(payload, clientId) {
|
|
1731
|
-
const authorizedParty = asString(payload.azp);
|
|
1732
|
-
if (authorizedParty && authorizedParty !== clientId) throw new OidcLoginError("OIDC authorized party validation failed.");
|
|
1733
|
-
if (Array.isArray(payload.aud) && payload.aud.length > 1 && authorizedParty !== clientId) throw new OidcLoginError("OIDC authorized party validation failed.");
|
|
1734
|
-
}
|
|
1735
|
-
function getTokenEndpointAuthMethod(provider) {
|
|
1736
|
-
return provider.tokenEndpointAuthMethod ?? (provider.clientSecret ? "client_secret_basic" : "none");
|
|
1737
|
-
}
|
|
1738
|
-
function getScopes(provider) {
|
|
1739
|
-
return provider.scopes?.length ? provider.scopes : [...DEFAULT_SCOPES];
|
|
1740
|
-
}
|
|
1741
|
-
function parseTokenResponse(json) {
|
|
1742
|
-
if (typeof json.id_token !== "string") throw new OidcLoginError("OIDC token response missing \"id_token\".");
|
|
1743
|
-
return {
|
|
1744
|
-
accessToken: asString(json.access_token),
|
|
1745
|
-
expiresAt: typeof json.expires_in === "number" ? new Date(Date.now() + json.expires_in * 1e3) : void 0,
|
|
1746
|
-
idToken: json.id_token,
|
|
1747
|
-
refreshToken: asString(json.refresh_token),
|
|
1748
|
-
scope: asString(json.scope),
|
|
1749
|
-
tokenType: asString(json.token_type)
|
|
1750
|
-
};
|
|
1751
|
-
}
|
|
1752
|
-
function parseTransaction(value) {
|
|
1753
|
-
if (!value || typeof value !== "object") throw new OidcLoginError("Invalid OIDC login transaction.");
|
|
1754
|
-
const record = value;
|
|
1755
|
-
if (!record.provider || !record.state || !record.nonce || !record.codeVerifier || typeof record.createdAt !== "number") throw new OidcLoginError("Invalid OIDC login transaction.");
|
|
1756
|
-
return {
|
|
1757
|
-
codeVerifier: record.codeVerifier,
|
|
1758
|
-
createdAt: record.createdAt,
|
|
1759
|
-
nonce: record.nonce,
|
|
1760
|
-
provider: record.provider,
|
|
1761
|
-
returnTo: asString(record.returnTo),
|
|
1762
|
-
state: record.state
|
|
1763
|
-
};
|
|
1764
|
-
}
|
|
1765
|
-
function encodeOidcTransaction(transaction) {
|
|
1766
|
-
const json = JSON.stringify(transaction);
|
|
1767
|
-
return bytesToBase64Url$1(new TextEncoder().encode(json));
|
|
1768
|
-
}
|
|
1769
|
-
function decodeOidcTransaction(value) {
|
|
1770
|
-
try {
|
|
1771
|
-
const json = new TextDecoder().decode(base64UrlToBytes$1(value));
|
|
1772
|
-
return parseTransaction(JSON.parse(json));
|
|
1773
|
-
} catch (error) {
|
|
1774
|
-
if (error instanceof OidcLoginError) throw error;
|
|
1775
|
-
throw new OidcLoginError("Invalid OIDC login transaction.");
|
|
1776
|
-
}
|
|
1777
|
-
}
|
|
1778
|
-
function resolveOidcProviderConfig(providerName, options = {}) {
|
|
1779
|
-
const oidcConfig = getUsersOidcConfig();
|
|
1780
|
-
const providers = {
|
|
1781
|
-
...oidcConfig.providers ?? {},
|
|
1782
|
-
...options.providers ?? {}
|
|
1783
|
-
};
|
|
1784
|
-
const resolvedProviderName = providerName ?? options.defaultProvider ?? oidcConfig.defaultProvider;
|
|
1785
|
-
if (!resolvedProviderName) throw new OidcLoginError("No OIDC provider specified. Pass a provider name or configure packages.users.auth.oidc.defaultProvider.");
|
|
1786
|
-
const provider = providers[resolvedProviderName];
|
|
1787
|
-
if (!provider) throw new OidcLoginError(`Unknown OIDC provider "${resolvedProviderName}". Configure it under packages.users.auth.oidc.providers.`);
|
|
1788
|
-
if (!provider.issuer || !provider.clientId) throw new OidcLoginError(`OIDC provider "${resolvedProviderName}" requires issuer and clientId.`);
|
|
1789
|
-
return {
|
|
1790
|
-
provider,
|
|
1791
|
-
providerName: resolvedProviderName
|
|
1792
|
-
};
|
|
1793
|
-
}
|
|
1794
|
-
var OidcLoginService = class {
|
|
1795
|
-
classOptions;
|
|
1796
|
-
clockTolerance;
|
|
1797
|
-
fetchImpl;
|
|
1798
|
-
metadataCacheTtlMs;
|
|
1799
|
-
authorizeProfileOwner;
|
|
1800
|
-
resolveProfile;
|
|
1801
|
-
metadataFetchedAt = 0;
|
|
1802
|
-
metadataPromise;
|
|
1803
|
-
remoteJwks;
|
|
1804
|
-
provider;
|
|
1805
|
-
providerName;
|
|
1806
|
-
constructor(options) {
|
|
1807
|
-
const { clockTolerance, fetch: fetchOverride, metadataCacheTtlMs, provider, providerName, authorizeProfileOwner, resolveProfile, ...classOptions } = options;
|
|
1808
|
-
if (!provider.redirectUri) throw new OidcLoginError(`OIDC provider "${providerName}" requires a redirectUri.`);
|
|
1809
|
-
this.classOptions = classOptions;
|
|
1810
|
-
this.clockTolerance = clockTolerance ?? DEFAULT_CLOCK_TOLERANCE_SECONDS;
|
|
1811
|
-
this.fetchImpl = ensureFetch(fetchOverride);
|
|
1812
|
-
this.metadataCacheTtlMs = metadataCacheTtlMs ?? DEFAULT_METADATA_CACHE_TTL_MS;
|
|
1813
|
-
this.authorizeProfileOwner = authorizeProfileOwner;
|
|
1814
|
-
this.resolveProfile = resolveProfile;
|
|
1815
|
-
this.provider = {
|
|
1816
|
-
...provider,
|
|
1817
|
-
issuer: normalizeIssuer(provider.issuer)
|
|
1818
|
-
};
|
|
1819
|
-
this.providerName = providerName;
|
|
1820
|
-
}
|
|
1821
|
-
createTransaction(returnTo) {
|
|
1822
|
-
return {
|
|
1823
|
-
codeVerifier: randomBase64Url$1(32),
|
|
1824
|
-
createdAt: Date.now(),
|
|
1825
|
-
nonce: randomBase64Url$1(32),
|
|
1826
|
-
provider: this.providerName,
|
|
1827
|
-
returnTo,
|
|
1828
|
-
state: randomBase64Url$1(32)
|
|
1829
|
-
};
|
|
1830
|
-
}
|
|
1831
|
-
async getMetadata() {
|
|
1832
|
-
const cacheExpired = this.metadataFetchedAt > 0 && Date.now() - this.metadataFetchedAt > this.metadataCacheTtlMs;
|
|
1833
|
-
if (!this.metadataPromise || cacheExpired) this.metadataPromise = this.fetchMetadata().then((metadata) => {
|
|
1834
|
-
this.metadataFetchedAt = Date.now();
|
|
1835
|
-
this.remoteJwks = void 0;
|
|
1836
|
-
return metadata;
|
|
1837
|
-
}).catch((error) => {
|
|
1838
|
-
this.metadataPromise = void 0;
|
|
1839
|
-
throw error;
|
|
1840
|
-
});
|
|
1841
|
-
return this.metadataPromise;
|
|
1842
|
-
}
|
|
1843
|
-
async fetchMetadata() {
|
|
1844
|
-
const discoveryUrl = resolveDiscoveryUrl(this.provider);
|
|
1845
|
-
const response = await this.fetchImpl(discoveryUrl, { headers: { accept: "application/json" } });
|
|
1846
|
-
if (!response.ok) throw new OidcLoginError(`OIDC discovery failed for "${this.providerName}" (${response.status}).`);
|
|
1847
|
-
const metadata = await readJsonResponse(response, "OIDC discovery");
|
|
1848
|
-
const issuer = requireString(metadata.issuer ?? this.provider.issuer, "issuer");
|
|
1849
|
-
if (normalizeIssuer(issuer) !== this.provider.issuer) throw new OidcLoginError(`OIDC discovery issuer mismatch for "${this.providerName}".`);
|
|
1850
|
-
return {
|
|
1851
|
-
...metadata,
|
|
1852
|
-
authorization_endpoint: requireString(metadata.authorization_endpoint, "authorization_endpoint"),
|
|
1853
|
-
issuer,
|
|
1854
|
-
jwks_uri: requireString(metadata.jwks_uri, "jwks_uri"),
|
|
1855
|
-
token_endpoint: requireString(metadata.token_endpoint, "token_endpoint")
|
|
1856
|
-
};
|
|
1857
|
-
}
|
|
1858
|
-
async createAuthorizationUrl(options = {}) {
|
|
1859
|
-
const metadata = await this.getMetadata();
|
|
1860
|
-
const transaction = options.transaction ?? this.createTransaction();
|
|
1861
|
-
const codeChallenge = await pkceChallenge(transaction.codeVerifier);
|
|
1862
|
-
const url = new URL(metadata.authorization_endpoint);
|
|
1863
|
-
url.searchParams.set("response_type", "code");
|
|
1864
|
-
url.searchParams.set("client_id", this.provider.clientId);
|
|
1865
|
-
url.searchParams.set("redirect_uri", this.provider.redirectUri);
|
|
1866
|
-
url.searchParams.set("scope", getScopes(this.provider).join(" "));
|
|
1867
|
-
url.searchParams.set("state", transaction.state);
|
|
1868
|
-
url.searchParams.set("nonce", transaction.nonce);
|
|
1869
|
-
url.searchParams.set("code_challenge", codeChallenge);
|
|
1870
|
-
url.searchParams.set("code_challenge_method", "S256");
|
|
1871
|
-
for (const [key, value] of Object.entries({
|
|
1872
|
-
...this.provider.authorizationParams,
|
|
1873
|
-
...options.authorizationParams
|
|
1874
|
-
})) if (value !== void 0) url.searchParams.set(key, String(value));
|
|
1875
|
-
return {
|
|
1876
|
-
transaction,
|
|
1877
|
-
url
|
|
1878
|
-
};
|
|
1879
|
-
}
|
|
1880
|
-
async exchangeCallback(callbackUrl, transaction) {
|
|
1881
|
-
this.validateCallbackEnvelope(callbackUrl, transaction);
|
|
1882
|
-
const metadata = await this.getMetadata();
|
|
1883
|
-
const code = this.validateCallback(callbackUrl, transaction, metadata);
|
|
1884
|
-
const tokens = await this.exchangeCode(code, transaction);
|
|
1885
|
-
const idTokenClaims = await this.verifyIdToken(tokens.idToken, transaction.nonce);
|
|
1886
|
-
return {
|
|
1887
|
-
claims: await this.enrichClaimsFromUserInfo(idTokenClaims, tokens),
|
|
1888
|
-
tokens
|
|
1889
|
-
};
|
|
1890
|
-
}
|
|
1891
|
-
async completeLogin(callbackUrl, transaction) {
|
|
1892
|
-
const { claims, tokens } = await this.exchangeCallback(callbackUrl, transaction);
|
|
1893
|
-
return {
|
|
1894
|
-
...await (await UserCollection.create(this.classOptions)).getOrCreateFromOidc(claims, this.providerName, {
|
|
1895
|
-
authorizeProfileOwner: this.authorizeProfileOwner,
|
|
1896
|
-
resolveProfile: this.resolveProfile
|
|
1897
|
-
}),
|
|
1898
|
-
claims,
|
|
1899
|
-
tokens
|
|
1900
|
-
};
|
|
1901
|
-
}
|
|
1902
|
-
validateCallback(callbackUrl, _transaction, metadata) {
|
|
1903
|
-
const url = callbackUrl instanceof URL ? callbackUrl : new URL(callbackUrl);
|
|
1904
|
-
const responseIssuer = url.searchParams.get("iss");
|
|
1905
|
-
if (!responseIssuer && metadata.authorization_response_iss_parameter_supported === true) throw new OidcLoginError("OIDC callback missing authorization response issuer.");
|
|
1906
|
-
if (responseIssuer && responseIssuer !== metadata.issuer) throw new OidcLoginError("OIDC response issuer validation failed.");
|
|
1907
|
-
const error = url.searchParams.get("error");
|
|
1908
|
-
if (error) {
|
|
1909
|
-
const description = url.searchParams.get("error_description");
|
|
1910
|
-
throw new OidcLoginError(description ? `OIDC provider returned "${error}": ${description}` : `OIDC provider returned "${error}".`);
|
|
1911
|
-
}
|
|
1912
|
-
const code = url.searchParams.get("code");
|
|
1913
|
-
if (!code) throw new OidcLoginError("OIDC callback missing authorization code.");
|
|
1914
|
-
return code;
|
|
1915
|
-
}
|
|
1916
|
-
validateCallbackEnvelope(callbackUrl, transaction) {
|
|
1917
|
-
if (transaction.provider !== this.providerName) throw new OidcLoginError("OIDC login transaction provider mismatch.");
|
|
1918
|
-
const state = (callbackUrl instanceof URL ? callbackUrl : new URL(callbackUrl)).searchParams.get("state");
|
|
1919
|
-
if (!state || state !== transaction.state) throw new OidcLoginError("OIDC state validation failed.");
|
|
1920
|
-
}
|
|
1921
|
-
async exchangeCode(code, transaction) {
|
|
1922
|
-
const metadata = await this.getMetadata();
|
|
1923
|
-
const body = new URLSearchParams({
|
|
1924
|
-
code,
|
|
1925
|
-
code_verifier: transaction.codeVerifier,
|
|
1926
|
-
grant_type: "authorization_code",
|
|
1927
|
-
redirect_uri: this.provider.redirectUri
|
|
1928
|
-
});
|
|
1929
|
-
const headers = new Headers({
|
|
1930
|
-
accept: "application/json",
|
|
1931
|
-
"content-type": "application/x-www-form-urlencoded"
|
|
1932
|
-
});
|
|
1933
|
-
const authMethod = getTokenEndpointAuthMethod(this.provider);
|
|
1934
|
-
if (authMethod === "client_secret_basic") {
|
|
1935
|
-
if (!this.provider.clientSecret) throw new OidcLoginError(`OIDC provider "${this.providerName}" is missing clientSecret.`);
|
|
1936
|
-
headers.set("authorization", `Basic ${encodeBasicAuth(this.provider.clientId, this.provider.clientSecret)}`);
|
|
1937
|
-
} else {
|
|
1938
|
-
body.set("client_id", this.provider.clientId);
|
|
1939
|
-
if (authMethod === "client_secret_post") {
|
|
1940
|
-
if (!this.provider.clientSecret) throw new OidcLoginError(`OIDC provider "${this.providerName}" is missing clientSecret.`);
|
|
1941
|
-
body.set("client_secret", this.provider.clientSecret);
|
|
1942
|
-
}
|
|
1943
|
-
}
|
|
1944
|
-
const response = await this.fetchImpl(metadata.token_endpoint, {
|
|
1945
|
-
body,
|
|
1946
|
-
headers,
|
|
1947
|
-
method: "POST"
|
|
1948
|
-
});
|
|
1949
|
-
const json = await readJsonResponse(response, "OIDC token endpoint");
|
|
1950
|
-
if (!response.ok) {
|
|
1951
|
-
const providerError = asString(json.error);
|
|
1952
|
-
const description = asString(json.error_description);
|
|
1953
|
-
throw new OidcLoginError(description ? `OIDC token exchange failed (${providerError ?? response.status}): ${description}` : `OIDC token exchange failed (${providerError ?? response.status}).`);
|
|
1954
|
-
}
|
|
1955
|
-
return parseTokenResponse(json);
|
|
1956
|
-
}
|
|
1957
|
-
async enrichClaimsFromUserInfo(claims, tokens) {
|
|
1958
|
-
if (claims.email || !tokens.accessToken) return claims;
|
|
1959
|
-
const metadata = await this.getMetadata();
|
|
1960
|
-
if (!metadata.userinfo_endpoint) return claims;
|
|
1961
|
-
const tokenType = tokens.tokenType ?? "Bearer";
|
|
1962
|
-
const response = await this.fetchImpl(metadata.userinfo_endpoint, { headers: {
|
|
1963
|
-
accept: "application/json",
|
|
1964
|
-
authorization: `${tokenType} ${tokens.accessToken}`
|
|
1965
|
-
} });
|
|
1966
|
-
if (!response.ok) throw new OidcLoginError(`OIDC userinfo request failed (${response.status}).`);
|
|
1967
|
-
return mergeClaims(claims, normalizeClaims(await readJsonResponse(response, "OIDC userinfo endpoint"), metadata.issuer, "OIDC userinfo"));
|
|
1968
|
-
}
|
|
1969
|
-
async verifyIdToken(idToken, expectedNonce) {
|
|
1970
|
-
const metadata = await this.getMetadata();
|
|
1971
|
-
this.remoteJwks ??= createRemoteJWKSet(new URL(metadata.jwks_uri), { [customFetch]: this.fetchImpl });
|
|
1972
|
-
const { payload } = await jwtVerify(idToken, this.remoteJwks, {
|
|
1973
|
-
audience: this.provider.clientId,
|
|
1974
|
-
clockTolerance: this.clockTolerance,
|
|
1975
|
-
issuer: metadata.issuer
|
|
1976
|
-
});
|
|
1977
|
-
validateAuthorizedParty(payload, this.provider.clientId);
|
|
1978
|
-
if (payload.nonce !== expectedNonce) throw new OidcLoginError("OIDC nonce validation failed.");
|
|
1979
|
-
return normalizeClaims(payload, metadata.issuer, "OIDC ID token");
|
|
1980
|
-
}
|
|
1981
|
-
};
|
|
1982
|
-
//#endregion
|
|
1983
|
-
//#region src/services/MobileAuthService.ts
|
|
1984
|
-
var DEFAULT_MOBILE_SESSION_TTL_SECONDS = 720 * 60 * 60;
|
|
1985
|
-
var DEFAULT_MOBILE_TRANSACTION_TTL_SECONDS = 600;
|
|
1986
|
-
var MAX_CLIENT_STATE_LENGTH = 512;
|
|
1987
|
-
var MAX_OIDC_SERVICE_CACHE = 16;
|
|
1988
|
-
var MAX_STORED_CLAIM_LENGTH = 1024;
|
|
1989
|
-
var MobileAuthError = class extends Error {
|
|
1990
|
-
status;
|
|
1991
|
-
code;
|
|
1992
|
-
constructor(status, code, message) {
|
|
1993
|
-
super(message);
|
|
1994
|
-
this.name = "MobileAuthError";
|
|
1995
|
-
this.status = status;
|
|
1996
|
-
this.code = code;
|
|
1997
|
-
}
|
|
1998
|
-
};
|
|
1999
|
-
function bytesToBase64Url(bytes) {
|
|
2000
|
-
let binary = "";
|
|
2001
|
-
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
2002
|
-
return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
|
|
2003
|
-
}
|
|
2004
|
-
function base64UrlToBytes(value) {
|
|
2005
|
-
const normalized = value.replaceAll("-", "+").replaceAll("_", "/");
|
|
2006
|
-
const padded = normalized.padEnd(normalized.length + (4 - normalized.length % 4) % 4, "=");
|
|
2007
|
-
const binary = atob(padded);
|
|
2008
|
-
const bytes = new Uint8Array(binary.length);
|
|
2009
|
-
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
|
|
2010
|
-
return bytes;
|
|
2011
|
-
}
|
|
2012
|
-
function randomBase64Url(byteLength = 16) {
|
|
2013
|
-
const bytes = new Uint8Array(byteLength);
|
|
2014
|
-
crypto.getRandomValues(bytes);
|
|
2015
|
-
return bytesToBase64Url(bytes);
|
|
2016
|
-
}
|
|
2017
|
-
async function hmacBase64Url(payload, secret) {
|
|
2018
|
-
const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), {
|
|
2019
|
-
hash: "SHA-256",
|
|
2020
|
-
name: "HMAC"
|
|
2021
|
-
}, false, ["sign"]);
|
|
2022
|
-
const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(payload));
|
|
2023
|
-
return bytesToBase64Url(new Uint8Array(signature));
|
|
2024
|
-
}
|
|
2025
|
-
function timingSafeEqual$1(left, right) {
|
|
2026
|
-
const leftBytes = new TextEncoder().encode(left);
|
|
2027
|
-
const rightBytes = new TextEncoder().encode(right);
|
|
2028
|
-
let diff = leftBytes.length ^ rightBytes.length;
|
|
2029
|
-
const length = Math.max(leftBytes.length, rightBytes.length);
|
|
2030
|
-
for (let index = 0; index < length; index += 1) diff |= (leftBytes[index] ?? 0) ^ (rightBytes[index] ?? 0);
|
|
2031
|
-
return diff === 0;
|
|
2032
|
-
}
|
|
2033
|
-
async function encodeMobileState(payload, secret) {
|
|
2034
|
-
const encoded = bytesToBase64Url(new TextEncoder().encode(JSON.stringify(payload)));
|
|
2035
|
-
if (!secret) return encoded;
|
|
2036
|
-
return `${encoded}.${await hmacBase64Url(encoded, secret)}`;
|
|
2037
|
-
}
|
|
2038
|
-
async function decodeMobileState(raw, secret) {
|
|
2039
|
-
const invalid = () => new MobileAuthError(401, "invalid_state", "Invalid mobile auth state.");
|
|
2040
|
-
let encoded = raw;
|
|
2041
|
-
if (secret) {
|
|
2042
|
-
const separator = raw.lastIndexOf(".");
|
|
2043
|
-
if (separator < 0) throw invalid();
|
|
2044
|
-
encoded = raw.slice(0, separator);
|
|
2045
|
-
if (!timingSafeEqual$1(raw.slice(separator + 1), await hmacBase64Url(encoded, secret))) throw invalid();
|
|
2046
|
-
}
|
|
2047
|
-
let parsed;
|
|
2048
|
-
try {
|
|
2049
|
-
parsed = JSON.parse(new TextDecoder().decode(base64UrlToBytes(encoded)));
|
|
2050
|
-
} catch {
|
|
2051
|
-
throw invalid();
|
|
2052
|
-
}
|
|
2053
|
-
if (!parsed || typeof parsed !== "object") throw invalid();
|
|
2054
|
-
const record = parsed;
|
|
2055
|
-
if (record.v !== 1 || typeof record.s !== "string" || record.s.length === 0 || typeof record.n !== "string" || record.n.length === 0 || typeof record.p !== "string" || record.p.length === 0 || typeof record.t !== "number" || !Number.isFinite(record.t) || record.c !== void 0 && typeof record.c !== "string") throw invalid();
|
|
2056
|
-
return {
|
|
2057
|
-
v: 1,
|
|
2058
|
-
s: record.s,
|
|
2059
|
-
n: record.n,
|
|
2060
|
-
p: record.p,
|
|
2061
|
-
t: record.t,
|
|
2062
|
-
c: record.c
|
|
2063
|
-
};
|
|
2064
|
-
}
|
|
2065
|
-
function readMobileBearerToken(authorizationHeader) {
|
|
2066
|
-
const token = (authorizationHeader?.match(/^Bearer\s+(.+)$/iu))?.[1]?.trim();
|
|
2067
|
-
return token && token.length > 0 ? token : null;
|
|
2068
|
-
}
|
|
2069
|
-
var DANGEROUS_REDIRECT_SCHEMES = /* @__PURE__ */ new Set([
|
|
2070
|
-
"javascript:",
|
|
2071
|
-
"data:",
|
|
2072
|
-
"vbscript:",
|
|
2073
|
-
"file:",
|
|
2074
|
-
"blob:",
|
|
2075
|
-
"about:"
|
|
2076
|
-
]);
|
|
2077
|
-
var NON_APP_REDIRECT_SCHEMES = /* @__PURE__ */ new Set([
|
|
2078
|
-
"ftp:",
|
|
2079
|
-
"ftps:",
|
|
2080
|
-
"ws:",
|
|
2081
|
-
"wss:",
|
|
2082
|
-
"mailto:",
|
|
2083
|
-
"tel:",
|
|
2084
|
-
"sms:",
|
|
2085
|
-
"gopher:",
|
|
2086
|
-
"ldap:",
|
|
2087
|
-
"ldaps:"
|
|
2088
|
-
]);
|
|
2089
|
-
function isLoopbackHost(hostname) {
|
|
2090
|
-
const host = hostname.toLowerCase();
|
|
2091
|
-
return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
|
|
2092
|
-
}
|
|
2093
|
-
function normalizeOptionalString(value) {
|
|
2094
|
-
return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
|
|
2095
|
-
}
|
|
2096
|
-
function validateMobileRedirectUri(value, allowList = []) {
|
|
2097
|
-
const redirectUri = normalizeOptionalString(value);
|
|
2098
|
-
if (!redirectUri) throw new MobileAuthError(400, "invalid_redirect_uri", "Missing mobile redirect URI.");
|
|
2099
|
-
let parsed;
|
|
2100
|
-
try {
|
|
2101
|
-
parsed = new URL(redirectUri);
|
|
2102
|
-
} catch {
|
|
2103
|
-
throw new MobileAuthError(400, "invalid_redirect_uri", "Mobile redirect URI must be an absolute URL.");
|
|
2104
|
-
}
|
|
2105
|
-
const scheme = parsed.protocol.toLowerCase();
|
|
2106
|
-
if (DANGEROUS_REDIRECT_SCHEMES.has(scheme) || NON_APP_REDIRECT_SCHEMES.has(scheme)) throw new MobileAuthError(400, "invalid_redirect_uri", "Mobile redirect URI uses an unsupported scheme.");
|
|
2107
|
-
if (scheme === "http:" && !isLoopbackHost(parsed.hostname)) throw new MobileAuthError(400, "invalid_redirect_uri", "Mobile redirect URI must use https, a loopback address, or an app scheme.");
|
|
2108
|
-
const entries = allowList.map((entry) => entry.trim()).filter(Boolean);
|
|
2109
|
-
if (entries.length > 0) {
|
|
2110
|
-
if (!entries.some((entry) => redirectUriMatchesAllowEntry(parsed, redirectUri, entry))) throw new MobileAuthError(400, "invalid_redirect_uri", "Mobile redirect URI is not allowed.");
|
|
2111
|
-
}
|
|
2112
|
-
return redirectUri;
|
|
2113
|
-
}
|
|
2114
|
-
function redirectUriMatchesAllowEntry(parsedCandidate, candidate, entry) {
|
|
2115
|
-
if (!entry.endsWith("/")) return candidate === entry;
|
|
2116
|
-
let parsedEntry;
|
|
2117
|
-
try {
|
|
2118
|
-
parsedEntry = new URL(entry);
|
|
2119
|
-
} catch {
|
|
2120
|
-
return false;
|
|
2121
|
-
}
|
|
2122
|
-
return parsedCandidate.protocol === parsedEntry.protocol && parsedCandidate.host === parsedEntry.host && parsedCandidate.pathname.startsWith(parsedEntry.pathname);
|
|
2123
|
-
}
|
|
2124
|
-
function isModuleNotFoundError$2(error) {
|
|
2125
|
-
return error instanceof Error && (error.code === "ERR_MODULE_NOT_FOUND" || /Cannot find package '@happyvertical\/smrt-tenancy'/.test(error.message));
|
|
2126
|
-
}
|
|
2127
|
-
async function runWithSystemContext(fn) {
|
|
2128
|
-
try {
|
|
2129
|
-
return await (await import("@happyvertical/smrt-tenancy")).withSystemContext(fn);
|
|
2130
|
-
} catch (error) {
|
|
2131
|
-
if (isModuleNotFoundError$2(error)) return await fn();
|
|
2132
|
-
throw error;
|
|
2133
|
-
}
|
|
2134
|
-
}
|
|
2135
|
-
var MobileAuthService = class MobileAuthService {
|
|
2136
|
-
options;
|
|
2137
|
-
classOptions;
|
|
2138
|
-
sessionTtl;
|
|
2139
|
-
transactionTtl;
|
|
2140
|
-
sessionService;
|
|
2141
|
-
userCollection;
|
|
2142
|
-
membershipCollection;
|
|
2143
|
-
roleCollection;
|
|
2144
|
-
tenantCollection;
|
|
2145
|
-
/** Per-(provider, redirectUri) service cache preserving metadata caches. */
|
|
2146
|
-
oidcServices = /* @__PURE__ */ new Map();
|
|
2147
|
-
constructor(options) {
|
|
2148
|
-
const { fetch: _fetch, clockTolerance: _clockTolerance, redirectUris: _redirectUris, sessionTtl, transactionTtl, stateSecret: _stateSecret, allowUnsignedState: _allowUnsignedState, includeInheritedTenants: _includeInheritedTenants, allowUnverifiedEmail: _allowUnverifiedEmail, resolveUser: _resolveUser, resolveTenantId: _resolveTenantId, buildExtras: _buildExtras, defaultProvider: _defaultProvider, providers: _providers, ...classOptions } = options;
|
|
2149
|
-
this.options = options;
|
|
2150
|
-
this.classOptions = classOptions;
|
|
2151
|
-
this.sessionTtl = sessionTtl && sessionTtl > 0 ? Math.floor(sessionTtl) : DEFAULT_MOBILE_SESSION_TTL_SECONDS;
|
|
2152
|
-
this.transactionTtl = transactionTtl && transactionTtl > 0 ? Math.floor(transactionTtl) : DEFAULT_MOBILE_TRANSACTION_TTL_SECONDS;
|
|
2153
|
-
}
|
|
2154
|
-
async initialize() {
|
|
2155
|
-
this.sessionService = await SessionService.create({
|
|
2156
|
-
...this.classOptions,
|
|
2157
|
-
defaultTTL: this.sessionTtl
|
|
2158
|
-
});
|
|
2159
|
-
this.userCollection = await UserCollection.create(this.classOptions);
|
|
2160
|
-
this.membershipCollection = await MembershipCollection.create(this.classOptions);
|
|
2161
|
-
this.roleCollection = await RoleCollection.create(this.classOptions);
|
|
2162
|
-
this.tenantCollection = await TenantCollection.create(this.classOptions);
|
|
2163
|
-
}
|
|
2164
|
-
static async create(options) {
|
|
2165
|
-
const service = new MobileAuthService(options);
|
|
2166
|
-
await service.initialize();
|
|
2167
|
-
return service;
|
|
2168
|
-
}
|
|
2169
|
-
/**
|
|
2170
|
-
* The underlying {@link SessionService}. Exposed so route guards can share
|
|
2171
|
-
* it with `withSessionPermissionContext` instead of minting a second one.
|
|
2172
|
-
*/
|
|
2173
|
-
getSessionService() {
|
|
2174
|
-
return this.sessionService;
|
|
2175
|
-
}
|
|
2176
|
-
resolveProvider(requested) {
|
|
2177
|
-
try {
|
|
2178
|
-
return resolveOidcProviderConfig(normalizeOptionalString(requested), this.options);
|
|
2179
|
-
} catch (error) {
|
|
2180
|
-
throw new MobileAuthError(400, "unknown_provider", error instanceof OidcLoginError ? error.message : "Unknown mobile auth provider.");
|
|
2181
|
-
}
|
|
2182
|
-
}
|
|
2183
|
-
getOidcService(providerName, redirectUri) {
|
|
2184
|
-
const key = `${providerName}
|
|
2185
|
-
${redirectUri}`;
|
|
2186
|
-
const cached = this.oidcServices.get(key);
|
|
2187
|
-
if (cached) {
|
|
2188
|
-
this.oidcServices.delete(key);
|
|
2189
|
-
this.oidcServices.set(key, cached);
|
|
2190
|
-
return cached;
|
|
2191
|
-
}
|
|
2192
|
-
const { provider } = this.resolveProvider(providerName);
|
|
2193
|
-
const service = new OidcLoginService({
|
|
2194
|
-
...this.classOptions,
|
|
2195
|
-
fetch: this.options.fetch,
|
|
2196
|
-
clockTolerance: this.options.clockTolerance,
|
|
2197
|
-
provider: {
|
|
2198
|
-
...provider,
|
|
2199
|
-
redirectUri
|
|
2200
|
-
},
|
|
2201
|
-
providerName
|
|
2202
|
-
});
|
|
2203
|
-
if (this.oidcServices.size >= MAX_OIDC_SERVICE_CACHE) {
|
|
2204
|
-
const lru = this.oidcServices.keys().next().value;
|
|
2205
|
-
if (lru !== void 0) this.oidcServices.delete(lru);
|
|
2206
|
-
}
|
|
2207
|
-
this.oidcServices.set(key, service);
|
|
2208
|
-
return service;
|
|
2209
|
-
}
|
|
2210
|
-
/**
|
|
2211
|
-
* The HMAC secret for state signing, or `undefined` when unsigned tokens
|
|
2212
|
-
* are explicitly permitted via {@link MobileAuthServiceOptions.allowUnsignedState}.
|
|
2213
|
-
* Fails closed (throws → 500 `server_misconfigured`) when no secret is
|
|
2214
|
-
* available and unsigned tokens are not opted in, so a deployment can never
|
|
2215
|
-
* silently fall back to forgeable state tokens.
|
|
2216
|
-
*/
|
|
2217
|
-
stateSecretFor(provider) {
|
|
2218
|
-
const secret = this.options.stateSecret ?? provider.clientSecret;
|
|
2219
|
-
if (secret && secret.length > 0) return secret;
|
|
2220
|
-
if (this.options.allowUnsignedState === true) return;
|
|
2221
|
-
throw new MobileAuthError(500, "server_misconfigured", "Mobile auth is not configured for signed state. Set a stateSecret (or provider clientSecret), or opt into allowUnsignedState.");
|
|
2222
|
-
}
|
|
2223
|
-
/**
|
|
2224
|
-
* `POST /api/mobile/auth/start` — begin the server-brokered PKCE
|
|
2225
|
-
* handshake. Returns the authorization URL plus the `state` and
|
|
2226
|
-
* `codeVerifier` the client must persist and echo back on complete.
|
|
2227
|
-
*/
|
|
2228
|
-
async start(input) {
|
|
2229
|
-
const resolution = this.resolveProvider(input.providerId);
|
|
2230
|
-
const redirectUri = validateMobileRedirectUri(input.redirectUri, this.options.redirectUris);
|
|
2231
|
-
const clientState = normalizeOptionalString(input.state);
|
|
2232
|
-
if (clientState && clientState.length > MAX_CLIENT_STATE_LENGTH) throw new MobileAuthError(400, "invalid_request", `Client state exceeds ${MAX_CLIENT_STATE_LENGTH} characters.`);
|
|
2233
|
-
const service = this.getOidcService(resolution.providerName, redirectUri);
|
|
2234
|
-
const base = service.createTransaction();
|
|
2235
|
-
const state = await encodeMobileState({
|
|
2236
|
-
v: 1,
|
|
2237
|
-
s: randomBase64Url(16),
|
|
2238
|
-
n: base.nonce,
|
|
2239
|
-
p: resolution.providerName,
|
|
2240
|
-
t: Date.now(),
|
|
2241
|
-
c: clientState
|
|
2242
|
-
}, this.stateSecretFor(resolution.provider));
|
|
2243
|
-
const transaction = {
|
|
2244
|
-
...base,
|
|
2245
|
-
state
|
|
2246
|
-
};
|
|
2247
|
-
const scopes = Array.isArray(input.scopes) ? input.scopes.filter((scope) => typeof scope === "string").map((scope) => scope.trim()).filter(Boolean) : [];
|
|
2248
|
-
const loginHint = normalizeOptionalString(input.loginHint);
|
|
2249
|
-
let url;
|
|
2250
|
-
try {
|
|
2251
|
-
({url} = await service.createAuthorizationUrl({
|
|
2252
|
-
transaction,
|
|
2253
|
-
authorizationParams: {
|
|
2254
|
-
...scopes.length > 0 ? { scope: scopes.join(" ") } : {},
|
|
2255
|
-
...loginHint ? { login_hint: loginHint } : {}
|
|
2256
|
-
}
|
|
2257
|
-
}));
|
|
2258
|
-
} catch (error) {
|
|
2259
|
-
throw new MobileAuthError(502, "provider_unavailable", error instanceof OidcLoginError ? error.message : "Mobile auth provider is unavailable.");
|
|
2260
|
-
}
|
|
2261
|
-
return {
|
|
2262
|
-
providerId: resolution.providerName,
|
|
2263
|
-
authorizationUrl: url.toString(),
|
|
2264
|
-
state,
|
|
2265
|
-
codeVerifier: transaction.codeVerifier,
|
|
2266
|
-
nonce: transaction.nonce,
|
|
2267
|
-
redirectUri
|
|
2268
|
-
};
|
|
2269
|
-
}
|
|
2270
|
-
/**
|
|
2271
|
-
* `POST /api/mobile/auth/complete` — exchange the authorization code (with
|
|
2272
|
-
* the echoed `state` + `codeVerifier`) for a mobile bearer session.
|
|
2273
|
-
*/
|
|
2274
|
-
async complete(input, meta = {}) {
|
|
2275
|
-
const code = normalizeOptionalString(input.code);
|
|
2276
|
-
if (!code) throw new MobileAuthError(400, "invalid_request", "Missing authorization code.");
|
|
2277
|
-
const rawState = normalizeOptionalString(input.state);
|
|
2278
|
-
if (!rawState) throw new MobileAuthError(401, "invalid_state", "Missing mobile auth state.");
|
|
2279
|
-
const codeVerifier = normalizeOptionalString(input.codeVerifier);
|
|
2280
|
-
if (!codeVerifier) throw new MobileAuthError(400, "missing_code_verifier", "Missing PKCE code verifier.");
|
|
2281
|
-
const redirectUri = validateMobileRedirectUri(input.redirectUri, this.options.redirectUris);
|
|
2282
|
-
const requestedProvider = normalizeOptionalString(input.providerId);
|
|
2283
|
-
const probe = this.resolveProvider(requestedProvider);
|
|
2284
|
-
const payload = await decodeMobileState(rawState, this.stateSecretFor(probe.provider));
|
|
2285
|
-
if (payload.p !== probe.providerName) throw new MobileAuthError(401, "invalid_state", "Mobile auth state does not match the requested provider.");
|
|
2286
|
-
const age = Date.now() - payload.t;
|
|
2287
|
-
if (age > this.transactionTtl * 1e3 || age < -6e4) throw new MobileAuthError(401, "expired_transaction", "Mobile auth handshake has expired. Start a new sign-in.");
|
|
2288
|
-
const transaction = {
|
|
2289
|
-
codeVerifier,
|
|
2290
|
-
createdAt: payload.t,
|
|
2291
|
-
nonce: payload.n,
|
|
2292
|
-
provider: payload.p,
|
|
2293
|
-
state: rawState
|
|
2294
|
-
};
|
|
2295
|
-
const service = this.getOidcService(probe.providerName, redirectUri);
|
|
2296
|
-
const callbackUrl = new URL(redirectUri);
|
|
2297
|
-
callbackUrl.searchParams.set("code", code);
|
|
2298
|
-
callbackUrl.searchParams.set("state", rawState);
|
|
2299
|
-
let claims;
|
|
2300
|
-
let tokens;
|
|
2301
|
-
try {
|
|
2302
|
-
({claims, tokens} = await service.exchangeCallback(callbackUrl, transaction));
|
|
2303
|
-
} catch (error) {
|
|
2304
|
-
throw new MobileAuthError(401, "exchange_failed", error instanceof OidcLoginError ? error.message : "Mobile auth code exchange failed.");
|
|
2305
|
-
}
|
|
2306
|
-
const resolved = await this.resolveUserFromLogin({
|
|
2307
|
-
claims,
|
|
2308
|
-
tokens,
|
|
2309
|
-
providerName: probe.providerName
|
|
2310
|
-
});
|
|
2311
|
-
if (!resolved?.id) throw new MobileAuthError(403, "signin_not_permitted", "This account is not permitted to sign in.");
|
|
2312
|
-
const tenants = await this.listTenantOptions(resolved.id);
|
|
2313
|
-
const tenantId = await this.resolveSessionTenantId({
|
|
2314
|
-
userId: resolved.id,
|
|
2315
|
-
claims,
|
|
2316
|
-
providerName: probe.providerName
|
|
2317
|
-
}, tenants);
|
|
2318
|
-
const sessionId = await this.sessionService.createSession(resolved.id, tenantId ?? void 0, {
|
|
2319
|
-
ttl: this.sessionTtl,
|
|
2320
|
-
userAgent: meta.userAgent,
|
|
2321
|
-
ipAddress: meta.ipAddress,
|
|
2322
|
-
authMethod: "mobile",
|
|
2323
|
-
data: {
|
|
2324
|
-
source: "mobile",
|
|
2325
|
-
oidcProvider: probe.providerName,
|
|
2326
|
-
oidcIssuer: claims.iss.slice(0, MAX_STORED_CLAIM_LENGTH),
|
|
2327
|
-
oidcSubject: claims.sub.slice(0, MAX_STORED_CLAIM_LENGTH)
|
|
2328
|
-
}
|
|
2329
|
-
});
|
|
2330
|
-
const email = resolved.email ?? claims.email ?? "";
|
|
2331
|
-
return {
|
|
2332
|
-
accessToken: sessionId,
|
|
2333
|
-
tokenType: "Bearer",
|
|
2334
|
-
expiresAt: new Date(Date.now() + this.sessionTtl * 1e3).toISOString(),
|
|
2335
|
-
user: this.toUserSummary(resolved.id, email),
|
|
2336
|
-
activeTenant: tenants.find((tenant) => tenant.id === tenantId) ?? null,
|
|
2337
|
-
tenants
|
|
2338
|
-
};
|
|
2339
|
-
}
|
|
2340
|
-
async resolveUserFromLogin(context) {
|
|
2341
|
-
if (this.options.resolveUser) return this.options.resolveUser(context);
|
|
2342
|
-
const result = await this.userCollection.getOrCreateFromOidc(context.claims, context.providerName, { allowUnverifiedEmail: this.options.allowUnverifiedEmail });
|
|
2343
|
-
const id = result.user.id;
|
|
2344
|
-
if (!id) return null;
|
|
2345
|
-
return {
|
|
2346
|
-
id,
|
|
2347
|
-
email: result.user.email
|
|
2348
|
-
};
|
|
2349
|
-
}
|
|
2350
|
-
async resolveSessionTenantId(context, tenants) {
|
|
2351
|
-
if (this.options.resolveTenantId) {
|
|
2352
|
-
const chosen = await this.options.resolveTenantId(context);
|
|
2353
|
-
if (chosen !== void 0) return chosen;
|
|
2354
|
-
}
|
|
2355
|
-
const direct = await runWithSystemContext(() => this.membershipCollection.findActiveByUser(context.userId));
|
|
2356
|
-
const directIds = new Set(direct.map((membership) => membership.tenantId).filter((id) => Boolean(id)));
|
|
2357
|
-
return tenants.find((tenant) => directIds.has(tenant.id))?.id ?? null;
|
|
2358
|
-
}
|
|
2359
|
-
/**
|
|
2360
|
-
* `GET /api/mobile/session` — bootstrap the app from a bearer token.
|
|
2361
|
-
* Throws 401 when the token is missing, unknown, expired, or revoked.
|
|
2362
|
-
*/
|
|
2363
|
-
async bootstrap(authorizationHeader) {
|
|
2364
|
-
const context = await this.resolveSessionContext(authorizationHeader);
|
|
2365
|
-
const userId = context.user.id;
|
|
2366
|
-
const tenants = await this.listTenantOptions(userId);
|
|
2367
|
-
const activeTenant = tenants.find((tenant) => tenant.id === context.tenantId) ?? null;
|
|
2368
|
-
const extras = this.options.buildExtras ? await this.options.buildExtras({
|
|
2369
|
-
session: context,
|
|
2370
|
-
permissions: context.permissions,
|
|
2371
|
-
tenants,
|
|
2372
|
-
activeTenant
|
|
2373
|
-
}) : void 0;
|
|
2374
|
-
return {
|
|
2375
|
-
user: this.toUserSummary(userId, context.user.email ?? ""),
|
|
2376
|
-
activeTenant,
|
|
2377
|
-
tenants,
|
|
2378
|
-
...extras ? { extras } : {}
|
|
2379
|
-
};
|
|
2380
|
-
}
|
|
2381
|
-
/**
|
|
2382
|
-
* Resolve a bearer header into a full {@link SessionContext} (user,
|
|
2383
|
-
* membership, resolved permissions, tenant). Throws {@link MobileAuthError}
|
|
2384
|
-
* with the 401 semantics the mobile client's re-auth flow expects.
|
|
2385
|
-
*/
|
|
2386
|
-
async resolveSessionContext(authorizationHeader) {
|
|
2387
|
-
const token = readMobileBearerToken(authorizationHeader);
|
|
2388
|
-
if (!token) throw new MobileAuthError(401, "missing_bearer_token", "Missing mobile bearer token.");
|
|
2389
|
-
const context = await runWithSystemContext(() => this.sessionService.loadSessionContext(token));
|
|
2390
|
-
if (!context?.user?.id) throw new MobileAuthError(401, "invalid_bearer_token", "Invalid or expired mobile bearer token.");
|
|
2391
|
-
return context;
|
|
2392
|
-
}
|
|
2393
|
-
/**
|
|
2394
|
-
* `DELETE /api/mobile/session` — revoke the bearer session. Idempotent:
|
|
2395
|
-
* a missing or unknown token reports `destroyed: false` with 200.
|
|
2396
|
-
*/
|
|
2397
|
-
async logout(authorizationHeader) {
|
|
2398
|
-
const token = readMobileBearerToken(authorizationHeader);
|
|
2399
|
-
if (!token) return {
|
|
2400
|
-
ok: true,
|
|
2401
|
-
destroyed: false
|
|
2402
|
-
};
|
|
2403
|
-
return {
|
|
2404
|
-
ok: true,
|
|
2405
|
-
destroyed: await this.sessionService.destroySession(token)
|
|
2406
|
-
};
|
|
2407
|
-
}
|
|
2408
|
-
/**
|
|
2409
|
-
* The user's selectable tenants: direct ACTIVE memberships plus — when
|
|
2410
|
-
* `includeInheritedTenants` is on (default) — descendant tenants reachable
|
|
2411
|
-
* through an ACTIVE membership whose role has `inheritsToDescendants:
|
|
2412
|
-
* true` (#1867). Selection mirrors the permission resolver: the NEAREST
|
|
2413
|
-
* flagged ancestor membership labels an inherited option, unflagged or
|
|
2414
|
-
* inactive ancestors neither confer nor block, and ANY direct membership
|
|
2415
|
-
* row on a tenant pins it (active → its own role; inactive → excluded,
|
|
2416
|
-
* since a pinned inactive row resolves to the empty permission set).
|
|
2417
|
-
*
|
|
2418
|
-
* This list is informational — per-request authorization always re-runs
|
|
2419
|
-
* through `PermissionResolver`, which additionally fail-closes on
|
|
2420
|
-
* malformed hierarchy paths.
|
|
2421
|
-
*/
|
|
2422
|
-
async listTenantOptions(userId) {
|
|
2423
|
-
return runWithSystemContext(() => this.buildTenantOptions(userId));
|
|
2424
|
-
}
|
|
2425
|
-
async buildTenantOptions(userId) {
|
|
2426
|
-
const { memberships, tenantById, roleById } = await this.loadTenantOptionSources(userId);
|
|
2427
|
-
const active = memberships.filter((membership) => membership.isActive() && membership.tenantId);
|
|
2428
|
-
const pinnedTenantIds = new Set(memberships.map((membership) => membership.tenantId).filter((id) => Boolean(id)));
|
|
2429
|
-
const options = [];
|
|
2430
|
-
for (const membership of active) {
|
|
2431
|
-
const tenant = tenantById.get(membership.tenantId);
|
|
2432
|
-
if (!tenant?.id) continue;
|
|
2433
|
-
const role = membership.roleId ? roleById.get(membership.roleId) : void 0;
|
|
2434
|
-
options.push(this.toTenantOption(tenant, role));
|
|
2435
|
-
}
|
|
2436
|
-
if (this.options.includeInheritedTenants !== false) {
|
|
2437
|
-
const activeByTenant = /* @__PURE__ */ new Map();
|
|
2438
|
-
for (const membership of active) activeByTenant.set(membership.tenantId, membership);
|
|
2439
|
-
const isFlagged = (membership) => {
|
|
2440
|
-
return (membership?.roleId ? roleById.get(membership.roleId) : void 0)?.inheritsToDescendants === true;
|
|
2441
|
-
};
|
|
2442
|
-
const flaggedTenantIds = active.filter(isFlagged).map((membership) => membership.tenantId);
|
|
2443
|
-
const descendantLists = await Promise.all(flaggedTenantIds.map((tenantId) => this.tenantCollection.getDescendants(tenantId)));
|
|
2444
|
-
const candidates = /* @__PURE__ */ new Map();
|
|
2445
|
-
for (const descendants of descendantLists) for (const descendant of descendants) {
|
|
2446
|
-
if (!descendant.id) continue;
|
|
2447
|
-
if (pinnedTenantIds.has(descendant.id)) continue;
|
|
2448
|
-
if (!candidates.has(descendant.id)) candidates.set(descendant.id, descendant);
|
|
2449
|
-
}
|
|
2450
|
-
for (const descendant of candidates.values()) {
|
|
2451
|
-
const ancestorIds = descendant.getAncestorIds();
|
|
2452
|
-
for (let i = ancestorIds.length - 1; i >= 0; i -= 1) {
|
|
2453
|
-
const ancestorMembership = activeByTenant.get(ancestorIds[i]);
|
|
2454
|
-
if (!isFlagged(ancestorMembership)) continue;
|
|
2455
|
-
const role = roleById.get(ancestorMembership?.roleId);
|
|
2456
|
-
options.push(this.toTenantOption(descendant, role));
|
|
2457
|
-
break;
|
|
2458
|
-
}
|
|
2459
|
-
}
|
|
2460
|
-
}
|
|
2461
|
-
return options.sort((a, b) => (a.name ?? "").localeCompare(b.name ?? "", void 0, { sensitivity: "base" }) || a.id.localeCompare(b.id));
|
|
2462
|
-
}
|
|
2463
|
-
async loadTenantOptionSources(userId) {
|
|
2464
|
-
const memberships = await this.membershipCollection.findByUser(userId);
|
|
2465
|
-
const active = memberships.filter((membership) => membership.isActive() && membership.tenantId);
|
|
2466
|
-
const tenantIds = [...new Set(active.map((membership) => membership.tenantId))];
|
|
2467
|
-
const roleIds = [...new Set(active.map((membership) => membership.roleId).filter((id) => Boolean(id)))];
|
|
2468
|
-
const [tenants, roles] = await Promise.all([tenantIds.length > 0 ? this.tenantCollection.listByIds(tenantIds) : Promise.resolve([]), roleIds.length > 0 ? this.roleCollection.listByIds(roleIds) : Promise.resolve([])]);
|
|
2469
|
-
return {
|
|
2470
|
-
memberships,
|
|
2471
|
-
tenantById: new Map(tenants.filter((tenant) => Boolean(tenant?.id)).map((tenant) => [tenant.id, tenant])),
|
|
2472
|
-
roleById: new Map(roles.filter((role) => Boolean(role?.id)).map((role) => [role.id, role]))
|
|
2473
|
-
};
|
|
2474
|
-
}
|
|
2475
|
-
toTenantOption(tenant, role) {
|
|
2476
|
-
return {
|
|
2477
|
-
id: tenant.id,
|
|
2478
|
-
name: tenant.name ?? "",
|
|
2479
|
-
slug: tenant.slug ?? "",
|
|
2480
|
-
roleSlug: role?.slug ?? "",
|
|
2481
|
-
roleLabel: role?.name || role?.slug || ""
|
|
2482
|
-
};
|
|
2483
|
-
}
|
|
2484
|
-
toUserSummary(id, email) {
|
|
2485
|
-
return {
|
|
2486
|
-
id,
|
|
2487
|
-
email,
|
|
2488
|
-
label: email || id
|
|
2489
|
-
};
|
|
2490
|
-
}
|
|
2491
|
-
};
|
|
2492
|
-
//#endregion
|
|
2493
|
-
//#region src/services/SessionPermissionContext.ts
|
|
2494
|
-
var PERMISSION_STORAGE_KEY = /* @__PURE__ */ Symbol.for("smrt:session-permission-context-storage");
|
|
2495
|
-
function resolvePermissionContextStorage() {
|
|
2496
|
-
const root = globalThis;
|
|
2497
|
-
root[PERMISSION_STORAGE_KEY] ??= new AsyncLocalStorage();
|
|
2498
|
-
return root[PERMISSION_STORAGE_KEY];
|
|
2499
|
-
}
|
|
2500
|
-
var requestPermissionContextStorage = resolvePermissionContextStorage();
|
|
2501
|
-
function getCurrentSessionPermissionContext() {
|
|
2502
|
-
return requestPermissionContextStorage.getStore();
|
|
2503
|
-
}
|
|
2504
|
-
function getRequestScopedDatabase() {
|
|
2505
|
-
return getCurrentSessionPermissionContext()?.database;
|
|
2506
|
-
}
|
|
2507
|
-
globalThis.__smrtGetRequestPermissionContext ??= getCurrentSessionPermissionContext;
|
|
2508
|
-
globalThis.__smrtGetRequestScopedDatabase ??= getRequestScopedDatabase;
|
|
2509
|
-
function isProbablyPostgres(configDb, database) {
|
|
2510
|
-
if (configDb && typeof configDb === "object" && !("query" in configDb) && "type" in configDb && configDb.type === "postgres") return true;
|
|
2511
|
-
if (typeof database.url === "string" && database.url.startsWith("postgres")) return true;
|
|
2512
|
-
return (database.constructor?.name || "").toLowerCase().includes("postgres");
|
|
2513
|
-
}
|
|
2514
|
-
async function setPostgresSessionVariables(database, context) {
|
|
2515
|
-
await database.query("SELECT set_config('smrt.tenant_id', $1, true)", context.tenantId ?? "");
|
|
2516
|
-
await database.query("SELECT set_config('smrt.user_id', $1, true)", context.userId ?? "");
|
|
2517
|
-
await database.query("SELECT set_config('smrt.session_id', $1, true)", context.sessionId ?? "");
|
|
2518
|
-
await database.query("SELECT set_config('smrt.permissions', $1, true)", JSON.stringify(context.permissions));
|
|
2519
|
-
await database.query("SELECT set_config('smrt.super_admin_bypass', $1, true)", context.superAdminBypass ? "true" : "false");
|
|
2520
|
-
await database.query("SELECT set_config('smrt.system_context', $1, true)", context.systemContext ? "true" : "false");
|
|
2521
|
-
}
|
|
2522
|
-
function isModuleNotFoundError$1(error) {
|
|
2523
|
-
return error instanceof Error && (error.code === "ERR_MODULE_NOT_FOUND" || /Cannot find package '@happyvertical\/smrt-tenancy'/.test(error.message));
|
|
2524
|
-
}
|
|
2525
|
-
async function runWithOptionalTenantContext(controls, context, fn) {
|
|
2526
|
-
if (controls.systemContext) try {
|
|
2527
|
-
return await (await import("@happyvertical/smrt-tenancy")).withSystemContext(fn);
|
|
2528
|
-
} catch (error) {
|
|
2529
|
-
if (isModuleNotFoundError$1(error)) return await fn();
|
|
2530
|
-
throw error;
|
|
2531
|
-
}
|
|
2532
|
-
if (!controls.enterTenantContext || !context.tenantId) return await fn();
|
|
2533
|
-
try {
|
|
2534
|
-
return await (await import("@happyvertical/smrt-tenancy")).withTenant({
|
|
2535
|
-
database: context.database,
|
|
2536
|
-
permissions: context.permissionSet,
|
|
2537
|
-
superAdminBypass: context.superAdminBypass,
|
|
2538
|
-
tenantId: context.tenantId,
|
|
2539
|
-
user: context.user ?? void 0,
|
|
2540
|
-
userId: context.userId ?? void 0
|
|
2541
|
-
}, fn);
|
|
2542
|
-
} catch (error) {
|
|
2543
|
-
if (isModuleNotFoundError$1(error)) return await fn();
|
|
2544
|
-
throw error;
|
|
2545
|
-
}
|
|
2546
|
-
}
|
|
2547
|
-
async function runWithinPermissionRuntime(controls, configuredDb, baseDatabase, spec, fn) {
|
|
2548
|
-
const config = getPackageConfig("users", {});
|
|
2549
|
-
const usePostgresRls = (controls.postgresRls ?? config.permissions?.postgres?.enabled ?? false) && isProbablyPostgres(configuredDb, baseDatabase);
|
|
2550
|
-
let transaction;
|
|
2551
|
-
let rolledBack = false;
|
|
2552
|
-
if (usePostgresRls) {
|
|
2553
|
-
if (!baseDatabase.beginTransaction) throw new Error("Postgres RLS requires a database adapter that supports beginTransaction().");
|
|
2554
|
-
transaction = await baseDatabase.beginTransaction();
|
|
2555
|
-
}
|
|
2556
|
-
const runtimeContext = {
|
|
2557
|
-
database: transaction ?? baseDatabase,
|
|
2558
|
-
permissions: spec.permissions,
|
|
2559
|
-
permissionSet: new Set(spec.permissions),
|
|
2560
|
-
membership: spec.membership,
|
|
2561
|
-
postgresRls: usePostgresRls,
|
|
2562
|
-
session: spec.session,
|
|
2563
|
-
sessionId: spec.sessionId,
|
|
2564
|
-
superAdminBypass: spec.superAdminBypass,
|
|
2565
|
-
systemContext: spec.systemContext,
|
|
2566
|
-
tenantId: spec.tenantId,
|
|
2567
|
-
user: spec.user,
|
|
2568
|
-
userId: spec.userId
|
|
2569
|
-
};
|
|
2570
|
-
try {
|
|
2571
|
-
if (transaction) await setPostgresSessionVariables(transaction, runtimeContext);
|
|
2572
|
-
return await requestPermissionContextStorage.run(runtimeContext, async () => runWithOptionalTenantContext(controls, runtimeContext, () => fn(runtimeContext)));
|
|
2573
|
-
} catch (error) {
|
|
2574
|
-
if (transaction) {
|
|
2575
|
-
if (transaction.isActive ? transaction.isActive() : true) {
|
|
2576
|
-
rolledBack = true;
|
|
2577
|
-
await transaction.rollback();
|
|
2578
|
-
}
|
|
2579
|
-
}
|
|
2580
|
-
throw error;
|
|
2581
|
-
} finally {
|
|
2582
|
-
if (transaction && !rolledBack) {
|
|
2583
|
-
if (transaction.isActive ? transaction.isActive() : true) await transaction.commit();
|
|
2584
|
-
}
|
|
2585
|
-
}
|
|
2586
|
-
}
|
|
2587
|
-
async function withSessionPermissionContext(options, fn) {
|
|
2588
|
-
const { enterTenantContext: _enterTenantContext, postgresRls: _postgresRls, sessionId: _sessionId, sessionService: _sessionService, superAdminBypass: _superAdminBypass, systemContext: _systemContext, ...sessionServiceOptions } = options;
|
|
2589
|
-
const sessionService = options.sessionService ?? await SessionService.create({ ...sessionServiceOptions });
|
|
2590
|
-
const configuredDb = sessionServiceOptions.db ?? sessionServiceOptions.persistence;
|
|
2591
|
-
const session = options.sessionId === void 0 || options.sessionId === null ? null : await sessionService.loadSessionContext(options.sessionId);
|
|
2592
|
-
const baseDatabase = sessionService.getDatabase();
|
|
2593
|
-
const ceilinged = Array.isArray(session?.permissionCeiling);
|
|
2594
|
-
const superAdminBypass = !ceilinged && (options.superAdminBypass ?? false);
|
|
2595
|
-
const systemContext = !ceilinged && (options.systemContext ?? false);
|
|
2596
|
-
return runWithinPermissionRuntime({
|
|
2597
|
-
enterTenantContext: options.enterTenantContext,
|
|
2598
|
-
postgresRls: options.postgresRls,
|
|
2599
|
-
systemContext
|
|
2600
|
-
}, configuredDb, baseDatabase, {
|
|
2601
|
-
permissions: session?.permissions ?? [],
|
|
2602
|
-
membership: session?.membership ?? null,
|
|
2603
|
-
session,
|
|
2604
|
-
sessionId: session?.sessionId ?? null,
|
|
2605
|
-
superAdminBypass,
|
|
2606
|
-
systemContext,
|
|
2607
|
-
tenantId: session?.tenantId ?? null,
|
|
2608
|
-
user: session?.user ?? null,
|
|
2609
|
-
userId: session?.user.id ?? null
|
|
2610
|
-
}, fn);
|
|
2611
|
-
}
|
|
2612
|
-
async function withPrincipalPermissionContext(options, fn) {
|
|
2613
|
-
const { enterTenantContext: _enterTenantContext, membership, permissions: providedPermissions, postgresRls: _postgresRls, resolver: providedResolver, tenantId, userId, ...serviceOptions } = options;
|
|
2614
|
-
const sessionService = await SessionService.create({ ...serviceOptions });
|
|
2615
|
-
const configuredDb = serviceOptions.db ?? serviceOptions.persistence;
|
|
2616
|
-
const baseDatabase = sessionService.getDatabase();
|
|
2617
|
-
let permissions;
|
|
2618
|
-
if (providedPermissions !== void 0) permissions = providedPermissions;
|
|
2619
|
-
else if (tenantId) {
|
|
2620
|
-
const resolved = await (providedResolver ?? await PermissionResolver.create({ ...serviceOptions })).resolvePermissions(userId, tenantId, membership === void 0 ? {} : { membership });
|
|
2621
|
-
permissions = Array.from(resolved.permissions);
|
|
2622
|
-
} else permissions = [];
|
|
2623
|
-
return runWithinPermissionRuntime({
|
|
2624
|
-
enterTenantContext: options.enterTenantContext,
|
|
2625
|
-
postgresRls: options.postgresRls,
|
|
2626
|
-
systemContext: false
|
|
2627
|
-
}, configuredDb, baseDatabase, {
|
|
2628
|
-
permissions,
|
|
2629
|
-
membership: null,
|
|
2630
|
-
session: null,
|
|
2631
|
-
sessionId: null,
|
|
2632
|
-
superAdminBypass: false,
|
|
2633
|
-
systemContext: false,
|
|
2634
|
-
tenantId: tenantId ?? null,
|
|
2635
|
-
user: null,
|
|
2636
|
-
userId
|
|
2637
|
-
}, fn);
|
|
2638
|
-
}
|
|
2639
|
-
//#endregion
|
|
2640
|
-
//#region src/services/OperationPermissionService.ts
|
|
2641
|
-
var OperationPermissionError = class extends Error {
|
|
2642
|
-
decision;
|
|
2643
|
-
permission;
|
|
2644
|
-
status = 403;
|
|
2645
|
-
constructor(decision) {
|
|
2646
|
-
super(decision.permission ? `Permission denied for '${decision.permission}'.` : "Permission denied.");
|
|
2647
|
-
this.name = "OperationPermissionError";
|
|
2648
|
-
this.decision = decision;
|
|
2649
|
-
this.permission = decision.permission;
|
|
2650
|
-
}
|
|
2651
|
-
};
|
|
2652
|
-
function isModuleNotFoundError(error) {
|
|
2653
|
-
return error instanceof Error && (error.code === "ERR_MODULE_NOT_FOUND" || /Cannot find package '@happyvertical\/smrt-tenancy'/.test(error.message));
|
|
2654
|
-
}
|
|
2655
|
-
async function readTenancyBypassContext() {
|
|
2656
|
-
try {
|
|
2657
|
-
const tenancy = await import("@happyvertical/smrt-tenancy");
|
|
2658
|
-
return {
|
|
2659
|
-
superAdminBypass: tenancy.isSuperAdminBypass(),
|
|
2660
|
-
systemContext: tenancy.isSystemContext()
|
|
2661
|
-
};
|
|
2662
|
-
} catch (error) {
|
|
2663
|
-
if (!isModuleNotFoundError(error)) throw error;
|
|
2664
|
-
return {
|
|
2665
|
-
superAdminBypass: false,
|
|
2666
|
-
systemContext: false
|
|
2667
|
-
};
|
|
2668
|
-
}
|
|
2669
|
-
}
|
|
2670
|
-
function deny(permission, reason, error) {
|
|
2671
|
-
return {
|
|
2672
|
-
allowed: false,
|
|
2673
|
-
error,
|
|
2674
|
-
permission,
|
|
2675
|
-
reason
|
|
2676
|
-
};
|
|
2677
|
-
}
|
|
2678
|
-
function allow(permission, reason) {
|
|
2679
|
-
return {
|
|
2680
|
-
allowed: true,
|
|
2681
|
-
permission,
|
|
2682
|
-
reason
|
|
2683
|
-
};
|
|
2684
|
-
}
|
|
2685
|
-
function hasCatalogSlug(catalog, permission) {
|
|
2686
|
-
return catalog.permissions.some((definition) => definition.slug === permission);
|
|
2687
|
-
}
|
|
2688
|
-
async function checkOperationPermission(options) {
|
|
2689
|
-
let permission;
|
|
2690
|
-
try {
|
|
2691
|
-
permission = deriveOperationPermissionSlug(options.collection, options.action);
|
|
2692
|
-
} catch (error) {
|
|
2693
|
-
return deny(null, "invalid_operation", error);
|
|
2694
|
-
}
|
|
2695
|
-
if (!hasCatalogSlug(options.catalog ?? PermissionCatalogService.create(options).getCatalog(), permission)) return deny(permission, "unknown_permission");
|
|
2696
|
-
const sessionContext = getCurrentSessionPermissionContext();
|
|
2697
|
-
let tenancyContext;
|
|
2698
|
-
try {
|
|
2699
|
-
tenancyContext = await readTenancyBypassContext();
|
|
2700
|
-
} catch (error) {
|
|
2701
|
-
return deny(permission, "resolution_error", error);
|
|
2702
|
-
}
|
|
2703
|
-
const ceiling = sessionContext?.session?.permissionCeiling;
|
|
2704
|
-
const ceilinged = Array.isArray(ceiling);
|
|
2705
|
-
const systemContext = !ceilinged && (sessionContext?.systemContext === true || tenancyContext.systemContext);
|
|
2706
|
-
const superAdminBypass = !ceilinged && (sessionContext?.superAdminBypass === true || tenancyContext.superAdminBypass);
|
|
2707
|
-
if (systemContext && options.allowSystemContextBypass !== false) return allow(permission, "system_context_bypass");
|
|
2708
|
-
if (superAdminBypass && options.allowSuperAdminBypass !== false) return allow(permission, "super_admin_bypass");
|
|
2709
|
-
const userId = options.userId ?? sessionContext?.userId ?? null;
|
|
2710
|
-
const tenantId = options.tenantId ?? sessionContext?.tenantId ?? null;
|
|
2711
|
-
if (!userId || !tenantId) return deny(permission, "missing_principal");
|
|
2712
|
-
if (ceilinged && userId === sessionContext?.userId && !ceiling.includes(permission)) return deny(permission, "permission_denied");
|
|
2713
|
-
if (options.permissionSet !== void 0) return (Array.isArray(options.permissionSet) ? options.permissionSet.includes(permission) : options.permissionSet.has(permission)) ? allow(permission, "permission_granted") : deny(permission, "permission_denied");
|
|
2714
|
-
try {
|
|
2715
|
-
return await (options.resolver ?? await PermissionResolver.create(options)).hasPermission(userId, tenantId, permission, { membership: options.membership }) ? allow(permission, "permission_granted") : deny(permission, "permission_denied");
|
|
2716
|
-
} catch (error) {
|
|
2717
|
-
return deny(permission, "resolution_error", error);
|
|
2718
|
-
}
|
|
2719
|
-
}
|
|
2720
|
-
async function hasOperationPermission(options) {
|
|
2721
|
-
return (await checkOperationPermission(options)).allowed;
|
|
2722
|
-
}
|
|
2723
|
-
async function assertOperationPermission(options) {
|
|
2724
|
-
const decision = await checkOperationPermission(options);
|
|
2725
|
-
if (decision.allowed || options.onDeny === "return") return decision;
|
|
2726
|
-
throw new OperationPermissionError(decision);
|
|
2727
|
-
}
|
|
2728
|
-
//#endregion
|
|
2729
|
-
//#region src/services/TerminalAuthService.ts
|
|
2730
|
-
var DEFAULT_CLI_AUTH_POLL_INTERVAL_SECONDS = 2;
|
|
2731
|
-
var DEFAULT_CLI_AUTH_REQUEST_TTL_SECONDS = 600;
|
|
2732
|
-
var DEFAULT_CLI_SESSION_TTL_SECONDS = 720 * 60 * 60;
|
|
2733
|
-
var TERMINAL_APPROVE_LOGIN_KIND = "terminal-approve";
|
|
2734
|
-
function base64url(bytes) {
|
|
2735
|
-
return bytes.toString("base64url");
|
|
2736
|
-
}
|
|
2737
|
-
function hashDeviceCode(deviceCode) {
|
|
2738
|
-
return createHash("sha256").update(deviceCode).digest("hex");
|
|
2739
|
-
}
|
|
2740
|
-
function isExpired(request) {
|
|
2741
|
-
return new Date(request.expiresAt).getTime() <= Date.now();
|
|
2742
|
-
}
|
|
2743
|
-
var TerminalAuthService = class TerminalAuthService {
|
|
2744
|
-
options;
|
|
2745
|
-
userCodePrefix;
|
|
2746
|
-
requestTtlSeconds;
|
|
2747
|
-
sessionTtlSeconds;
|
|
2748
|
-
pollIntervalSeconds;
|
|
2749
|
-
verificationPath;
|
|
2750
|
-
maxApproveAttempts;
|
|
2751
|
-
approveAttemptWindowMs;
|
|
2752
|
-
approveQueuesByUser = /* @__PURE__ */ new Map();
|
|
2753
|
-
loginLimiter;
|
|
2754
|
-
requestCollection;
|
|
2755
|
-
sessionService;
|
|
2756
|
-
constructor(options) {
|
|
2757
|
-
this.options = options;
|
|
2758
|
-
this.userCodePrefix = (options.userCodePrefix ?? "").trim().toUpperCase();
|
|
2759
|
-
this.requestTtlSeconds = options.requestTtlSeconds ?? 600;
|
|
2760
|
-
this.sessionTtlSeconds = options.sessionTtlSeconds ?? 2592e3;
|
|
2761
|
-
this.pollIntervalSeconds = options.pollIntervalSeconds ?? 2;
|
|
2762
|
-
this.maxApproveAttempts = options.maxApproveAttempts ?? 5;
|
|
2763
|
-
this.approveAttemptWindowMs = (options.approveAttemptWindowSeconds ?? 300) * 1e3;
|
|
2764
|
-
const verificationPath = options.verificationPath ?? "/terminal-login";
|
|
2765
|
-
this.verificationPath = verificationPath.startsWith("/") ? verificationPath : `/${verificationPath}`;
|
|
2766
|
-
}
|
|
2767
|
-
async initialize() {
|
|
2768
|
-
this.loginLimiter = this.options.loginLimiter ?? await LoginAttemptLimiter.create({
|
|
2769
|
-
...this.options,
|
|
2770
|
-
audit: this.options.loginAudit,
|
|
2771
|
-
lockout: false,
|
|
2772
|
-
maxAttempts: this.maxApproveAttempts,
|
|
2773
|
-
windowSeconds: this.approveAttemptWindowMs / 1e3
|
|
2774
|
-
});
|
|
2775
|
-
this.requestCollection = await UsersCliAuthRequestCollection.create(this.options);
|
|
2776
|
-
this.sessionService = await SessionService.create({
|
|
2777
|
-
...this.options,
|
|
2778
|
-
autoExtend: this.options.sessionAutoExtend ?? true,
|
|
2779
|
-
cookieName: this.options.sessionCookieName,
|
|
2780
|
-
defaultTTL: this.sessionTtlSeconds
|
|
2781
|
-
});
|
|
2782
|
-
}
|
|
2783
|
-
static async create(options) {
|
|
2784
|
-
const service = new TerminalAuthService(options);
|
|
2785
|
-
await service.initialize();
|
|
2786
|
-
return service;
|
|
2787
|
-
}
|
|
2788
|
-
makeUserCode() {
|
|
2789
|
-
const raw = randomBytes(6).toString("hex").toUpperCase().slice(0, 8);
|
|
2790
|
-
return this.userCodePrefix ? `${this.userCodePrefix}-${raw}` : raw;
|
|
2791
|
-
}
|
|
2792
|
-
/**
|
|
2793
|
-
* Generate a user code that is not present in durable request history.
|
|
2794
|
-
* Collisions are vanishingly rare (1 in 2^32 per attempt) but happen at
|
|
2795
|
-
* scale; retrying keeps the affected CLI from being locked out.
|
|
2796
|
-
*/
|
|
2797
|
-
async makeUniqueUserCode(maxAttempts = 5) {
|
|
2798
|
-
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
2799
|
-
const candidate = this.makeUserCode();
|
|
2800
|
-
if (!await this.requestCollection.findByUserCode(candidate)) return candidate;
|
|
2801
|
-
}
|
|
2802
|
-
throw new TerminalAuthError("Unable to generate a unique terminal user code; try again.");
|
|
2803
|
-
}
|
|
2804
|
-
/**
|
|
2805
|
-
* Start a new request. Returns the device code the CLI keeps secret, the
|
|
2806
|
-
* user code the human types into the browser, and the verification URL to
|
|
2807
|
-
* open. The device code is stored only as a hash.
|
|
2808
|
-
*/
|
|
2809
|
-
async createRequest(origin) {
|
|
2810
|
-
const trimmedOrigin = origin.replace(/\/+$/u, "");
|
|
2811
|
-
for (let attempt = 0; attempt < 5; attempt++) {
|
|
2812
|
-
const deviceCode = base64url(randomBytes(32));
|
|
2813
|
-
const userCode = await this.makeUniqueUserCode();
|
|
2814
|
-
const expiresAt = new Date(Date.now() + this.requestTtlSeconds * 1e3);
|
|
2815
|
-
try {
|
|
2816
|
-
await this.requestCollection.create({
|
|
2817
|
-
deviceCodeHash: hashDeviceCode(deviceCode),
|
|
2818
|
-
expiresAt,
|
|
2819
|
-
status: "pending",
|
|
2820
|
-
userCode
|
|
2821
|
-
});
|
|
2822
|
-
} catch (error) {
|
|
2823
|
-
if (isUniqueViolationError(error) && attempt < 4) continue;
|
|
2824
|
-
throw error;
|
|
2825
|
-
}
|
|
2826
|
-
return {
|
|
2827
|
-
deviceCode,
|
|
2828
|
-
expiresAt: expiresAt.toISOString(),
|
|
2829
|
-
interval: this.pollIntervalSeconds,
|
|
2830
|
-
issuer: trimmedOrigin,
|
|
2831
|
-
userCode,
|
|
2832
|
-
verificationUrl: `${trimmedOrigin}${this.verificationPath}?code=${encodeURIComponent(userCode)}`
|
|
2833
|
-
};
|
|
2834
|
-
}
|
|
2835
|
-
throw new TerminalAuthError("Unable to create a unique terminal login request; try again.");
|
|
2836
|
-
}
|
|
2837
|
-
/**
|
|
2838
|
-
* Look up a request by user code. Performs lazy expiry: pending requests
|
|
2839
|
-
* past their TTL are flipped to `expired` and persisted.
|
|
2840
|
-
*/
|
|
2841
|
-
async getRequestForUserCode(userCode) {
|
|
2842
|
-
const request = await this.requestCollection.findByUserCode(userCode);
|
|
2843
|
-
if (!request) return null;
|
|
2844
|
-
if (request.status === "pending" && isExpired(request)) {
|
|
2845
|
-
request.status = "expired";
|
|
2846
|
-
await request.save();
|
|
2847
|
-
}
|
|
2848
|
-
return request;
|
|
2849
|
-
}
|
|
2850
|
-
/**
|
|
2851
|
-
* Mark a pending request as approved and mint a bearer session bound to the
|
|
2852
|
-
* approving user. Idempotent: re-approving an already-approved request is a
|
|
2853
|
-
* no-op. Throws if the user/tenant are missing, the request is unknown, or
|
|
2854
|
-
* the request has expired.
|
|
2855
|
-
*/
|
|
2856
|
-
async approveRequest(input) {
|
|
2857
|
-
if (!input.user.id || !input.tenantId) throw new TerminalAuthError("An authenticated tenant session is required.");
|
|
2858
|
-
const userId = input.user.id;
|
|
2859
|
-
const tenantId = input.tenantId;
|
|
2860
|
-
return await this.withSerializedApprove(userId, async () => {
|
|
2861
|
-
const lease = await this.loginLimiter.reserve({
|
|
2862
|
-
kind: TERMINAL_APPROVE_LOGIN_KIND,
|
|
2863
|
-
subject: `${TERMINAL_APPROVE_LOGIN_KIND}:${userId}`
|
|
2864
|
-
});
|
|
2865
|
-
if (!lease.allowed) throw new TerminalAuthRateLimitError("Too many failed terminal-login attempts. Try again later.", lease.retryAfterSeconds);
|
|
2866
|
-
let settle = "release";
|
|
2867
|
-
try {
|
|
2868
|
-
const request = await this.getRequestForUserCode(input.userCode);
|
|
2869
|
-
if (!request) {
|
|
2870
|
-
settle = "fail";
|
|
2871
|
-
throw new TerminalAuthError("Terminal login request not found.");
|
|
2872
|
-
}
|
|
2873
|
-
if (request.status === "approved" || request.status === "consumed") {
|
|
2874
|
-
settle = "release";
|
|
2875
|
-
return request;
|
|
2876
|
-
}
|
|
2877
|
-
if (request.status !== "pending" || isExpired(request)) {
|
|
2878
|
-
request.status = "expired";
|
|
2879
|
-
await request.save();
|
|
2880
|
-
settle = "fail";
|
|
2881
|
-
throw new TerminalAuthError("Terminal login request has expired.");
|
|
2882
|
-
}
|
|
2883
|
-
const approved = await this.requestCollection.approvePendingRequest({
|
|
2884
|
-
approvedBy: input.user.email ?? userId,
|
|
2885
|
-
ipAddress: input.ipAddress,
|
|
2886
|
-
sessionTtlSeconds: this.sessionTtlSeconds,
|
|
2887
|
-
tenantId,
|
|
2888
|
-
userAgent: input.userAgent,
|
|
2889
|
-
userCode: input.userCode,
|
|
2890
|
-
userId
|
|
2891
|
-
});
|
|
2892
|
-
if (!approved) {
|
|
2893
|
-
const concurrent = await this.getRequestForUserCode(input.userCode);
|
|
2894
|
-
if (concurrent?.status === "approved" || concurrent?.status === "consumed") {
|
|
2895
|
-
settle = "release";
|
|
2896
|
-
return concurrent;
|
|
2897
|
-
}
|
|
2898
|
-
settle = "fail";
|
|
2899
|
-
throw new TerminalAuthError("Terminal login request has expired.");
|
|
2900
|
-
}
|
|
2901
|
-
request.approvedAt = approved.approvedAt;
|
|
2902
|
-
request.sessionId = approved.sessionId;
|
|
2903
|
-
request.status = "approved";
|
|
2904
|
-
request.tenantId = approved.tenantId;
|
|
2905
|
-
request.userId = approved.userId;
|
|
2906
|
-
settle = "succeed";
|
|
2907
|
-
return request;
|
|
2908
|
-
} finally {
|
|
2909
|
-
await lease[settle]().catch(() => void 0);
|
|
2910
|
-
}
|
|
2911
|
-
});
|
|
2912
|
-
}
|
|
2913
|
-
/**
|
|
2914
|
-
* Serialize approval attempts per user within this process so a burst of
|
|
2915
|
-
* parallel approvals of one valid code settles one reservation at a time
|
|
2916
|
-
* instead of each holding its own; the shared limiter row remains the
|
|
2917
|
-
* cross-replica arbiter.
|
|
2918
|
-
*/
|
|
2919
|
-
async withSerializedApprove(userId, operation) {
|
|
2920
|
-
const previous = this.approveQueuesByUser.get(userId) ?? Promise.resolve();
|
|
2921
|
-
let release = () => {};
|
|
2922
|
-
const gate = new Promise((resolve) => {
|
|
2923
|
-
release = resolve;
|
|
2924
|
-
});
|
|
2925
|
-
const tail = previous.then(() => gate);
|
|
2926
|
-
this.approveQueuesByUser.set(userId, tail);
|
|
2927
|
-
await previous;
|
|
2928
|
-
try {
|
|
2929
|
-
return await operation();
|
|
2930
|
-
} finally {
|
|
2931
|
-
release();
|
|
2932
|
-
if (this.approveQueuesByUser.get(userId) === tail) this.approveQueuesByUser.delete(userId);
|
|
2933
|
-
}
|
|
2934
|
-
}
|
|
2935
|
-
/**
|
|
2936
|
-
* Exchange a device code (the secret the CLI keeps) for an access token
|
|
2937
|
-
* once the request has been approved. Returns `{ status: 'pending' }` while
|
|
2938
|
-
* the CLI should keep polling, and `{ status: 'expired' }` if the request
|
|
2939
|
-
* was never approved within its TTL.
|
|
2940
|
-
*/
|
|
2941
|
-
async exchangeDeviceCode(deviceCode) {
|
|
2942
|
-
const deviceCodeHash = hashDeviceCode(deviceCode);
|
|
2943
|
-
const request = await this.requestCollection.findByDeviceCodeHash(deviceCodeHash);
|
|
2944
|
-
if (!request) return { status: "expired" };
|
|
2945
|
-
if (request.status === "approved" && request.sessionId) {
|
|
2946
|
-
const accessToken = await this.requestCollection.consumeApprovedSession(deviceCodeHash);
|
|
2947
|
-
if (!accessToken) return { status: "expired" };
|
|
2948
|
-
return {
|
|
2949
|
-
accessToken,
|
|
2950
|
-
expiresIn: this.sessionTtlSeconds,
|
|
2951
|
-
status: "approved",
|
|
2952
|
-
tokenType: "Bearer"
|
|
2953
|
-
};
|
|
2954
|
-
}
|
|
2955
|
-
if (isExpired(request)) {
|
|
2956
|
-
if (request.status === "pending") {
|
|
2957
|
-
request.status = "expired";
|
|
2958
|
-
await request.save();
|
|
2959
|
-
}
|
|
2960
|
-
return { status: "expired" };
|
|
2961
|
-
}
|
|
2962
|
-
if (request.status === "pending") return {
|
|
2963
|
-
expiresAt: new Date(request.expiresAt).toISOString(),
|
|
2964
|
-
interval: this.pollIntervalSeconds,
|
|
2965
|
-
status: "pending"
|
|
2966
|
-
};
|
|
2967
|
-
return { status: "expired" };
|
|
2968
|
-
}
|
|
2969
|
-
/**
|
|
2970
|
-
* Resolve a bearer token issued by this service into a full session
|
|
2971
|
-
* context — load the user, permissions, and tenant just like the cookie
|
|
2972
|
-
* path does. Returns `null` if the token is unknown, expired, or revoked.
|
|
2973
|
-
*/
|
|
2974
|
-
async loadBearerSession(token) {
|
|
2975
|
-
return this.sessionService.loadSessionContext(token);
|
|
2976
|
-
}
|
|
2977
|
-
/**
|
|
2978
|
-
* Revoke a bearer token (CLI logout). Returns true if a session was
|
|
2979
|
-
* actually revoked.
|
|
2980
|
-
*/
|
|
2981
|
-
async destroyBearerSession(token) {
|
|
2982
|
-
return this.sessionService.destroySession(token);
|
|
2983
|
-
}
|
|
2984
|
-
/**
|
|
2985
|
-
* Delete expired pending or already-consumed requests (cleanup job).
|
|
2986
|
-
*/
|
|
2987
|
-
async cleanupExpiredRequests() {
|
|
2988
|
-
return this.requestCollection.deleteExpired();
|
|
2989
|
-
}
|
|
2990
|
-
/** The default polling interval clients should use. Exposed for tests. */
|
|
2991
|
-
get pollInterval() {
|
|
2992
|
-
return this.pollIntervalSeconds;
|
|
2993
|
-
}
|
|
2994
|
-
};
|
|
2995
|
-
var TerminalAuthError = class extends Error {
|
|
2996
|
-
constructor(message) {
|
|
2997
|
-
super(message);
|
|
2998
|
-
this.name = "TerminalAuthError";
|
|
2999
|
-
}
|
|
3000
|
-
};
|
|
3001
|
-
var TerminalAuthRateLimitError = class extends TerminalAuthError {
|
|
3002
|
-
retryAfterSeconds;
|
|
3003
|
-
constructor(message, retryAfterSeconds) {
|
|
3004
|
-
super(message);
|
|
3005
|
-
this.name = "TerminalAuthRateLimitError";
|
|
3006
|
-
this.retryAfterSeconds = retryAfterSeconds;
|
|
3007
|
-
}
|
|
3008
|
-
};
|
|
3009
|
-
//#endregion
|
|
3010
|
-
export { DeviceCredentialForbiddenError as A, UsersCliAuthRequest as B, encodeOidcTransaction as C, DEFAULT_DEVICE_PERSON_IDLE_SECONDS as D, webapi_exports as E, PinVerifier as F, ensurePinPermissionsRegistered as I, UsersPinCredentialCollection as L, DeviceCredentialService as M, PIN_LOGIN_KIND as N, DEFAULT_PIN_MANAGE_PERMISSION as O, PIN_PERMISSION_DEFINITIONS as P, UsersPinCredential as R, decodeOidcTransaction as S, resolveOidcProviderConfig as T, MobileAuthService as _, TerminalAuthError as a, OidcLoginError as b, OperationPermissionError as c, hasOperationPermission as d, getCurrentSessionPermissionContext as f, MobileAuthError as g, withSessionPermissionContext as h, TERMINAL_APPROVE_LOGIN_KIND as i, DeviceCredentialPolicyError as j, DeviceCredentialError as k, assertOperationPermission as l, withPrincipalPermissionContext as m, DEFAULT_CLI_AUTH_REQUEST_TTL_SECONDS as n, TerminalAuthRateLimitError as o, getRequestScopedDatabase as p, DEFAULT_CLI_SESSION_TTL_SECONDS as r, TerminalAuthService as s, DEFAULT_CLI_AUTH_POLL_INTERVAL_SECONDS as t, checkOperationPermission as u, readMobileBearerToken as v, getUsersOidcConfig as w, OidcLoginService as x, validateMobileRedirectUri as y, UsersCliAuthRequestCollection as z };
|
|
3011
|
-
|
|
3012
|
-
//# sourceMappingURL=TerminalAuthService-CCbM_G1V.js.map
|