@happyvertical/smrt-users 0.57.12 → 0.57.14

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.
@@ -2,7 +2,7 @@
2
2
  "version": "1.0.0",
3
3
  "timestamp": 0,
4
4
  "packageName": "@happyvertical/smrt-users",
5
- "packageVersion": "0.57.12",
5
+ "packageVersion": "0.57.14",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-users:AccessRequestCollection": {
8
8
  "name": "accessrequestcollection",
@@ -0,0 +1,32 @@
1
+ import type { DatabaseInterface } from '@happyvertical/sql';
2
+ import { type PasswordPolicyOptions } from './services/PasswordCredentialService.js';
3
+ /** Explicit immutable identities make retries safe across operator processes. */
4
+ export interface ProvisionPasswordOwnerInput {
5
+ tenantId: string;
6
+ tenantName: string;
7
+ userId: string;
8
+ email?: string;
9
+ username?: string;
10
+ password: string;
11
+ }
12
+ /** Public-safe result; no credentials, user objects, or session are returned. */
13
+ export interface ProvisionPasswordOwnerResult {
14
+ status: 'created' | 'unchanged';
15
+ tenantId: string;
16
+ userId: string;
17
+ }
18
+ /** No provider, SQL, or password-policy error text crosses this boundary. */
19
+ export declare class OperatorProvisioningError extends Error {
20
+ constructor();
21
+ }
22
+ /**
23
+ * Provision a new PostgreSQL deployment owner atomically. Existing identities
24
+ * are never adopted or repaired. A complete exact retry verifies the existing
25
+ * password and returns without writing; changed passwords or grants are never
26
+ * reset. The database must already have the application's migrated manifest.
27
+ *
28
+ * Supports PostgreSQL only: the operator lock and atomicity are tested against
29
+ * the deployed dialect. Local bootstrap continues to use its existing API.
30
+ */
31
+ export declare function provisionPasswordOwner(db: DatabaseInterface, input: ProvisionPasswordOwnerInput, passwordPolicy?: PasswordPolicyOptions): Promise<ProvisionPasswordOwnerResult>;
32
+ //# sourceMappingURL=operator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"operator.d.ts","sourceRoot":"","sources":["../src/operator.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAY5D,OAAO,EAEL,KAAK,qBAAqB,EAC3B,MAAM,yCAAyC,CAAC;AAIjD,iFAAiF;AACjF,MAAM,WAAW,2BAA2B;IAC1C,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,iFAAiF;AACjF,MAAM,WAAW,4BAA4B;IAC3C,MAAM,EAAE,SAAS,GAAG,WAAW,CAAC;IAChC,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,6EAA6E;AAC7E,qBAAa,yBAA0B,SAAQ,KAAK;;CAOnD;AAKD;;;;;;;;GAQG;AACH,wBAAsB,sBAAsB,CAC1C,EAAE,EAAE,iBAAiB,EACrB,KAAK,EAAE,2BAA2B,EAClC,cAAc,GAAE,qBAA0B,GACzC,OAAO,CAAC,4BAA4B,CAAC,CA2JvC"}
@@ -0,0 +1,114 @@
1
+ import { Dt as normalizeUsername, Et as normalizeEmail, L as UserCollection, P as verifySecretHash, Tt as isValidEmail, U as TenantCollection, _ as PermissionResolver, ct as UsersPasswordCredentialCollection, f as PasswordCredentialService, ft as MembershipCollection, ot as RoleCollection } from "./chunks/PasswordCredentialService-CyB9FmYp.js";
2
+ import { a as MembershipStatus, l as TenantStatus, u as UserStatus } from "./chunks/types-DFqeph0R.js";
3
+ import { isPostgresDatabase, withEmbeddedWriteTransaction } from "@happyvertical/smrt-core";
4
+ import { withSystemContext } from "@happyvertical/smrt-tenancy";
5
+ //#region src/operator.ts
6
+ var OperatorProvisioningError = class extends Error {
7
+ constructor() {
8
+ super("Owner provisioning refused. Verify the identities, password policy, and database state.");
9
+ this.name = "OperatorProvisioningError";
10
+ }
11
+ };
12
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
13
+ async function provisionPasswordOwner(db, input, passwordPolicy = {}) {
14
+ try {
15
+ if (!isPostgresDatabase(db) || !UUID.test(input.tenantId) || !UUID.test(input.userId) || typeof input.tenantName !== "string" || !input.tenantName.trim() || input.tenantName.length > 200 || input.email !== void 0 && !isValidEmail(input.email) || input.username !== void 0 && !normalizeUsername(input.username)) throw new OperatorProvisioningError();
16
+ const email = normalizeEmail(input.email ?? "");
17
+ const username = normalizeUsername(input.username);
18
+ if (!email && !username) throw new OperatorProvisioningError();
19
+ const tenantId = input.tenantId.toLowerCase();
20
+ const userId = input.userId.toLowerCase();
21
+ const tenantName = input.tenantName.trim();
22
+ const passwordHash = await PasswordCredentialService.preparePasswordHash(input.password, {
23
+ id: userId,
24
+ email,
25
+ emailKey: email || null,
26
+ username: username || null,
27
+ usernameKey: username || null
28
+ }, passwordPolicy);
29
+ return await withSystemContext(() => withEmbeddedWriteTransaction(db, false, async (tx) => {
30
+ await tx.query("SELECT pg_advisory_xact_lock(4158, 1)");
31
+ const options = { db: tx };
32
+ const users = await UserCollection.create(options);
33
+ const tenants = await TenantCollection.create(options);
34
+ const memberships = await MembershipCollection.create(options);
35
+ const roles = await RoleCollection.create(options);
36
+ const permissions = await PermissionResolver.create(options);
37
+ const requireEffectivePermissions = async () => {
38
+ if (!(await permissions.resolvePermissions(userId, tenantId)).permissions.size) throw new OperatorProvisioningError();
39
+ };
40
+ const credentials = await UsersPasswordCredentialCollection.create(options);
41
+ const tenant = await tenants.get({ id: tenantId });
42
+ const user = await users.get({ id: userId });
43
+ const emailMatches = email ? await users.list({
44
+ where: { emailKey: email },
45
+ limit: 2
46
+ }) : [];
47
+ const usernameMatches = username ? await users.list({
48
+ where: { usernameKey: username },
49
+ limit: 2
50
+ }) : [];
51
+ if (emailMatches.some((match) => match.id !== userId) || usernameMatches.some((match) => match.id !== userId)) throw new OperatorProvisioningError();
52
+ if (user) {
53
+ const role2 = await roles.findBySlug("owner");
54
+ const membership = await memberships.findByUserAndTenant(userId, tenantId);
55
+ const credential = await credentials.findByUserId(userId);
56
+ if (!tenant || tenant.name !== tenantName || tenant.status !== TenantStatus.ACTIVE || tenant.parentTenantId || user.status !== UserStatus.ACTIVE || (user.emailKey ?? "") !== email || (user.usernameKey ?? "") !== username || !role2?.isSystem || role2.tenantId || !membership || membership.status !== MembershipStatus.ACTIVE || membership.roleId !== role2.id || !credential || credential.mustChange || !await verifySecretHash(input.password.normalize("NFKC"), passwordPolicy.pepper ?? "", credential.passwordHash)) throw new OperatorProvisioningError();
57
+ await requireEffectivePermissions();
58
+ return {
59
+ status: "unchanged",
60
+ tenantId,
61
+ userId
62
+ };
63
+ }
64
+ if (tenant && (tenant.name !== tenantName || tenant.status !== TenantStatus.ACTIVE || tenant.parentTenantId || (await memberships.list({
65
+ where: { tenantId },
66
+ limit: 1
67
+ })).length > 0)) throw new OperatorProvisioningError();
68
+ let role = await roles.findBySlug("owner");
69
+ if (!role) {
70
+ if ((await roles.list({ limit: 1 })).length > 0) throw new OperatorProvisioningError();
71
+ await roles.seedSystemRoles({ seedPermissions: true });
72
+ role = await roles.findBySlug("owner");
73
+ }
74
+ if (!role?.id || !role.isSystem || role.tenantId) throw new OperatorProvisioningError();
75
+ if (!tenant) await tenants.create({
76
+ id: tenantId,
77
+ slug: `operator-${tenantId}`,
78
+ name: tenantName,
79
+ _insertOnly: true
80
+ });
81
+ await users.create({
82
+ id: userId,
83
+ slug: `operator-${userId}`,
84
+ email,
85
+ username: username || null,
86
+ _insertOnly: true
87
+ });
88
+ await memberships.create({
89
+ userId,
90
+ tenantId,
91
+ roleId: role.id,
92
+ _insertOnly: true
93
+ });
94
+ await requireEffectivePermissions();
95
+ if (!await credentials.insertIfAbsent(userId, {
96
+ passwordHash,
97
+ mustChange: false,
98
+ rotatedAt: /* @__PURE__ */ new Date(),
99
+ rotatedBy: "operator"
100
+ })) throw new OperatorProvisioningError();
101
+ return {
102
+ status: "created",
103
+ tenantId,
104
+ userId
105
+ };
106
+ }));
107
+ } catch {
108
+ throw new OperatorProvisioningError();
109
+ }
110
+ }
111
+ //#endregion
112
+ export { OperatorProvisioningError, provisionPasswordOwner };
113
+
114
+ //# sourceMappingURL=operator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"operator.js","names":["role"],"sources":["../src/operator.ts"],"sourcesContent":["/**\n * Trusted, offline database administration. Never mount this entrypoint in a\n * request handler or generated REST/MCP surface. Possession of the database\n * connection is the authority; this is deliberately not a session API.\n * @packageDocumentation\n */\nimport {\n isPostgresDatabase,\n withEmbeddedWriteTransaction,\n} from '@happyvertical/smrt-core';\nimport { withSystemContext } from '@happyvertical/smrt-tenancy';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { MembershipCollection } from './collections/MembershipCollection.js';\nimport { UsersPasswordCredentialCollection } from './collections/PasswordCredentialCollection.js';\nimport { RoleCollection } from './collections/RoleCollection.js';\nimport { TenantCollection } from './collections/TenantCollection.js';\nimport { UserCollection } from './collections/UserCollection.js';\nimport {\n isValidEmail,\n normalizeEmail,\n normalizeUsername,\n} from './models/User.js';\nimport { verifySecretHash } from './services/credential-hash.js';\nimport {\n PasswordCredentialService,\n type PasswordPolicyOptions,\n} from './services/PasswordCredentialService.js';\nimport { PermissionResolver } from './services/PermissionResolver.js';\nimport { MembershipStatus, TenantStatus, UserStatus } from './types/index.js';\n\n/** Explicit immutable identities make retries safe across operator processes. */\nexport interface ProvisionPasswordOwnerInput {\n tenantId: string;\n tenantName: string;\n userId: string;\n email?: string;\n username?: string;\n password: string;\n}\n\n/** Public-safe result; no credentials, user objects, or session are returned. */\nexport interface ProvisionPasswordOwnerResult {\n status: 'created' | 'unchanged';\n tenantId: string;\n userId: string;\n}\n\n/** No provider, SQL, or password-policy error text crosses this boundary. */\nexport class OperatorProvisioningError extends Error {\n constructor() {\n super(\n 'Owner provisioning refused. Verify the identities, password policy, and database state.',\n );\n this.name = 'OperatorProvisioningError';\n }\n}\n\nconst UUID =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n/**\n * Provision a new PostgreSQL deployment owner atomically. Existing identities\n * are never adopted or repaired. A complete exact retry verifies the existing\n * password and returns without writing; changed passwords or grants are never\n * reset. The database must already have the application's migrated manifest.\n *\n * Supports PostgreSQL only: the operator lock and atomicity are tested against\n * the deployed dialect. Local bootstrap continues to use its existing API.\n */\nexport async function provisionPasswordOwner(\n db: DatabaseInterface,\n input: ProvisionPasswordOwnerInput,\n passwordPolicy: PasswordPolicyOptions = {},\n): Promise<ProvisionPasswordOwnerResult> {\n try {\n if (\n !isPostgresDatabase(db) ||\n !UUID.test(input.tenantId) ||\n !UUID.test(input.userId) ||\n typeof input.tenantName !== 'string' ||\n !input.tenantName.trim() ||\n input.tenantName.length > 200 ||\n (input.email !== undefined && !isValidEmail(input.email)) ||\n (input.username !== undefined && !normalizeUsername(input.username))\n )\n throw new OperatorProvisioningError();\n const email = normalizeEmail(input.email ?? '');\n const username = normalizeUsername(input.username);\n if (!email && !username) throw new OperatorProvisioningError();\n const tenantId = input.tenantId.toLowerCase();\n const userId = input.userId.toLowerCase();\n const tenantName = input.tenantName.trim();\n // Policy failures and hashing happen before any database mutation.\n const passwordHash = await PasswordCredentialService.preparePasswordHash(\n input.password,\n {\n id: userId,\n email,\n emailKey: email || null,\n username: username || null,\n usernameKey: username || null,\n },\n passwordPolicy,\n );\n return await withSystemContext(() =>\n withEmbeddedWriteTransaction(db, false, async (tx) => {\n // Serialize all operator provisioning, including overlapping identities\n // across tenants. Normal writers remain subject to unique constraints.\n await tx.query('SELECT pg_advisory_xact_lock(4158, 1)');\n const options = { db: tx };\n const users = await UserCollection.create(options);\n const tenants = await TenantCollection.create(options);\n const memberships = await MembershipCollection.create(options);\n const roles = await RoleCollection.create(options);\n const permissions = await PermissionResolver.create(options);\n const requireEffectivePermissions = async () => {\n // Resolve against the same transaction as the membership: role grants\n // alone do not account for tenant or membership DENY overrides.\n if (\n !(await permissions.resolvePermissions(userId, tenantId))\n .permissions.size\n )\n throw new OperatorProvisioningError();\n };\n const credentials =\n await UsersPasswordCredentialCollection.create(options);\n const tenant = await tenants.get({ id: tenantId });\n const user = await users.get({ id: userId });\n const emailMatches = email\n ? await users.list({ where: { emailKey: email }, limit: 2 })\n : [];\n const usernameMatches = username\n ? await users.list({ where: { usernameKey: username }, limit: 2 })\n : [];\n if (\n emailMatches.some((match) => match.id !== userId) ||\n usernameMatches.some((match) => match.id !== userId)\n )\n throw new OperatorProvisioningError();\n if (user) {\n const role = await roles.findBySlug('owner');\n const membership = await memberships.findByUserAndTenant(\n userId,\n tenantId,\n );\n const credential = await credentials.findByUserId(userId);\n if (\n !tenant ||\n tenant.name !== tenantName ||\n tenant.status !== TenantStatus.ACTIVE ||\n tenant.parentTenantId ||\n user.status !== UserStatus.ACTIVE ||\n (user.emailKey ?? '') !== email ||\n (user.usernameKey ?? '') !== username ||\n !role?.isSystem ||\n role.tenantId ||\n !membership ||\n membership.status !== MembershipStatus.ACTIVE ||\n membership.roleId !== role.id ||\n !credential ||\n credential.mustChange ||\n !(await verifySecretHash(\n input.password.normalize('NFKC'),\n passwordPolicy.pepper ?? '',\n credential.passwordHash,\n ))\n )\n throw new OperatorProvisioningError();\n await requireEffectivePermissions();\n return { status: 'unchanged', tenantId, userId };\n }\n // Never attach an owner to an occupied or differently configured tenant.\n if (\n tenant &&\n (tenant.name !== tenantName ||\n tenant.status !== TenantStatus.ACTIVE ||\n tenant.parentTenantId ||\n (await memberships.list({ where: { tenantId }, limit: 1 })).length >\n 0)\n )\n throw new OperatorProvisioningError();\n let role = await roles.findBySlug('owner');\n if (!role) {\n // Seed only a fresh authority catalog. Provisioning must never\n // re-grant permissions an operator removed from existing roles.\n if ((await roles.list({ limit: 1 })).length > 0)\n throw new OperatorProvisioningError();\n await roles.seedSystemRoles({ seedPermissions: true });\n role = await roles.findBySlug('owner');\n }\n if (!role?.id || !role.isSystem || role.tenantId)\n throw new OperatorProvisioningError();\n if (!tenant)\n await tenants.create({\n id: tenantId,\n slug: `operator-${tenantId}`,\n name: tenantName,\n _insertOnly: true,\n });\n await users.create({\n id: userId,\n slug: `operator-${userId}`,\n email,\n username: username || null,\n _insertOnly: true,\n });\n await memberships.create({\n userId,\n tenantId,\n roleId: role.id,\n _insertOnly: true,\n });\n await requireEffectivePermissions();\n if (\n !(await credentials.insertIfAbsent(userId, {\n passwordHash,\n mustChange: false,\n rotatedAt: new Date(),\n rotatedBy: 'operator',\n }))\n )\n throw new OperatorProvisioningError();\n return { status: 'created', tenantId, userId };\n }),\n );\n } catch {\n throw new OperatorProvisioningError();\n }\n}\n"],"mappings":";;;;;AAgDO,IAAM,4BAAN,cAAwC,MAAM;CACnD,cAAc;EACZ,MACE,yFACF;EACA,KAAK,OAAO;CACd;AACF;AAEA,IAAM,OACJ;AAWF,eAAsB,uBACpB,IACA,OACA,iBAAwC,CAAC,GACF;CACvC,IAAI;EACF,IACE,CAAC,mBAAmB,EAAE,KACtB,CAAC,KAAK,KAAK,MAAM,QAAQ,KACzB,CAAC,KAAK,KAAK,MAAM,MAAM,KACvB,OAAO,MAAM,eAAe,YAC5B,CAAC,MAAM,WAAW,KAAK,KACvB,MAAM,WAAW,SAAS,OACzB,MAAM,UAAU,KAAA,KAAa,CAAC,aAAa,MAAM,KAAK,KACtD,MAAM,aAAa,KAAA,KAAa,CAAC,kBAAkB,MAAM,QAAQ,GAElE,MAAM,IAAI,0BAA0B;EACtC,MAAM,QAAQ,eAAe,MAAM,SAAS,EAAE;EAC9C,MAAM,WAAW,kBAAkB,MAAM,QAAQ;EACjD,IAAI,CAAC,SAAS,CAAC,UAAU,MAAM,IAAI,0BAA0B;EAC7D,MAAM,WAAW,MAAM,SAAS,YAAY;EAC5C,MAAM,SAAS,MAAM,OAAO,YAAY;EACxC,MAAM,aAAa,MAAM,WA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,OAAO;IACvB;IACA;IACA,QAAQ,KAAK;IACb,aAAa;GACf,CAAC;GACD,MAAM,4BAA4B;GAClC,IACE,CAAE,MAAM,YAAY,eAAe,QAAQ;IACzC;IACA,YAAY;IACZ,2BAAW,IAAI,KAAK;IACpB,WAAW;GACb,CAAC,GAED,MAAM,IAAI,0BAA0B;GACtC,OAAO;IAAE,QAAQ;IAAW;IAAU;GAAO;EAC/C,CAAC,CACH;CACF,QAAQ;EACN,MAAM,IAAI,0BAA0B;CACtC;AACF"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Readiness contract for the public self-hosted password provider.
3
+ *
4
+ * This is intentionally a provider module for app-runtime's generic
5
+ * `createProviderReadinessProbe`: operators select it with
6
+ * `SMRT_AUTH_READINESS_MODULE=@happyvertical/smrt-users`. It proves the
7
+ * configured PostgreSQL database has the rows password sign-in actually uses;
8
+ * it never creates or repairs application schema.
9
+ */
10
+ export interface PasswordReadinessContext {
11
+ component: string;
12
+ profile: string;
13
+ provider: string;
14
+ }
15
+ /**
16
+ * Provider readiness entry point. Errors are intentionally generic because
17
+ * app-runtime projects provider failures into public-safe startup diagnostics.
18
+ */
19
+ export declare function checkReadiness(context: PasswordReadinessContext): Promise<true>;
20
+ //# sourceMappingURL=password-readiness.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"password-readiness.d.ts","sourceRoot":"","sources":["../src/password-readiness.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAQH,MAAM,WAAW,wBAAwB;IACvC,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAqFD;;;GAGG;AACH,wBAAsB,cAAc,CAClC,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC,IAAI,CAAC,CAwBf"}
@@ -47,6 +47,7 @@
47
47
  */
48
48
  import { type SmrtClassOptions } from '@happyvertical/smrt-core';
49
49
  import { type SessionAuthMethod } from '../models/Session.js';
50
+ import { type User } from '../models/User.js';
50
51
  import { type ScryptParams } from './credential-hash.js';
51
52
  import { InvalidCredentialsError, LoginAttemptLimiter, type LoginAttemptLimiterOptions } from './LoginAttemptLimiter.js';
52
53
  import { type PermissionDefinition } from './PermissionCatalogService.js';
@@ -281,6 +282,12 @@ export declare class PasswordCredentialService {
281
282
  constructor(options: PasswordCredentialServiceOptions);
282
283
  private static resolveRecovery;
283
284
  static create(options: PasswordCredentialServiceOptions): Promise<PasswordCredentialService>;
285
+ /**
286
+ * Validate and hash a prospective password without reading or writing state.
287
+ * Trusted operator provisioning uses the same policy as ordinary lifecycle
288
+ * writes. This does not install a credential or authorize an account change.
289
+ */
290
+ static preparePasswordHash(password: string, user: Pick<User, 'id' | 'email' | 'emailKey' | 'username' | 'usernameKey'>, policy?: PasswordPolicyOptions): Promise<string>;
284
291
  initialize(): Promise<void>;
285
292
  /** The limiter in use (shared or private). */
286
293
  get loginLimiter(): LoginAttemptLimiter;
@@ -1 +1 @@
1
- {"version":3,"file":"PasswordCredentialService.d.ts","sourceRoot":"","sources":["../../src/services/PasswordCredentialService.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAGH,OAAO,EAEL,KAAK,gBAAgB,EAEtB,MAAM,0BAA0B,CAAC;AAQlC,OAAO,EAGL,KAAK,iBAAiB,EACvB,MAAM,sBAAsB,CAAC;AAQ9B,OAAO,EAIL,KAAK,YAAY,EAGlB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,uBAAuB,EACvB,mBAAmB,EACnB,KAAK,0BAA0B,EAEhC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,KAAK,oBAAoB,EAE1B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,KAAK,cAAc,EAAkB,MAAM,qBAAqB,CAAC;AAE1E,yEAAyE;AACzE,eAAO,MAAM,mBAAmB,aAAa,CAAC;AAC9C,qFAAqF;AACrF,eAA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IpB;;;;;;;OAOG;YACW,eAAe;IAU7B;;;;;OAKG;YACW,mBAAmB;YAwBnB,gBAAgB;CAY/B"}
@@ -3,13 +3,13 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-users",
6
- "packageVersion": "0.57.12",
6
+ "packageVersion": "0.57.14",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "b6fe1478dda5d662246bedf30e7f616d361a9afe79d1320eaa57d8b0d67a1f52",
11
- "packageJson": "10a0c71f11cfc457b12ca1099dd3771ca12c512168ee32cd33324524b1839cf8",
12
- "agents": "c4ab6a1aae24c0fb687d4d02ef25dcb5e6942ad7e8318e9d0dd8d03d5750b788",
10
+ "manifest": "b54fcad326e2fb86eb676cc893740cca2a79089846352db3154b39f27be8c23f",
11
+ "packageJson": "e51dff829def844c40dd78a86a76ee86dcc22731909b816f7a142c2df594f52e",
12
+ "agents": "eac1496479196208c81a434fdc0d861a8d57ea2246a70e2606dea8d07e424903",
13
13
  "moduleDoc:agents/permissions.md": "02b2f03f0e057721369d9c693a624a6fdb3df4935401531a4373ff18229a64be",
14
14
  "moduleDoc:agents/oidc-provisioning.md": "b73f3fdaf61136720132a614c7e14237b7bd35f7bf5d43eabb29f565485803b9",
15
15
  "moduleDoc:agents/mobile-auth.md": "25e85e83f43e3a46383a92fa809f3a003b4545c3026e78dbe1bccbbc35161e18",
@@ -21,6 +21,7 @@
21
21
  "./app-contract",
22
22
  "./manifest",
23
23
  "./manifest.json",
24
+ "./operator",
24
25
  "./playground",
25
26
  "./svelte",
26
27
  "./sveltekit"
@@ -7780,7 +7781,7 @@
7780
7781
  "polymorphicAssociations": 0,
7781
7782
  "uuidColumns": 156
7782
7783
  },
7783
- "agentDoc": "# @happyvertical/smrt-users\n\nMulti-tenant identity, RBAC, hierarchical tenants, sessions, and SvelteKit auth.\n\n## Modules\n\nRead only the module relevant to the change; protocol and provisioning details\nare not prerequisites for unrelated user-package work.\n\n| Module | Scope | Module doc |\n|---|---|---|\n| `src/services/PermissionResolver.ts` | permission precedence, inherited memberships, guards, RLS, role seeding | [agents/permissions.md](agents/permissions.md) |\n| `src/services/OidcLoginService.ts`, collections and OIDC handlers | identity reconciliation, transaction boundaries, migration readiness | [agents/oidc-provisioning.md](agents/oidc-provisioning.md) |\n| `src/services/MobileAuthService.ts` | mobile handshake, bearer sessions, bootstrap extension boundary | [agents/mobile-auth.md](agents/mobile-auth.md) |\n| `src/services/TerminalAuthService.ts`, `src/services/LoginAttemptLimiter.ts`, `src/collections/LoginAttemptCollection.ts` | terminal approval concurrency, shared login budget and lockout (#3273), retry-safe database fixtures | [agents/terminal-auth-testing.md](agents/terminal-auth-testing.md) |\n| `src/services/DeviceCredentialService.ts` | per-person PIN layered on a device session (#3276), verifier seam for other credential kinds | this file, \"Security boundaries\" |\n| `src/services/PasswordCredentialService.ts`, `src/sveltekit/password-handlers.ts` | email + password sign-in and password lifecycle (#3274); shared scrypt in `credential-hash.ts` | this file, \"Security boundaries\"; README \"Password sign-in\" |\n| `src/retention.ts` | expired session/token/CLI-auth reaping and retention sweep wiring | [agents/retention.md](agents/retention.md) |\n\n## Models and authority\n\n- Users are global; tenant access comes through Membership (unique user/tenant).\n User email is normalized and globally unique through readonly nullable\n `emailKey`. `profileId` is a unique cross-package reference: at most one User\n owns each non-null Profile.\n- Tenant uses STI and a materialized hierarchy, maximum depth 10.\n `hierarchyPath`/`hierarchyLevel` are derived from `parentTenantId` by\n `Tenant.save()` on every save (any caller-supplied value is recomputed) and\n descendants are re-materialized when they change; never hand-maintain them.\n Legacy rows are backfilled with `smrt db:materialize-tenant-hierarchy`\n (`materializeTenantHierarchy()`). Tests that need a corrupt path must write it\n with raw SQL (#3036).\n- Role with `tenantId = null` is available to all tenants; `isSystem` prevents\n deletion. `inheritsToDescendants` is opt-in. Seed owner/admin/member/viewer\n through `RoleCollection.seedSystemRoles()` at application initialization.\n- Group roles apply only in their own tenant. Use `getGroupIdsForTenant()`,\n never cross-tenant `getGroupIds()`, for authorization.\n- Upward visibility is opt-in and read-only: `permissions.ancestorRead`\n ({ roles, collections, maxDepth? }) lets a DESCENDANT membership contribute\n declared `<collection>.read` at an ancestor, only when no membership resolved\n there, intersected with BOTH the role's own catalog grants and the\n principal's effective permissions in that descendant, and only for SYSTEM\n roles (a tenant-scoped role sharing a declared slug is ignored). Off by default, never\n write, never lateral, and never row visibility — sibling rows stay scoped by\n tenancy/RLS. Read the permissions module before changing it.\n- Membership DENY always wins. Direct inactive membership blocks inherited\n authority; a direct active membership pins resolution instead of unioning it\n with ancestors. Read the permissions module before changing these rules.\n- AccessRequest has no generated API/MCP/CLI operations; access it through\n `AccessRequestService`. Its JSON field is `requestContext`, not reserved\n slug-scoping `context`.\n\n## Security boundaries\n\n- Generated REST/MCP operations on identity/RBAC models are list/get only.\n Route authentication does not authorize authority mutations, and these models\n are not tenant-scoped. Use permission-gated services or explicitly checked\n consumer handlers. Generated CLI is list/get or closed (`cli: false` for\n credential/grant models) because agents shell out to it; a `cli` without\n `include` is full CRUD (#3742). Their catalog slugs stay full via\n `USERS_AUTHORITY_CATALOG_MODELS`. Preserve the registry assertions in\n `security-audit-1400.test.ts` and `issue-3742-cli-surface-lockdown.test.ts`.\n- Resource guards take the resource tenant, not the session tenant. Omit a\n session membership when targeting a different tenant; mismatches fail closed.\n `loadSessionContext().tenantAuthorization` must be checked by required-tenant\n consumers: null membership can represent inherited authority.\n- Sessions use secure UUIDs; TTL is seconds (default seven days). Access marks\n expired sessions EXPIRED. Magic-link tokens are single use.\n- `Session.authMethod` is server-set at mint time and never read from the\n client; every mint site in this package sets it. A session with\n `parentSessionId` is valid only while its parent validates\n (`loadSessionContext` enforces this; there is no FK cascade by design), may\n not switch to a tenant other than the parent's, and is revoked with its\n parent by `destroySession`.\n- Credential sign-ins reserve through `LoginAttemptLimiter` BEFORE credential\n work and key the subject on the submitted identifier, never a resolved user,\n so unknown and wrong take the same path. Reservations are fail-closed: keep\n them on failure, release on success or abort, never skip the reserve.\n Limiter writes are raw SQL and bypass the change feed; the audit sink is the\n observability seam, and it must never throw into the sign-in path.\n Subject and source budgets are sized independently (#3531); `source: false`\n ignores the source key, so a reservation then needs a subject (fail closed).\n The `source-locked` audit entry never carries a subject or caller metadata.\n- `DeviceCredentialService` accepts a person credential only from a\n first-class session whose `authMethod` is a device-enrollment method\n (`terminal` by default) and that the host's `assertEnrolledDevice` confirms.\n A layered or PIN session can never administer PINs regardless of\n permissions. PIN hashes carry a per-row salt and the configured pepper;\n treat an unset pepper as a production misconfiguration.\n- A person session carries the PERSON's authority (resolved from their own\n membership on every load), never the device account's. `Session.data` keys\n in `SESSION_DATA_KEYS` are server-set controls enforced by the model:\n `permissionCeiling` only ever intersects (malformed fails closed to none)\n and suppresses `superAdminBypass`/`systemContext`; `absoluteExpiresAt`\n bounds `extend()` and `isValid()`; `idleSeconds` overrides the resolving\n service's TTL policy. Never write them from client input. The ceiling is a\n sign-in snapshot; `singleOccupant` revokes other children only AFTER a\n successful mint. A `mustReset` sign-in mints with an empty ceiling and\n `setPin` ends that session; do not grant it authority another way.\n- `UsersPasswordCredential` is one row per person, sensitive, with no\n generated surface; `PasswordCredentialService` and its handlers are its only\n read/write paths. Sign-in normalizes the email like `emailKey`, reserves\n before work, always runs one scrypt verify (dummy hash when absent), never\n creates a user, and maps every non-rate-limit refusal to one\n `PasswordCredentialError`. It re-checks the credential after the mint (a\n rehash that keeps row and version is confirmed by re-verifying); the\n parameter-upgrade write is a guarded UPDATE that must never replace a\n rotated password, and verification against a weaker stored hash is padded\n to the policy's scrypt cost. Self-service writes are guarded on the proven\n credential (first set insert-only); session sweeps run before and after\n each write. Self-service needs the current password except for a first\n set; `users.password.manage` follows the PIN's single-tenant target\n rule and never resets the actor's own. Layered sessions never manage\n passwords; a `mustChange` sign-in mints an empty ceiling.\n `replaceForgottenPassword` (#3905, opt-in `recovery`) is the only\n self-service write without the current password: it decides on the stored\n session row (owner, first-class, no ceiling, listed non-password/pin\n `authMethod`, fresh `outOfBandProofAt` stamp) and ends every session,\n its own included. Never set that stamp from client input.\n- A layered session whose tenant differs from its parent's never loads (null\n is allowed: narrower). Limiter rows carry `retain_until`; retention must\n not fall back to a process-wide horizon.\n- `Session.parentSessionId` is the parent's bearer: sensitive, never a\n `list()` filter (raw-SQL id reads, which also keep revocation sweeps free of\n caller list bounds), never serialized to clients. `users.pin.manage` reaches\n only people whose every active membership is in the actor's tenant (the PIN\n is global per person). A sign-in re-checks the verified\n credential generation AFTER the mint (`stillValid`); keep that ordering.\n Operation guards deny outside a session's ceiling; `loadPersonSession`\n re-checks device enrollment.\n- Tenant switching verifies active membership before writing and rotates the\n session ID for non-null targets, revoking the old session. Persist the returned\n `SwitchTenantResult.sessionId`; `switchSessionTenant()` updates the cookie and\n preserves its security settings. Failed switches mutate nothing; null clears\n do not rotate, and layered sessions never rotate (a replacement would escape\n the revocation sweeps they depend on). Layers do not nest. `SessionCollection.setSessionTenant()` is unguarded and must\n never receive an untrusted tenant ID.\n- OIDC provisioning is atomic and fail-closed. Preserve exact issuer/subject\n identifiers, claim-source email verification, unique global Person ownership,\n and transaction-bound reconciliation. Read the OIDC module and canonical\n scenario matrix before changing any provisioning path.\n\n## Entry points and validation\n\n`src/sveltekit/` owns `createSessionHandler`, `createSessionCookie`,\n`destroySessionCookie`, and `switchSessionTenant`. Use README integration examples\nrather than copying application setup into these instructions.\n\nFrom the repository root:\n\n```bash\npnpm --filter @happyvertical/smrt-users test\npnpm --filter @happyvertical/smrt-users typecheck\npnpm --filter @happyvertical/smrt-users test:postgres\n```\n\nStart with the relevant test file via `test -- src/__tests__/<file>.test.ts`.\nRun `test:postgres` for RLS, principal context, OIDC, or terminal-auth database\nchanges. `typecheck` includes Svelte accessibility checks; plain `tsc` is\ninsufficient. Follow root knowledge freshness checks before shipping.\n",
7784
+ "agentDoc": "# @happyvertical/smrt-users\n\nMulti-tenant identity, RBAC, hierarchical tenants, sessions, and SvelteKit auth.\n\n## Modules\n\nRead only the module relevant to the change; protocol and provisioning details\nare not prerequisites for unrelated user-package work.\n\n| Module | Scope | Module doc |\n|---|---|---|\n| `src/services/PermissionResolver.ts` | permission precedence, inherited memberships, guards, RLS, role seeding | [agents/permissions.md](agents/permissions.md) |\n| `src/services/OidcLoginService.ts`, collections and OIDC handlers | identity reconciliation, transaction boundaries, migration readiness | [agents/oidc-provisioning.md](agents/oidc-provisioning.md) |\n| `src/services/MobileAuthService.ts` | mobile handshake, bearer sessions, bootstrap extension boundary | [agents/mobile-auth.md](agents/mobile-auth.md) |\n| `src/services/TerminalAuthService.ts`, `src/services/LoginAttemptLimiter.ts`, `src/collections/LoginAttemptCollection.ts` | terminal approval concurrency, shared login budget and lockout (#3273), retry-safe database fixtures | [agents/terminal-auth-testing.md](agents/terminal-auth-testing.md) |\n| `src/services/DeviceCredentialService.ts` | per-person PIN layered on a device session (#3276), verifier seam for other credential kinds | this file, \"Security boundaries\" |\n| `src/services/PasswordCredentialService.ts`, `src/sveltekit/password-handlers.ts` | email + password sign-in and password lifecycle (#3274); shared scrypt in `credential-hash.ts` | this file, \"Security boundaries\"; README \"Password sign-in\" |\n| `src/retention.ts` | expired session/token/CLI-auth reaping and retention sweep wiring | [agents/retention.md](agents/retention.md) |\n\n## Models and authority\n\n- Users are global; tenant access comes through Membership (unique user/tenant).\n User email is normalized and globally unique through readonly nullable\n `emailKey`. `profileId` is a unique cross-package reference: at most one User\n owns each non-null Profile.\n- Tenant uses STI and a materialized hierarchy, maximum depth 10.\n `hierarchyPath`/`hierarchyLevel` are derived from `parentTenantId` by\n `Tenant.save()` on every save (any caller-supplied value is recomputed) and\n descendants are re-materialized when they change; never hand-maintain them.\n Legacy rows are backfilled with `smrt db:materialize-tenant-hierarchy`\n (`materializeTenantHierarchy()`). Tests that need a corrupt path must write it\n with raw SQL (#3036).\n- Role with `tenantId = null` is available to all tenants; `isSystem` prevents\n deletion. `inheritsToDescendants` is opt-in. Seed owner/admin/member/viewer\n through `RoleCollection.seedSystemRoles()` at application initialization.\n- Group roles apply only in their own tenant. Use `getGroupIdsForTenant()`,\n never cross-tenant `getGroupIds()`, for authorization.\n- Upward visibility is opt-in and read-only: `permissions.ancestorRead`\n ({ roles, collections, maxDepth? }) lets a DESCENDANT membership contribute\n declared `<collection>.read` at an ancestor, only when no membership resolved\n there, intersected with BOTH the role's own catalog grants and the\n principal's effective permissions in that descendant, and only for SYSTEM\n roles (a tenant-scoped role sharing a declared slug is ignored). Off by default, never\n write, never lateral, and never row visibility — sibling rows stay scoped by\n tenancy/RLS. Read the permissions module before changing it.\n- Membership DENY always wins. Direct inactive membership blocks inherited\n authority; a direct active membership pins resolution instead of unioning it\n with ancestors. Read the permissions module before changing these rules.\n- AccessRequest has no generated API/MCP/CLI operations; access it through\n `AccessRequestService`. Its JSON field is `requestContext`, not reserved\n slug-scoping `context`.\n\n## Security boundaries\n\n- Generated REST/MCP operations on identity/RBAC models are list/get only.\n Route authentication does not authorize authority mutations, and these models\n are not tenant-scoped. Use permission-gated services or explicitly checked\n consumer handlers. Generated CLI is list/get or closed (`cli: false` for\n credential/grant models) because agents shell out to it; a `cli` without\n `include` is full CRUD (#3742). Their catalog slugs stay full via\n `USERS_AUTHORITY_CATALOG_MODELS`. Preserve the registry assertions in\n `security-audit-1400.test.ts` and `issue-3742-cli-surface-lockdown.test.ts`.\n- Resource guards take the resource tenant, not the session tenant. Omit a\n session membership when targeting a different tenant; mismatches fail closed.\n `loadSessionContext().tenantAuthorization` must be checked by required-tenant\n consumers: null membership can represent inherited authority.\n- Sessions use secure UUIDs; TTL is seconds (default seven days). Access marks\n expired sessions EXPIRED. Magic-link tokens are single use.\n- `Session.authMethod` is server-set at mint time and never read from the\n client; every mint site in this package sets it. A session with\n `parentSessionId` is valid only while its parent validates\n (`loadSessionContext` enforces this; there is no FK cascade by design), may\n not switch to a tenant other than the parent's, and is revoked with its\n parent by `destroySession`.\n- Credential sign-ins reserve through `LoginAttemptLimiter` BEFORE credential\n work and key the subject on the submitted identifier, never a resolved user,\n so unknown and wrong take the same path. Reservations are fail-closed: keep\n them on failure, release on success or abort, never skip the reserve.\n Limiter writes are raw SQL and bypass the change feed; the audit sink is the\n observability seam, and it must never throw into the sign-in path.\n Subject and source budgets are sized independently (#3531); `source: false`\n ignores the source key, so a reservation then needs a subject (fail closed).\n The `source-locked` audit entry never carries a subject or caller metadata.\n- `DeviceCredentialService` accepts a person credential only from a\n first-class session whose `authMethod` is a device-enrollment method\n (`terminal` by default) and that the host's `assertEnrolledDevice` confirms.\n A layered or PIN session can never administer PINs regardless of\n permissions. PIN hashes carry a per-row salt and the configured pepper;\n treat an unset pepper as a production misconfiguration.\n- A person session carries the PERSON's authority (resolved from their own\n membership on every load), never the device account's. `Session.data` keys\n in `SESSION_DATA_KEYS` are server-set controls enforced by the model:\n `permissionCeiling` only ever intersects (malformed fails closed to none)\n and suppresses `superAdminBypass`/`systemContext`; `absoluteExpiresAt`\n bounds `extend()` and `isValid()`; `idleSeconds` overrides the resolving\n service's TTL policy. Never write them from client input. The ceiling is a\n sign-in snapshot; `singleOccupant` revokes other children only AFTER a\n successful mint. A `mustReset` sign-in mints with an empty ceiling and\n `setPin` ends that session; do not grant it authority another way.\n- `UsersPasswordCredential` is one row per person, sensitive, with no\n generated surface; `PasswordCredentialService` and its handlers are its only\n session-authorized read/write paths. The separate Node `./operator` entrypoint\n provisions new PostgreSQL owners from trusted database custody, atomically;\n never mount it in a browser/REST/MCP handler. Exact retries verify existing\n credentials without writes; partial/conflicting identities fail closed.\n See README \"Trusted deployment owner provisioning\".\n Sign-in normalizes the email like `emailKey`, reserves\n before work, always runs one scrypt verify (dummy hash when absent), never\n creates a user, and maps every non-rate-limit refusal to one\n `PasswordCredentialError`. It re-checks the credential after the mint (a\n rehash that keeps row and version is confirmed by re-verifying); the\n parameter-upgrade write is a guarded UPDATE that must never replace a\n rotated password, and verification against a weaker stored hash is padded\n to the policy's scrypt cost. Self-service writes are guarded on the proven\n credential (first set insert-only); session sweeps run before and after\n each write. Self-service needs the current password except for a first\n set; `users.password.manage` follows the PIN's single-tenant target\n rule and never resets the actor's own. Layered sessions never manage\n passwords; a `mustChange` sign-in mints an empty ceiling.\n `replaceForgottenPassword` (#3905, opt-in `recovery`) is the only\n self-service write without the current password: it decides on the stored\n session row (owner, first-class, no ceiling, listed non-password/pin\n `authMethod`, fresh `outOfBandProofAt` stamp) and ends every session,\n its own included. Never set that stamp from client input.\n- A layered session whose tenant differs from its parent's never loads (null\n is allowed: narrower). Limiter rows carry `retain_until`; retention must\n not fall back to a process-wide horizon.\n- `Session.parentSessionId` is the parent's bearer: sensitive, never a\n `list()` filter (raw-SQL id reads, which also keep revocation sweeps free of\n caller list bounds), never serialized to clients. `users.pin.manage` reaches\n only people whose every active membership is in the actor's tenant (the PIN\n is global per person). A sign-in re-checks the verified\n credential generation AFTER the mint (`stillValid`); keep that ordering.\n Operation guards deny outside a session's ceiling; `loadPersonSession`\n re-checks device enrollment.\n- Tenant switching verifies active membership before writing and rotates the\n session ID for non-null targets, revoking the old session. Persist the returned\n `SwitchTenantResult.sessionId`; `switchSessionTenant()` updates the cookie and\n preserves its security settings. Failed switches mutate nothing; null clears\n do not rotate, and layered sessions never rotate (a replacement would escape\n the revocation sweeps they depend on). Layers do not nest. `SessionCollection.setSessionTenant()` is unguarded and must\n never receive an untrusted tenant ID.\n- OIDC provisioning is atomic and fail-closed. Preserve exact issuer/subject\n identifiers, claim-source email verification, unique global Person ownership,\n and transaction-bound reconciliation. Read the OIDC module and canonical\n scenario matrix before changing any provisioning path.\n\n## Entry points and validation\n\n`src/sveltekit/` owns `createSessionHandler`, `createSessionCookie`,\n`destroySessionCookie`, and `switchSessionTenant`. Use README integration examples\nrather than copying application setup into these instructions.\n\nFrom the repository root:\n\n```bash\npnpm --filter @happyvertical/smrt-users test\npnpm --filter @happyvertical/smrt-users typecheck\npnpm --filter @happyvertical/smrt-users test:postgres\n```\n\nStart with the relevant test file via `test -- src/__tests__/<file>.test.ts`.\nRun `test:postgres` for RLS, principal context, OIDC, or terminal-auth database\nchanges. `typecheck` includes Svelte accessibility checks; plain `tsc` is\ninsufficient. Follow root knowledge freshness checks before shipping.\n",
7784
7785
  "moduleDocs": [
7785
7786
  {
7786
7787
  "path": "agents/permissions.md",
package/dist/sveltekit.js CHANGED
@@ -1,4 +1,5 @@
1
- import { A as withSessionPermissionContext, B as resolveOidcProviderConfig, C as OperationPermissionError, F as OidcLoginError, G as DeviceCredentialForbiddenError, I as OidcLoginService, K as DeviceCredentialPolicyError, L as decodeOidcTransaction, M as MobileAuthService, N as readMobileBearerToken, P as validateMobileRedirectUri, Q as SessionService, R as encodeOidcTransaction, W as DeviceCredentialError, _ as PasswordCredentialError, a as TerminalAuthError, b as PasswordPolicyError, j as MobileAuthError, lt as LoginRateLimitError, o as TerminalAuthRateLimitError, q as DeviceCredentialService, s as TerminalAuthService, v as PasswordCredentialForbiddenError, y as PasswordCredentialService, z as getUsersOidcConfig } from "./chunks/TerminalAuthService--oSXc4nT.js";
1
+ import { M as LoginRateLimitError, d as PasswordCredentialForbiddenError, f as PasswordCredentialService, g as SessionService, p as PasswordPolicyError, u as PasswordCredentialError } from "./chunks/PasswordCredentialService-CyB9FmYp.js";
2
+ import { A as DeviceCredentialForbiddenError, C as encodeOidcTransaction, M as DeviceCredentialService, S as decodeOidcTransaction, T as resolveOidcProviderConfig, _ as MobileAuthService, a as TerminalAuthError, b as OidcLoginError, c as OperationPermissionError, g as MobileAuthError, h as withSessionPermissionContext, j as DeviceCredentialPolicyError, k as DeviceCredentialError, o as TerminalAuthRateLimitError, s as TerminalAuthService, v as readMobileBearerToken, w as getUsersOidcConfig, x as OidcLoginService, y as validateMobileRedirectUri } from "./chunks/TerminalAuthService-DlNv0fkn.js";
2
3
  import { DiscoveryArtifactValidationError, SMRT_APP_RESULT_CONTRACT, SMRT_APP_RESULT_SCHEMA, SMRT_APP_RESULT_VERSION, SMRT_DISCOVERY_CONFORMANCE_ARTIFACT_SCHEMA, SMRT_DISCOVERY_CONFORMANCE_SCHEMA, SMRT_DISCOVERY_CONFORMANCE_VERSION, SMRT_MCP_RESULT_METADATA_KEY, canonicalizeDiscoveryArtifact, createDiscoveryConformanceArtifact, deriveCommandRequirements, validateDiscoveryConformanceArtifact } from "./app-contract.js";
3
4
  import { ObjectRegistry, createClassNamePredicate, resolveCustomActionMetadata, resolveEffectiveActionMetadata } from "@happyvertical/smrt-core";
4
5
  import { createLogger } from "@happyvertical/logger";