@happyvertical/smrt-profiles 0.37.2 → 0.37.3

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.
Files changed (61) hide show
  1. package/dist/chunks/ApiKey-3DlNEc91.js +145 -0
  2. package/dist/chunks/ApiKey-3DlNEc91.js.map +1 -0
  3. package/dist/chunks/ApiKeyCollection-PwVs0qDb.js +83 -0
  4. package/dist/chunks/ApiKeyCollection-PwVs0qDb.js.map +1 -0
  5. package/dist/chunks/AuditLogCollection-CnIYU0aK.js +191 -0
  6. package/dist/chunks/AuditLogCollection-CnIYU0aK.js.map +1 -0
  7. package/dist/chunks/NostrIdentityCollection-CG6HGf6c.js +3267 -0
  8. package/dist/chunks/NostrIdentityCollection-CG6HGf6c.js.map +1 -0
  9. package/dist/chunks/OidcIdentityCollection-DiLneB7J.js +158 -0
  10. package/dist/chunks/OidcIdentityCollection-DiLneB7J.js.map +1 -0
  11. package/dist/chunks/ProfileAssetCollection-BY2Wbem3.js +93 -0
  12. package/dist/chunks/ProfileAssetCollection-BY2Wbem3.js.map +1 -0
  13. package/dist/chunks/ProfileCollection-DlhdOnDr.js +641 -0
  14. package/dist/chunks/ProfileCollection-DlhdOnDr.js.map +1 -0
  15. package/dist/chunks/ProfileMetadataCollection-CGcO4Iw_.js +105 -0
  16. package/dist/chunks/ProfileMetadataCollection-CGcO4Iw_.js.map +1 -0
  17. package/dist/chunks/ProfileMetafieldCollection-C8TX9HvN.js +142 -0
  18. package/dist/chunks/ProfileMetafieldCollection-C8TX9HvN.js.map +1 -0
  19. package/dist/chunks/ProfileRelationshipCollection-JnskbZTd.js +159 -0
  20. package/dist/chunks/ProfileRelationshipCollection-JnskbZTd.js.map +1 -0
  21. package/dist/chunks/ProfileRelationshipTermCollection-UopP7sja.js +105 -0
  22. package/dist/chunks/ProfileRelationshipTermCollection-UopP7sja.js.map +1 -0
  23. package/dist/chunks/ProfileRelationshipType-OMBn5cWR.js +98 -0
  24. package/dist/chunks/ProfileRelationshipType-OMBn5cWR.js.map +1 -0
  25. package/dist/chunks/ProfileRelationshipTypeCollection-CQu08kxF.js +54 -0
  26. package/dist/chunks/ProfileRelationshipTypeCollection-CQu08kxF.js.map +1 -0
  27. package/dist/index.js +690 -69
  28. package/dist/index.js.map +1 -1
  29. package/dist/manifest.json +2 -2
  30. package/dist/smrt-knowledge.json +9 -9
  31. package/dist/types.js +0 -2
  32. package/dist/utils.js +18 -36
  33. package/dist/utils.js.map +1 -1
  34. package/package.json +16 -16
  35. package/dist/chunks/ApiKey-B2LKEaP8.js +0 -143
  36. package/dist/chunks/ApiKey-B2LKEaP8.js.map +0 -1
  37. package/dist/chunks/ApiKeyCollection-B6Op817e.js +0 -91
  38. package/dist/chunks/ApiKeyCollection-B6Op817e.js.map +0 -1
  39. package/dist/chunks/AuditLogCollection-BYqCj0uE.js +0 -195
  40. package/dist/chunks/AuditLogCollection-BYqCj0uE.js.map +0 -1
  41. package/dist/chunks/NostrIdentityCollection-DadQBHWy.js +0 -3065
  42. package/dist/chunks/NostrIdentityCollection-DadQBHWy.js.map +0 -1
  43. package/dist/chunks/ProfileAssetCollection-CUM5QfuJ.js +0 -122
  44. package/dist/chunks/ProfileAssetCollection-CUM5QfuJ.js.map +0 -1
  45. package/dist/chunks/ProfileCollection-M2PK8bp-.js +0 -800
  46. package/dist/chunks/ProfileCollection-M2PK8bp-.js.map +0 -1
  47. package/dist/chunks/ProfileMetadataCollection-DEhmljMY.js +0 -120
  48. package/dist/chunks/ProfileMetadataCollection-DEhmljMY.js.map +0 -1
  49. package/dist/chunks/ProfileMetafieldCollection-DMKhSHXX.js +0 -184
  50. package/dist/chunks/ProfileMetafieldCollection-DMKhSHXX.js.map +0 -1
  51. package/dist/chunks/ProfileRelationshipCollection-_TsY7MHL.js +0 -189
  52. package/dist/chunks/ProfileRelationshipCollection-_TsY7MHL.js.map +0 -1
  53. package/dist/chunks/ProfileRelationshipTermCollection-CXem_qT-.js +0 -117
  54. package/dist/chunks/ProfileRelationshipTermCollection-CXem_qT-.js.map +0 -1
  55. package/dist/chunks/ProfileRelationshipType-BXBLldea.js +0 -103
  56. package/dist/chunks/ProfileRelationshipType-BXBLldea.js.map +0 -1
  57. package/dist/chunks/ProfileRelationshipTypeCollection-CF8YvLTV.js +0 -48
  58. package/dist/chunks/ProfileRelationshipTypeCollection-CF8YvLTV.js.map +0 -1
  59. package/dist/chunks/index-B9lXQy7N.js +0 -1029
  60. package/dist/chunks/index-B9lXQy7N.js.map +0 -1
  61. package/dist/types.js.map +0 -1
@@ -0,0 +1,145 @@
1
+ import { x as __exportAll } from "./NostrIdentityCollection-CG6HGf6c.js";
2
+ import { SmrtObject, foreignKey, smrt } from "@happyvertical/smrt-core";
3
+ import { createHash, randomBytes } from "node:crypto";
4
+ //#region src/models/ApiKey.ts
5
+ var ApiKey_exports = /* @__PURE__ */ __exportAll({ ApiKey: () => ApiKey });
6
+ var __defProp = Object.defineProperty;
7
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
+ var __decorateClass = (decorators, target, key, kind) => {
9
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
10
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
11
+ if (kind && result) __defProp(target, key, result);
12
+ return result;
13
+ };
14
+ var ApiKey = class extends SmrtObject {
15
+ profileId;
16
+ /**
17
+ * SHA-256 hash of the API key
18
+ */
19
+ keyHash = "";
20
+ /**
21
+ * First 8 characters of the key for identification (e.g., "sk_live_a1b2...")
22
+ */
23
+ keyPrefix = "";
24
+ /**
25
+ * Human-readable name for the key (e.g., "CI Bot", "Local CLI")
26
+ */
27
+ name = "";
28
+ /**
29
+ * Scopes/permissions for this key
30
+ */
31
+ scopes = [];
32
+ /**
33
+ * Last time this key was used
34
+ */
35
+ lastUsedAt = null;
36
+ /**
37
+ * When this key expires (null = never)
38
+ */
39
+ expiresAt = null;
40
+ /**
41
+ * When this key was revoked (null = active)
42
+ */
43
+ revokedAt = null;
44
+ constructor(options = {}) {
45
+ super(options);
46
+ if (options.profileId) this.profileId = options.profileId;
47
+ if (options.name) this.name = options.name;
48
+ if (options.scopes) this.scopes = options.scopes;
49
+ if (options.expiresAt !== void 0) this.expiresAt = options.expiresAt;
50
+ }
51
+ /**
52
+ * Get the linked Profile
53
+ */
54
+ async getProfile() {
55
+ return await this.getRelated("profileId");
56
+ }
57
+ /**
58
+ * Check if this key is valid (not expired, not revoked)
59
+ */
60
+ isValid() {
61
+ if (this.revokedAt) return false;
62
+ if (this.expiresAt && this.expiresAt < /* @__PURE__ */ new Date()) return false;
63
+ return true;
64
+ }
65
+ /**
66
+ * Check if this key has a specific scope
67
+ */
68
+ hasScope(scope) {
69
+ return this.scopes.includes(scope) || this.scopes.includes("*");
70
+ }
71
+ /**
72
+ * Revoke this key
73
+ */
74
+ async revoke() {
75
+ this.revokedAt = /* @__PURE__ */ new Date();
76
+ await this.save();
77
+ }
78
+ /**
79
+ * Record usage of this key
80
+ */
81
+ async recordUsage() {
82
+ this.lastUsedAt = /* @__PURE__ */ new Date();
83
+ await this.save();
84
+ }
85
+ /**
86
+ * Hash an API key
87
+ */
88
+ static hashKey(key) {
89
+ return createHash("sha256").update(key).digest("hex");
90
+ }
91
+ /**
92
+ * Generate a new API key for a profile
93
+ */
94
+ static async generate(profile, options) {
95
+ const key = `sk_live_${randomBytes(32).toString("hex")}`;
96
+ const keyPrefix = key.substring(0, 16);
97
+ const keyHash = ApiKey.hashKey(key);
98
+ const apiKey = new ApiKey({
99
+ db: options.db || profile.options?.db,
100
+ profileId: profile.id,
101
+ name: options.name,
102
+ scopes: options.scopes || ["*"],
103
+ expiresAt: options.expiresAt ?? null
104
+ });
105
+ apiKey.keyHash = keyHash;
106
+ apiKey.keyPrefix = keyPrefix;
107
+ await apiKey.initialize();
108
+ await apiKey.save();
109
+ return {
110
+ key,
111
+ apiKey
112
+ };
113
+ }
114
+ /**
115
+ * Verify an API key and return the ApiKey record if valid
116
+ */
117
+ static async verify(key, options = {}) {
118
+ const keyHash = ApiKey.hashKey(key);
119
+ const { ApiKeyCollection } = await import("./ApiKeyCollection-PwVs0qDb.js").then((n) => n.n);
120
+ const apiKey = await (await ApiKeyCollection.create(options)).findOne({ where: { keyHash } });
121
+ if (!apiKey) return null;
122
+ if (!apiKey.isValid()) return null;
123
+ await apiKey.recordUsage();
124
+ return apiKey;
125
+ }
126
+ };
127
+ __decorateClass([foreignKey("Profile", { required: true })], ApiKey.prototype, "profileId", 2);
128
+ ApiKey = __decorateClass([smrt({
129
+ tableName: "api_keys",
130
+ api: { include: ["list", "get"] },
131
+ mcp: { include: ["list", "get"] },
132
+ cli: {
133
+ include: [
134
+ "list",
135
+ "get",
136
+ "create",
137
+ "revoke"
138
+ ],
139
+ skipApiCheck: true
140
+ }
141
+ })], ApiKey);
142
+ //#endregion
143
+ export { ApiKey_exports as n, ApiKey as t };
144
+
145
+ //# sourceMappingURL=ApiKey-3DlNEc91.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ApiKey-3DlNEc91.js","names":[],"sources":["../../src/models/ApiKey.ts"],"sourcesContent":["/**\n * ApiKey - API keys for CLI and CI authentication\n *\n * Provides secure API key management with hashing, scopes, and expiration.\n * Keys are stored as hashes - the plaintext is only returned on creation.\n */\n\nimport { createHash, randomBytes } from 'node:crypto';\nimport {\n foreignKey,\n SmrtObject,\n type SmrtObjectOptions,\n smrt,\n} from '@happyvertical/smrt-core';\nimport type { Profile } from './Profile';\n\nexport interface ApiKeyOptions extends SmrtObjectOptions {\n profileId?: string;\n name?: string;\n scopes?: string[];\n expiresAt?: Date | null;\n}\n\nexport interface GenerateKeyResult {\n key: string;\n apiKey: ApiKey;\n}\n\n@smrt({\n tableName: 'api_keys',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n // create/revoke are admin operations invoked in-process via the CLI; only\n // read-only list/get are exposed over HTTP.\n cli: { include: ['list', 'get', 'create', 'revoke'], skipApiCheck: true },\n})\nexport class ApiKey extends SmrtObject {\n /**\n * Link to the Profile (Person, Organization, Bot)\n */\n @foreignKey('Profile', { required: true })\n profileId?: string;\n\n /**\n * SHA-256 hash of the API key\n */\n keyHash: string = '';\n\n /**\n * First 8 characters of the key for identification (e.g., \"sk_live_a1b2...\")\n */\n keyPrefix: string = '';\n\n /**\n * Human-readable name for the key (e.g., \"CI Bot\", \"Local CLI\")\n */\n name: string = '';\n\n /**\n * Scopes/permissions for this key\n */\n scopes: string[] = [];\n\n /**\n * Last time this key was used\n */\n lastUsedAt: Date | null = null;\n\n /**\n * When this key expires (null = never)\n */\n expiresAt: Date | null = null;\n\n /**\n * When this key was revoked (null = active)\n */\n revokedAt: Date | null = null;\n\n constructor(options: ApiKeyOptions = {}) {\n super(options);\n if (options.profileId) this.profileId = options.profileId;\n if (options.name) this.name = options.name;\n if (options.scopes) this.scopes = options.scopes;\n if (options.expiresAt !== undefined) this.expiresAt = options.expiresAt;\n }\n\n /**\n * Get the linked Profile\n */\n async getProfile(): Promise<Profile | null> {\n return (await this.getRelated('profileId')) as Profile | null;\n }\n\n /**\n * Check if this key is valid (not expired, not revoked)\n */\n isValid(): boolean {\n if (this.revokedAt) return false;\n if (this.expiresAt && this.expiresAt < new Date()) return false;\n return true;\n }\n\n /**\n * Check if this key has a specific scope\n */\n hasScope(scope: string): boolean {\n return this.scopes.includes(scope) || this.scopes.includes('*');\n }\n\n /**\n * Revoke this key\n */\n async revoke(): Promise<void> {\n this.revokedAt = new Date();\n await this.save();\n }\n\n /**\n * Record usage of this key\n */\n async recordUsage(): Promise<void> {\n this.lastUsedAt = new Date();\n await this.save();\n }\n\n /**\n * Hash an API key\n */\n static hashKey(key: string): string {\n return createHash('sha256').update(key).digest('hex');\n }\n\n /**\n * Generate a new API key for a profile\n */\n static async generate(\n profile: Profile,\n options: {\n name: string;\n scopes?: string[];\n expiresAt?: Date | null;\n db?: SmrtObjectOptions['db'];\n },\n ): Promise<GenerateKeyResult> {\n // Generate a random key: sk_live_<32 random bytes as hex>\n const randomPart = randomBytes(32).toString('hex');\n const key = `sk_live_${randomPart}`;\n const keyPrefix = key.substring(0, 16);\n const keyHash = ApiKey.hashKey(key);\n\n const apiKey = new ApiKey({\n db: options.db || profile.options?.db,\n profileId: profile.id as string,\n name: options.name,\n scopes: options.scopes || ['*'],\n expiresAt: options.expiresAt ?? null,\n });\n apiKey.keyHash = keyHash;\n apiKey.keyPrefix = keyPrefix;\n\n await apiKey.initialize();\n await apiKey.save();\n\n return { key, apiKey };\n }\n\n /**\n * Verify an API key and return the ApiKey record if valid\n */\n static async verify(\n key: string,\n options: SmrtObjectOptions = {},\n ): Promise<ApiKey | null> {\n const keyHash = ApiKey.hashKey(key);\n\n const { ApiKeyCollection } = await import(\n '../collections/ApiKeyCollection'\n );\n const collection = await ApiKeyCollection.create(options);\n\n const apiKey = await collection.findOne({\n where: { keyHash },\n });\n\n if (!apiKey) return null;\n if (!apiKey.isValid()) return null;\n\n // Record usage\n await apiKey.recordUsage();\n\n return apiKey;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAoCO,IAAM,SAAN,cAAqB,WAAW;CAKrC;;;;CAKA,UAAkB;;;;CAKlB,YAAoB;;;;CAKpB,OAAe;;;;CAKf,SAAmB,CAAC;;;;CAKpB,aAA0B;;;;CAK1B,YAAyB;;;;CAKzB,YAAyB;CAEzB,YAAY,UAAyB,CAAC,GAAG;EACvC,MAAM,OAAO;EACb,IAAI,QAAQ,WAAW,KAAK,YAAY,QAAQ;EAChD,IAAI,QAAQ,MAAM,KAAK,OAAO,QAAQ;EACtC,IAAI,QAAQ,QAAQ,KAAK,SAAS,QAAQ;EAC1C,IAAI,QAAQ,cAAc,KAAA,GAAW,KAAK,YAAY,QAAQ;CAChE;;;;CAKA,MAAM,aAAsC;EAC1C,OAAQ,MAAM,KAAK,WAAW,WAAW;CAC3C;;;;CAKA,UAAmB;EACjB,IAAI,KAAK,WAAW,OAAO;EAC3B,IAAI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,OAAO,QAAQ,GAAG,OAAO;EAG9B,MAAM,OAAO,YAAY;EAEzB,OAAO;CACT;AACF;AAvJE,gBAAA,CADC,WAAW,WAAW,EAAE,UAAU,KAAK,CAAC,CAAA,GAJ9B,OAKX,WAAA,aAAA,CAAA;AALW,SAAN,gBAAA,CARN,KAAK;CACJ,WAAW;CACX,KAAK,EAAE,SAAS,CAAC,QAAQ,KAAK,EAAE;CAChC,KAAK,EAAE,SAAS,CAAC,QAAQ,KAAK,EAAE;CAGhC,KAAK;EAAE,SAAS;GAAC;GAAQ;GAAO;GAAU;EAAQ;EAAG,cAAc;CAAK;AAC1E,CAAC,CAAA,GACY,MAAA"}
@@ -0,0 +1,83 @@
1
+ import { x as __exportAll } from "./NostrIdentityCollection-CG6HGf6c.js";
2
+ import { t as ApiKey } from "./ApiKey-3DlNEc91.js";
3
+ import { SmrtCollection } from "@happyvertical/smrt-core";
4
+ //#region src/collections/ApiKeyCollection.ts
5
+ var ApiKeyCollection_exports = /* @__PURE__ */ __exportAll({ ApiKeyCollection: () => ApiKeyCollection });
6
+ var ApiKeyCollection = class extends SmrtCollection {
7
+ static _itemClass = ApiKey;
8
+ /**
9
+ * Find all keys for a profile
10
+ */
11
+ async findByProfile(profileId) {
12
+ return await this.list({ where: { profileId } });
13
+ }
14
+ /**
15
+ * Find active (non-revoked, non-expired) keys for a profile
16
+ */
17
+ async findActiveByProfile(profileId) {
18
+ return (await this.findByProfile(profileId)).filter((key) => key.isValid());
19
+ }
20
+ /**
21
+ * Find key by hash
22
+ */
23
+ async findByHash(keyHash) {
24
+ return await this.findOne({ where: { keyHash } });
25
+ }
26
+ /**
27
+ * Verify an API key string and return the record if valid
28
+ */
29
+ async verify(key) {
30
+ const keyHash = ApiKey.hashKey(key);
31
+ const apiKey = await this.findByHash(keyHash);
32
+ if (!apiKey) return null;
33
+ if (!apiKey.isValid()) return null;
34
+ await apiKey.recordUsage();
35
+ return apiKey;
36
+ }
37
+ /**
38
+ * Generate a new key for a profile
39
+ */
40
+ async generateForProfile(profile, options) {
41
+ return await ApiKey.generate(profile, {
42
+ ...options,
43
+ db: this.options.db
44
+ });
45
+ }
46
+ /**
47
+ * Revoke all keys for a profile
48
+ */
49
+ async revokeAllForProfile(profileId) {
50
+ const keys = await this.findActiveByProfile(profileId);
51
+ for (const key of keys) await key.revoke();
52
+ return keys.length;
53
+ }
54
+ /**
55
+ * Revoke a specific key by prefix
56
+ */
57
+ async revokeByPrefix(keyPrefix) {
58
+ const key = await this.findOne({ where: { keyPrefix } });
59
+ if (key && key.isValid()) {
60
+ await key.revoke();
61
+ return true;
62
+ }
63
+ return false;
64
+ }
65
+ /**
66
+ * Clean up expired keys (soft delete by setting revokedAt)
67
+ */
68
+ async cleanupExpired() {
69
+ const now = /* @__PURE__ */ new Date();
70
+ const allKeys = await this.list({});
71
+ let cleaned = 0;
72
+ for (const key of allKeys) if (key.expiresAt && key.expiresAt < now && !key.revokedAt) {
73
+ key.revokedAt = now;
74
+ await key.save();
75
+ cleaned++;
76
+ }
77
+ return cleaned;
78
+ }
79
+ };
80
+ //#endregion
81
+ export { ApiKeyCollection_exports as n, ApiKeyCollection as t };
82
+
83
+ //# sourceMappingURL=ApiKeyCollection-PwVs0qDb.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ApiKeyCollection-PwVs0qDb.js","names":[],"sources":["../../src/collections/ApiKeyCollection.ts"],"sourcesContent":["/**\n * ApiKeyCollection - Collection for managing API keys\n */\n\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport { ApiKey, type GenerateKeyResult } from '../models/ApiKey';\nimport type { Profile } from '../models/Profile';\n\nexport class ApiKeyCollection extends SmrtCollection<ApiKey> {\n static readonly _itemClass = ApiKey;\n\n /**\n * Find all keys for a profile\n */\n async findByProfile(profileId: string): Promise<ApiKey[]> {\n return await this.list({\n where: { profileId },\n });\n }\n\n /**\n * Find active (non-revoked, non-expired) keys for a profile\n */\n async findActiveByProfile(profileId: string): Promise<ApiKey[]> {\n const keys = await this.findByProfile(profileId);\n return keys.filter((key) => key.isValid());\n }\n\n /**\n * Find key by hash\n */\n async findByHash(keyHash: string): Promise<ApiKey | null> {\n return await this.findOne({\n where: { keyHash },\n });\n }\n\n /**\n * Verify an API key string and return the record if valid\n */\n async verify(key: string): Promise<ApiKey | null> {\n const keyHash = ApiKey.hashKey(key);\n const apiKey = await this.findByHash(keyHash);\n\n if (!apiKey) return null;\n if (!apiKey.isValid()) return null;\n\n // Record usage\n await apiKey.recordUsage();\n\n return apiKey;\n }\n\n /**\n * Generate a new key for a profile\n */\n async generateForProfile(\n profile: Profile,\n options: {\n name: string;\n scopes?: string[];\n expiresAt?: Date | null;\n },\n ): Promise<GenerateKeyResult> {\n return await ApiKey.generate(profile, {\n ...options,\n db: this.options.db,\n });\n }\n\n /**\n * Revoke all keys for a profile\n */\n async revokeAllForProfile(profileId: string): Promise<number> {\n const keys = await this.findActiveByProfile(profileId);\n for (const key of keys) {\n await key.revoke();\n }\n return keys.length;\n }\n\n /**\n * Revoke a specific key by prefix\n */\n async revokeByPrefix(keyPrefix: string): Promise<boolean> {\n const key = await this.findOne({\n where: { keyPrefix },\n });\n\n if (key && key.isValid()) {\n await key.revoke();\n return true;\n }\n return false;\n }\n\n /**\n * Clean up expired keys (soft delete by setting revokedAt)\n */\n async cleanupExpired(): Promise<number> {\n const now = new Date();\n const allKeys = await this.list({});\n let cleaned = 0;\n\n for (const key of allKeys) {\n if (key.expiresAt && key.expiresAt < now && !key.revokedAt) {\n key.revokedAt = now;\n await key.save();\n cleaned++;\n }\n }\n\n return cleaned;\n }\n}\n"],"mappings":";;;;;AAQO,IAAM,mBAAN,cAA+B,eAAuB;CAC3D,OAAgB,aAAa;;;;CAK7B,MAAM,cAAc,WAAsC;EACxD,OAAO,MAAM,KAAK,KAAK,EACrB,OAAO,EAAE,UAAU,EACrB,CAAC;CACH;;;;CAKA,MAAM,oBAAoB,WAAsC;EAE9D,QAAO,MADY,KAAK,cAAc,SAAS,EAAA,CACnC,QAA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ertical/smrt-core";
3
+ import { TenantScoped, tenantId } from "@happyvertical/smrt-tenancy";
4
+ //#region src/models/AuditLog.ts
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __decorateClass = (decorators, target, key, kind) => {
8
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
9
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
10
+ if (kind && result) __defProp(target, key, result);
11
+ return result;
12
+ };
13
+ var AuditLog = class extends SmrtObject {
14
+ tenantId = null;
15
+ profileId;
16
+ /**
17
+ * Action performed (e.g., 'issue.update', 'feedback.incorporate')
18
+ */
19
+ action = "";
20
+ /**
21
+ * Type of resource affected (e.g., 'Issue', 'Repository')
22
+ */
23
+ resourceType = "";
24
+ /**
25
+ * ID of the affected resource
26
+ */
27
+ resourceId = "";
28
+ /**
29
+ * Source of the action
30
+ */
31
+ source = "web";
32
+ /**
33
+ * Additional context (CI run ID, request ID, etc.)
34
+ */
35
+ metadata = {};
36
+ onBehalfOfId;
37
+ constructor(options = {}) {
38
+ super(options);
39
+ if (options.profileId) this.profileId = options.profileId;
40
+ if (options.action) this.action = options.action;
41
+ if (options.resourceType) this.resourceType = options.resourceType;
42
+ if (options.resourceId) this.resourceId = options.resourceId;
43
+ if (options.source) this.source = options.source;
44
+ if (options.metadata) this.metadata = options.metadata;
45
+ if (options.onBehalfOfId !== void 0) this.onBehalfOfId = options.onBehalfOfId;
46
+ }
47
+ /**
48
+ * Get the profile who performed the action
49
+ */
50
+ async getProfile() {
51
+ return await this.getRelated("profileId");
52
+ }
53
+ /**
54
+ * Get the profile on whose behalf the action was performed (if any)
55
+ */
56
+ async getOnBehalfOf() {
57
+ if (!this.onBehalfOfId) return null;
58
+ return await this.getRelated("onBehalfOfId");
59
+ }
60
+ /**
61
+ * Get the effective actor (onBehalfOf if set, otherwise profile)
62
+ */
63
+ async getEffectiveActor() {
64
+ const onBehalfOf = await this.getOnBehalfOf();
65
+ if (onBehalfOf) return onBehalfOf;
66
+ return await this.getProfile();
67
+ }
68
+ /**
69
+ * Create an audit log entry
70
+ */
71
+ static async record(options) {
72
+ const log = new AuditLog({
73
+ ...options,
74
+ profileId: options.profile.id,
75
+ onBehalfOfId: options.onBehalfOf?.id
76
+ });
77
+ await log.initialize();
78
+ await log.save();
79
+ return log;
80
+ }
81
+ };
82
+ __decorateClass([tenantId({ nullable: true })], AuditLog.prototype, "tenantId", 2);
83
+ __decorateClass([foreignKey("Profile", { required: true })], AuditLog.prototype, "profileId", 2);
84
+ __decorateClass([foreignKey("Profile", { nullable: true })], AuditLog.prototype, "onBehalfOfId", 2);
85
+ AuditLog = __decorateClass([TenantScoped({
86
+ mode: "optional",
87
+ allowSuperAdminBypass: true
88
+ }), smrt({
89
+ tableName: "audit_logs",
90
+ api: { include: ["list", "get"] },
91
+ mcp: { include: ["list", "get"] },
92
+ cli: { include: ["list"] }
93
+ })], AuditLog);
94
+ //#endregion
95
+ //#region src/collections/AuditLogCollection.ts
96
+ var AuditLogCollection_exports = /* @__PURE__ */ __exportAll({ AuditLogCollection: () => AuditLogCollection });
97
+ var AuditLogCollection = class extends SmrtCollection {
98
+ static _itemClass = AuditLog;
99
+ /**
100
+ * Find logs for a profile (actions they performed)
101
+ */
102
+ async findByProfile(profileId) {
103
+ return await this.list({
104
+ where: { profileId },
105
+ orderBy: "createdAt DESC"
106
+ });
107
+ }
108
+ /**
109
+ * Find logs for a resource
110
+ */
111
+ async findByResource(resourceType, resourceId) {
112
+ return await this.list({
113
+ where: {
114
+ resourceType,
115
+ resourceId
116
+ },
117
+ orderBy: "createdAt DESC"
118
+ });
119
+ }
120
+ /**
121
+ * Find logs by action type
122
+ */
123
+ async findByAction(action) {
124
+ return await this.list({
125
+ where: { action },
126
+ orderBy: "createdAt DESC"
127
+ });
128
+ }
129
+ /**
130
+ * Find logs by source
131
+ */
132
+ async findBySource(source) {
133
+ return await this.list({
134
+ where: { source },
135
+ orderBy: "createdAt DESC"
136
+ });
137
+ }
138
+ /**
139
+ * Find logs where actions were performed on behalf of someone
140
+ */
141
+ async findOnBehalfOf(profileId) {
142
+ return await this.list({
143
+ where: { onBehalfOfId: profileId },
144
+ orderBy: "createdAt DESC"
145
+ });
146
+ }
147
+ /**
148
+ * Record a new audit log entry
149
+ */
150
+ async record(options) {
151
+ const log = new AuditLog({
152
+ ...this.options,
153
+ profileId: options.profile.id,
154
+ action: options.action,
155
+ resourceType: options.resourceType,
156
+ resourceId: options.resourceId,
157
+ source: options.source || "web",
158
+ metadata: options.metadata || {},
159
+ onBehalfOfId: options.onBehalfOf?.id
160
+ });
161
+ await log.initialize();
162
+ await log.save();
163
+ return log;
164
+ }
165
+ /**
166
+ * Get recent activity for a profile
167
+ */
168
+ async getRecentActivity(profileId, limit = 50) {
169
+ return await this.list({
170
+ where: { profileId },
171
+ orderBy: "createdAt DESC",
172
+ limit
173
+ });
174
+ }
175
+ /**
176
+ * Get activity timeline for a resource
177
+ */
178
+ async getResourceTimeline(resourceType, resourceId) {
179
+ return await this.list({
180
+ where: {
181
+ resourceType,
182
+ resourceId
183
+ },
184
+ orderBy: "createdAt ASC"
185
+ });
186
+ }
187
+ };
188
+ //#endregion
189
+ export { AuditLogCollection_exports as n, AuditLog as r, AuditLogCollection as t };
190
+
191
+ //# sourceMappingURL=AuditLogCollection-CnIYU0aK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AuditLogCollection-CnIYU0aK.js","names":[],"sources":["../../src/models/AuditLog.ts","../../src/collections/AuditLogCollection.ts"],"sourcesContent":["/**\n * AuditLog - Tracks all actions for full audit trail\n *\n * Records who did what, when, and how (web, CLI, CI, webhook, MCP).\n * Supports pass-through identity for CI workflows.\n */\n\nimport {\n foreignKey,\n SmrtObject,\n type SmrtObjectOptions,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport type { Profile } from './Profile';\n\nexport type AuditSource = 'web' | 'cli' | 'ci' | 'webhook' | 'mcp';\n\nexport interface AuditLogOptions extends SmrtObjectOptions {\n profileId?: string;\n action?: string;\n resourceType?: string;\n resourceId?: string;\n source?: AuditSource;\n metadata?: Record<string, unknown>;\n onBehalfOfId?: string | null;\n tenantId?: string | null;\n}\n\n@TenantScoped({ mode: 'optional', allowSuperAdminBypass: true })\n@smrt({\n tableName: 'audit_logs',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: { include: ['list'] },\n})\nexport class AuditLog extends SmrtObject {\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n /**\n * The profile who performed the action\n */\n @foreignKey('Profile', { required: true })\n profileId?: string;\n\n /**\n * Action performed (e.g., 'issue.update', 'feedback.incorporate')\n */\n action: string = '';\n\n /**\n * Type of resource affected (e.g., 'Issue', 'Repository')\n */\n resourceType: string = '';\n\n /**\n * ID of the affected resource\n */\n resourceId: string = '';\n\n /**\n * Source of the action\n */\n source: AuditSource = 'web';\n\n /**\n * Additional context (CI run ID, request ID, etc.)\n */\n metadata: Record<string, unknown> = {};\n\n /**\n * For pass-through identity in CI - the actual person who triggered\n */\n @foreignKey('Profile', { nullable: true })\n onBehalfOfId?: string | null;\n\n constructor(options: AuditLogOptions = {}) {\n super(options);\n if (options.profileId) this.profileId = options.profileId;\n if (options.action) this.action = options.action;\n if (options.resourceType) this.resourceType = options.resourceType;\n if (options.resourceId) this.resourceId = options.resourceId;\n if (options.source) this.source = options.source;\n if (options.metadata) this.metadata = options.metadata;\n if (options.onBehalfOfId !== undefined)\n this.onBehalfOfId = options.onBehalfOfId;\n }\n\n /**\n * Get the profile who performed the action\n */\n async getProfile(): Promise<Profile | null> {\n return (await this.getRelated('profileId')) as Profile | null;\n }\n\n /**\n * Get the profile on whose behalf the action was performed (if any)\n */\n async getOnBehalfOf(): Promise<Profile | null> {\n if (!this.onBehalfOfId) return null;\n return (await this.getRelated('onBehalfOfId')) as Profile | null;\n }\n\n /**\n * Get the effective actor (onBehalfOf if set, otherwise profile)\n */\n async getEffectiveActor(): Promise<Profile | null> {\n const onBehalfOf = await this.getOnBehalfOf();\n if (onBehalfOf) return onBehalfOf;\n return await this.getProfile();\n }\n\n /**\n * Create an audit log entry\n */\n static async record(\n options: AuditLogOptions & {\n profile: Profile;\n onBehalfOf?: Profile | null;\n },\n ): Promise<AuditLog> {\n const log = new AuditLog({\n ...options,\n profileId: options.profile.id as string,\n onBehalfOfId: options.onBehalfOf?.id as string | undefined,\n });\n await log.initialize();\n await log.save();\n return log;\n }\n}\n","/**\n * AuditLogCollection - Collection for querying audit logs\n */\n\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport { AuditLog, type AuditSource } from '../models/AuditLog';\nimport type { Profile } from '../models/Profile';\n\nexport class AuditLogCollection extends SmrtCollection<AuditLog> {\n static readonly _itemClass = AuditLog;\n\n /**\n * Find logs for a profile (actions they performed)\n */\n async findByProfile(profileId: string): Promise<AuditLog[]> {\n return await this.list({\n where: { profileId },\n orderBy: 'createdAt DESC',\n });\n }\n\n /**\n * Find logs for a resource\n */\n async findByResource(\n resourceType: string,\n resourceId: string,\n ): Promise<AuditLog[]> {\n return await this.list({\n where: { resourceType, resourceId },\n orderBy: 'createdAt DESC',\n });\n }\n\n /**\n * Find logs by action type\n */\n async findByAction(action: string): Promise<AuditLog[]> {\n return await this.list({\n where: { action },\n orderBy: 'createdAt DESC',\n });\n }\n\n /**\n * Find logs by source\n */\n async findBySource(source: AuditSource): Promise<AuditLog[]> {\n return await this.list({\n where: { source },\n orderBy: 'createdAt DESC',\n });\n }\n\n /**\n * Find logs where actions were performed on behalf of someone\n */\n async findOnBehalfOf(profileId: string): Promise<AuditLog[]> {\n return await this.list({\n where: { onBehalfOfId: profileId },\n orderBy: 'createdAt DESC',\n });\n }\n\n /**\n * Record a new audit log entry\n */\n async record(options: {\n profile: Profile;\n action: string;\n resourceType: string;\n resourceId: string;\n source?: AuditSource;\n metadata?: Record<string, unknown>;\n onBehalfOf?: Profile | null;\n }): Promise<AuditLog> {\n const log = new AuditLog({\n ...this.options,\n profileId: options.profile.id as string,\n action: options.action,\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n source: options.source || 'web',\n metadata: options.metadata || {},\n onBehalfOfId: options.onBehalfOf?.id as string | undefined,\n });\n await log.initialize();\n await log.save();\n return log;\n }\n\n /**\n * Get recent activity for a profile\n */\n async getRecentActivity(\n profileId: string,\n limit: number = 50,\n ): Promise<AuditLog[]> {\n return await this.list({\n where: { profileId },\n orderBy: 'createdAt DESC',\n limit,\n });\n }\n\n /**\n * Get activity timeline for a resource\n */\n async getResourceTimeline(\n resourceType: string,\n resourceId: string,\n ): Promise<AuditLog[]> {\n return await this.list({\n where: { resourceType, resourceId },\n orderBy: 'createdAt ASC',\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;AAoCO,IAAM,WAAN,cAAuB,WAAW;CAEvC,WAA0B;CAM1B;;;;CAKA,SAAiB;;;;CAKjB,eAAuB;;;;CAKvB,aAAqB;;;;CAKrB,SAAsB;;;;CAKtB,WAAoC,CAAC;CAMrC;CAEA,YAAY,UAA2B,CAAC,GAAG;EACzC,MAAM,OAAO;EACb,IAAI,QAAQ,WAAW,KAAK,YAAY,QAAQ;EAChD,IAAI,QAAQ,QAAQ,KAAK,SAAS,QAAQ;EAC1C,IAAI,QAAQ,cAAc,KAAK,eAAe,QAAQ;EACtD,IAAI,QAAQ,YAAY,KAAK,aAAa,QAAQ;EAClD,IAAI,QAAQ,QAAQ,KAAK,SAAS,QAAQ;EAC1C,IAAI,QAAQ,UAAU,KAAK,WAAW,QAAQ;EAC9C,IAAI,QAAQ,iBAAiB,KAAA,GAC3B,KAAK,eAAe,QAAQ;CAChC;;;;CAKA,MAAM,aAAsC;EAC1C,OAAQ,MAAM,KAAK,WAAW,WAAW;CAC3C;;;;CAKA,MAAM,gBAAyC;EAC7C,IAAI,CAAC,KAAK,cAAc,OAAO;EAC/B,OAAQ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