@happyvertical/smrt-profiles 0.39.13 → 0.39.15

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 (54) hide show
  1. package/AGENTS.md +69 -5
  2. package/README.md +101 -50
  3. package/dist/chunks/{ApiKey-BrNyaaZN.js → ApiKey-Br9NGBnr.js} +3 -3
  4. package/dist/chunks/{ApiKey-BrNyaaZN.js.map → ApiKey-Br9NGBnr.js.map} +1 -1
  5. package/dist/chunks/{ApiKeyCollection-DNhDkS7O.js → ApiKeyCollection-CrTjdMz8.js} +3 -3
  6. package/dist/chunks/{ApiKeyCollection-DNhDkS7O.js.map → ApiKeyCollection-CrTjdMz8.js.map} +1 -1
  7. package/dist/chunks/{AuditLogCollection-CnIYU0aK.js → AuditLogCollection-BBIEI6BD.js} +2 -2
  8. package/dist/chunks/{AuditLogCollection-CnIYU0aK.js.map → AuditLogCollection-BBIEI6BD.js.map} +1 -1
  9. package/dist/chunks/{NostrIdentityCollection-CG6HGf6c.js → NostrIdentity-DF_a_WZk.js} +6 -125
  10. package/dist/chunks/NostrIdentity-DF_a_WZk.js.map +1 -0
  11. package/dist/chunks/NostrIdentityCollection-BRYUgt47.js +124 -0
  12. package/dist/chunks/NostrIdentityCollection-BRYUgt47.js.map +1 -0
  13. package/dist/chunks/OidcIdentity-ChkiT6hg.js +111 -0
  14. package/dist/chunks/OidcIdentity-ChkiT6hg.js.map +1 -0
  15. package/dist/chunks/OidcIdentityCollection-Ce4yv8p0.js +76 -0
  16. package/dist/chunks/OidcIdentityCollection-Ce4yv8p0.js.map +1 -0
  17. package/dist/chunks/{ProfileAssetCollection-DzUwbtTq.js → ProfileAssetCollection-CtlvXbGy.js} +3 -3
  18. package/dist/chunks/{ProfileAssetCollection-DzUwbtTq.js.map → ProfileAssetCollection-CtlvXbGy.js.map} +1 -1
  19. package/dist/chunks/ProfileCollection-Bix9yAiy.js +1161 -0
  20. package/dist/chunks/ProfileCollection-Bix9yAiy.js.map +1 -0
  21. package/dist/chunks/{ProfileMetadataCollection-CGcO4Iw_.js → ProfileMetadataCollection-loKVv_pj.js} +2 -2
  22. package/dist/chunks/{ProfileMetadataCollection-CGcO4Iw_.js.map → ProfileMetadataCollection-loKVv_pj.js.map} +1 -1
  23. package/dist/chunks/{ProfileMetafieldCollection-C8TX9HvN.js → ProfileMetafieldCollection-CACMY1hl.js} +2 -2
  24. package/dist/chunks/{ProfileMetafieldCollection-C8TX9HvN.js.map → ProfileMetafieldCollection-CACMY1hl.js.map} +1 -1
  25. package/dist/chunks/{ProfileRelationshipCollection-JnskbZTd.js → ProfileRelationshipCollection-CzQKfvMy.js} +5 -5
  26. package/dist/chunks/{ProfileRelationshipCollection-JnskbZTd.js.map → ProfileRelationshipCollection-CzQKfvMy.js.map} +1 -1
  27. package/dist/chunks/{ProfileRelationshipTermCollection-UopP7sja.js → ProfileRelationshipTermCollection-DzmU48P6.js} +2 -2
  28. package/dist/chunks/{ProfileRelationshipTermCollection-UopP7sja.js.map → ProfileRelationshipTermCollection-DzmU48P6.js.map} +1 -1
  29. package/dist/chunks/{ProfileRelationshipType-OMBn5cWR.js → ProfileRelationshipType-BjoaCt-u.js} +2 -2
  30. package/dist/chunks/{ProfileRelationshipType-OMBn5cWR.js.map → ProfileRelationshipType-BjoaCt-u.js.map} +1 -1
  31. package/dist/chunks/{ProfileRelationshipTypeCollection-CQu08kxF.js → ProfileRelationshipTypeCollection-Bh4xJ4-I.js} +3 -3
  32. package/dist/chunks/{ProfileRelationshipTypeCollection-CQu08kxF.js.map → ProfileRelationshipTypeCollection-Bh4xJ4-I.js.map} +1 -1
  33. package/dist/chunks/oidcProvisioningPrimitives-ZuVcDPt-.js +138 -0
  34. package/dist/chunks/oidcProvisioningPrimitives-ZuVcDPt-.js.map +1 -0
  35. package/dist/chunks/resolveIdentity-_h_2sGqJ.js +260 -0
  36. package/dist/chunks/resolveIdentity-_h_2sGqJ.js.map +1 -0
  37. package/dist/index.d.ts +127 -15
  38. package/dist/index.js +30 -273
  39. package/dist/index.js.map +1 -1
  40. package/dist/internal/oidc-provisioning.d.ts +17 -0
  41. package/dist/internal/oidc-provisioning.js +13 -0
  42. package/dist/internal/oidc-provisioning.js.map +1 -0
  43. package/dist/manifest.json +431 -46
  44. package/dist/oidc-provisioning.d.ts +83 -0
  45. package/dist/smrt-knowledge.json +105 -43
  46. package/dist/types.d.ts +26 -2
  47. package/dist/utils.d.ts +26 -2
  48. package/dist/utils.js +4 -4
  49. package/package.json +10 -6
  50. package/dist/chunks/NostrIdentityCollection-CG6HGf6c.js.map +0 -1
  51. package/dist/chunks/OidcIdentityCollection-DiLneB7J.js +0 -158
  52. package/dist/chunks/OidcIdentityCollection-DiLneB7J.js.map +0 -1
  53. package/dist/chunks/ProfileCollection-BOMOloTL.js +0 -641
  54. package/dist/chunks/ProfileCollection-BOMOloTL.js.map +0 -1
@@ -0,0 +1,138 @@
1
+ import { y as __exportAll } from "./NostrIdentity-DF_a_WZk.js";
2
+ import { a as ProfileType, f as saveOidcRaceArbiter, i as Profile, n as ProfileCollection } from "./ProfileCollection-Bix9yAiy.js";
3
+ import { t as OidcIdentity } from "./OidcIdentity-ChkiT6hg.js";
4
+ import { SmrtCollection, smrt } from "@happyvertical/smrt-core";
5
+ import { isSystemContext } from "@happyvertical/smrt-tenancy";
6
+ //#region src/collections/ProfileTypeCollection.ts
7
+ var ProfileTypeCollection_exports = /* @__PURE__ */ __exportAll({ ProfileTypeCollection: () => ProfileTypeCollection });
8
+ var ProfileTypeCollection = class extends SmrtCollection {
9
+ static _itemClass = ProfileType;
10
+ /**
11
+ * Get profile type by slug
12
+ *
13
+ * @param slug - The slug to search for
14
+ * @returns ProfileType instance or null
15
+ */
16
+ async getBySlug(slug) {
17
+ return await this.get({ slug });
18
+ }
19
+ /**
20
+ * Get or create a profile type by slug
21
+ *
22
+ * @param slug - The slug to search for
23
+ * @param defaults - Default values if creating
24
+ * @returns ProfileType instance
25
+ */
26
+ async getOrCreateBySlug(slug, defaults) {
27
+ const existing = await this.getBySlug(slug);
28
+ if (existing) return existing;
29
+ const profileType = await this.create({
30
+ slug,
31
+ ...defaults
32
+ });
33
+ await profileType.save();
34
+ return profileType;
35
+ }
36
+ /**
37
+ * Atomically create or load a global ProfileType from trusted system code.
38
+ *
39
+ * This intentionally bypasses tenant auto-population and therefore refuses
40
+ * to run outside an explicit `withSystemContext()` boundary.
41
+ */
42
+ async getOrCreateGlobalBySlug(slug, defaults) {
43
+ if (!isSystemContext()) throw new Error("Global ProfileType creation requires an explicit system context.");
44
+ const existing = await this.loadGlobalBySlug(slug);
45
+ if (existing) return existing;
46
+ await this.db.query(`INSERT INTO profile_types
47
+ (id, slug, context, _meta_type, tenant_id, name, description)
48
+ VALUES (?, ?, '', '@happyvertical/smrt-profiles:ProfileType', NULL, ?, ?)
49
+ ON CONFLICT (slug, context, _meta_type) DO NOTHING`, crypto.randomUUID(), slug, defaults.name, defaults.description ?? null);
50
+ const profileType = await this.loadGlobalBySlug(slug);
51
+ if (!profileType) throw new Error(`Global ProfileType '${slug}' could not be created or loaded.`);
52
+ return profileType;
53
+ }
54
+ async loadGlobalBySlug(slug) {
55
+ const id = (await this.db.query(`SELECT id
56
+ FROM profile_types
57
+ WHERE slug = ?
58
+ AND context = ''
59
+ AND _meta_type = '@happyvertical/smrt-profiles:ProfileType'
60
+ AND tenant_id IS NULL
61
+ LIMIT 1`, slug)).rows[0]?.id;
62
+ return typeof id === "string" ? this.get({ id }) : null;
63
+ }
64
+ };
65
+ //#endregion
66
+ //#region src/models/ProfileTypes.ts
67
+ var ProfileTypes_exports = /* @__PURE__ */ __exportAll({
68
+ Bot: () => Bot,
69
+ Organization: () => Organization,
70
+ Person: () => Person
71
+ });
72
+ var __defProp = Object.defineProperty;
73
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
74
+ var __decorateClass = (decorators, target, key, kind) => {
75
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
76
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
77
+ if (kind && result) __defProp(target, key, result);
78
+ return result;
79
+ };
80
+ var Person = class extends Profile {
81
+ constructor(options = {}) {
82
+ super(options);
83
+ }
84
+ };
85
+ Person = __decorateClass([smrt({ tableStrategy: "sti" })], Person);
86
+ var Organization = class extends Profile {
87
+ constructor(options = {}) {
88
+ super(options);
89
+ }
90
+ };
91
+ Organization = __decorateClass([smrt({ tableStrategy: "sti" })], Organization);
92
+ var Bot = class extends Profile {
93
+ constructor(options = {}) {
94
+ super(options);
95
+ }
96
+ };
97
+ Bot = __decorateClass([smrt({ tableStrategy: "sti" })], Bot);
98
+ //#endregion
99
+ //#region src/auth/oidcProvisioningPrimitives.ts
100
+ async function createOidcProvisioningPerson(db, input) {
101
+ const typeId = requireProvisioningId((await (await ProfileTypeCollection.create({ db })).getOrCreateGlobalBySlug("person", {
102
+ name: "Person",
103
+ description: "Individual person profile"
104
+ })).id, "Person ProfileType");
105
+ let profile = new Person({
106
+ db,
107
+ slug: `oidc-${crypto.randomUUID()}`,
108
+ tenantId: null,
109
+ typeId,
110
+ email: input.email ?? "",
111
+ name: input.name || input.preferredUsername || input.subject
112
+ });
113
+ await profile.initialize();
114
+ await saveOidcRaceArbiter(() => profile.save());
115
+ if (input.email) profile = await (await ProfileCollection.create({ db })).reserveCanonicalIdentityEmail(requireProvisioningId(profile.id, "Created Profile"), input.email);
116
+ return profile;
117
+ }
118
+ async function insertOidcProvisioningIdentity(db, input) {
119
+ const identity = new OidcIdentity({
120
+ db,
121
+ email: input.email ?? "",
122
+ issuer: input.issuer,
123
+ profileId: input.profileId,
124
+ provider: input.provider,
125
+ subject: input.subject
126
+ });
127
+ await identity.initialize();
128
+ await saveOidcRaceArbiter(() => identity.save());
129
+ return identity;
130
+ }
131
+ function requireProvisioningId(value, label) {
132
+ if (typeof value !== "string" || !value) throw new Error(`${label} did not produce an id.`);
133
+ return value;
134
+ }
135
+ //#endregion
136
+ export { Person as a, ProfileTypeCollection_exports as c, Organization as i, insertOidcProvisioningIdentity as n, ProfileTypes_exports as o, Bot as r, ProfileTypeCollection as s, createOidcProvisioningPerson as t };
137
+
138
+ //# sourceMappingURL=oidcProvisioningPrimitives-ZuVcDPt-.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oidcProvisioningPrimitives-ZuVcDPt-.js","names":[],"sources":["../../src/collections/ProfileTypeCollection.ts","../../src/models/ProfileTypes.ts","../../src/auth/oidcProvisioningPrimitives.ts"],"sourcesContent":["/**\n * ProfileTypeCollection - Collection manager for ProfileType objects\n *\n * Provides querying for profile type lookup table.\n */\n\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport { isSystemContext } from '@happyvertical/smrt-tenancy';\nimport { ProfileType } from '../models/ProfileType';\n\nexport class ProfileTypeCollection extends SmrtCollection<ProfileType> {\n static readonly _itemClass = ProfileType;\n\n /**\n * Get profile type by slug\n *\n * @param slug - The slug to search for\n * @returns ProfileType instance or null\n */\n async getBySlug(slug: string): Promise<ProfileType | null> {\n return await this.get({ slug });\n }\n\n /**\n * Get or create a profile type by slug\n *\n * @param slug - The slug to search for\n * @param defaults - Default values if creating\n * @returns ProfileType instance\n */\n async getOrCreateBySlug(\n slug: string,\n defaults: { name: string; description?: string },\n ): Promise<ProfileType> {\n const existing = await this.getBySlug(slug);\n if (existing) return existing;\n\n const profileType = await this.create({ slug, ...defaults });\n await profileType.save();\n return profileType;\n }\n\n /**\n * Atomically create or load a global ProfileType from trusted system code.\n *\n * This intentionally bypasses tenant auto-population and therefore refuses\n * to run outside an explicit `withSystemContext()` boundary.\n */\n async getOrCreateGlobalBySlug(\n slug: string,\n defaults: { name: string; description?: string },\n ): Promise<ProfileType> {\n if (!isSystemContext()) {\n throw new Error(\n 'Global ProfileType creation requires an explicit system context.',\n );\n }\n\n const existing = await this.loadGlobalBySlug(slug);\n if (existing) return existing;\n\n // A plain SMRT create is an upsert and may replace the winning row's id\n // when two first-login transactions race. Keep the canonical id stable by\n // using a cross-adapter insert-if-absent and then hydrating the winner.\n await this.db.query(\n `INSERT INTO profile_types\n (id, slug, context, _meta_type, tenant_id, name, description)\n VALUES (?, ?, '', '@happyvertical/smrt-profiles:ProfileType', NULL, ?, ?)\n ON CONFLICT (slug, context, _meta_type) DO NOTHING`,\n crypto.randomUUID(),\n slug,\n defaults.name,\n defaults.description ?? null,\n );\n const profileType = await this.loadGlobalBySlug(slug);\n if (!profileType) {\n throw new Error(\n `Global ProfileType '${slug}' could not be created or loaded.`,\n );\n }\n return profileType;\n }\n\n private async loadGlobalBySlug(slug: string): Promise<ProfileType | null> {\n const result = await this.db.query(\n `SELECT id\n FROM profile_types\n WHERE slug = ?\n AND context = ''\n AND _meta_type = '@happyvertical/smrt-profiles:ProfileType'\n AND tenant_id IS NULL\n LIMIT 1`,\n slug,\n );\n const id = result.rows[0]?.id;\n return typeof id === 'string' ? this.get({ id }) : null;\n }\n}\n","/**\n * Profile subclasses for STI (Single Table Inheritance)\n *\n * These classes inherit from Profile and automatically use the shared\n * profiles table with _meta_type discriminator.\n */\n\nimport { smrt } from '@happyvertical/smrt-core';\nimport { Profile, type ProfileOptions } from './Profile';\n\n/**\n * Person profile type\n *\n * Represents individual people/users.\n */\n@smrt({\n tableStrategy: 'sti',\n})\nexport class Person extends Profile {\n constructor(options: ProfileOptions = {}) {\n super(options);\n // Person-specific initialization can go here\n }\n}\n\n/**\n * Organization profile type\n *\n * Represents companies, groups, institutions, and other organizational entities.\n */\n@smrt({\n tableStrategy: 'sti',\n})\nexport class Organization extends Profile {\n constructor(options: ProfileOptions = {}) {\n super(options);\n // Organization-specific initialization can go here\n }\n}\n\n/**\n * Bot profile type\n *\n * Represents automated agents, bots, and AI entities.\n */\n@smrt({\n tableStrategy: 'sti',\n})\nexport class Bot extends Profile {\n constructor(options: ProfileOptions = {}) {\n super(options);\n // Bot-specific initialization can go here\n }\n}\n","import type { getDatabase } from '@happyvertical/sql';\nimport { ProfileCollection } from '../collections/ProfileCollection';\nimport { ProfileTypeCollection } from '../collections/ProfileTypeCollection';\nimport { OidcIdentity } from '../models/OidcIdentity';\nimport type { Profile } from '../models/Profile';\nimport { Person } from '../models/ProfileTypes';\nimport { saveOidcRaceArbiter } from './oidcProvisioningCoordinator';\n\ntype DatabaseInterface = Awaited<ReturnType<typeof getDatabase>>;\n\nexport interface OidcProvisioningPersonInput {\n email?: string;\n name?: string;\n preferredUsername?: string;\n subject: string;\n}\n\nexport interface OidcProvisioningIdentityInput {\n email?: string;\n issuer: string;\n profileId: string;\n provider: string;\n subject: string;\n}\n\n/** Create and reserve a fresh global Person inside the caller's transaction. */\nexport async function createOidcProvisioningPerson(\n db: DatabaseInterface,\n input: OidcProvisioningPersonInput,\n): Promise<Profile> {\n const typeCollection = await ProfileTypeCollection.create({ db });\n const personType = await typeCollection.getOrCreateGlobalBySlug('person', {\n name: 'Person',\n description: 'Individual person profile',\n });\n const typeId = requireProvisioningId(personType.id, 'Person ProfileType');\n let profile: Profile = new Person({\n db,\n // OIDC display names are not identity keys. A per-profile slug keeps\n // SMRT's natural-key upsert from replacing an unrelated Person.\n slug: `oidc-${crypto.randomUUID()}`,\n tenantId: null,\n typeId,\n email: input.email ?? '',\n name: input.name || input.preferredUsername || input.subject,\n });\n await profile.initialize();\n await saveOidcRaceArbiter(() => profile.save());\n\n if (input.email) {\n const profiles = await ProfileCollection.create({ db });\n profile = await profiles.reserveCanonicalIdentityEmail(\n requireProvisioningId(profile.id, 'Created Profile'),\n input.email,\n );\n }\n return profile;\n}\n\n/** Insert the identity after the caller proves Profile ownership. */\nexport async function insertOidcProvisioningIdentity(\n db: DatabaseInterface,\n input: OidcProvisioningIdentityInput,\n): Promise<OidcIdentity> {\n const identity = new OidcIdentity({\n db,\n email: input.email ?? '',\n issuer: input.issuer,\n profileId: input.profileId,\n provider: input.provider,\n subject: input.subject,\n });\n await identity.initialize();\n await saveOidcRaceArbiter(() => identity.save());\n return identity;\n}\n\nfunction requireProvisioningId(value: unknown, label: string): string {\n if (typeof value !== 'string' || !value) {\n throw new Error(`${label} did not produce an id.`);\n }\n return value;\n}\n"],"mappings":";;;;;;;AAUO,IAAM,wBAAN,cAAoC,eAA4B;CACrE,OAAgB,aAAa;;;;;;;CAQ7B,MAAM,UAAU,MAA2C;EACzD,OAAO,MAAM,KAAK,IAAI,EAAE,KAAK,CAAC;CAChC;;;;;;;;CASA,MAAM,kBACJ,MACA,UACsB;EACtB,MAAM,WAAW,MAAM,KAAK,UAAU,IAAI;EAC1C,IAAI,UAAU,OAAO;EAErB,MAAM,cAAc,MAAM,KAAK,OAAO;GAAE;GAAM,GAAG;EAAS,CAAC;EAC3D,MAAM,YAAY,KAAK;EACvB,OAAO;CACT;;;;;;;CAQA,MAAM,wBACJ,MACA,UACsB;EACtB,IAAI,CAAC,gBAAgB,GACnB,MAAM,IAAI,MACR,kEACF;EAGF,MAAM,WAAW,MAAM,KAAK,iBAAiB,IAAI;EACjD,IAAI,UAAU,OAAO;EAKrB,MAAM,KAAK,GAAG,MACZ;;;4DAIA,OAAO,WAAW,GAClB,MACA,SAAS,MACT,SAAS,eAAe,IAC1B;EACA,MAAM,cAAc,MAAM,KAAK,iBAAiB,IAAI;EACpD,IAAI,CAAC,aACH,MAAM,IAAI,MACR,uBAAuB,KAAI,kCAC7B;EAEF,OAAO;CACT;CAEA,MAAc,iBAAiB,MAA2C;EAWxE,MAAM,MAAK,MAVU,KAAK,GAAG,MAC3B;;;;;;iBAOA,IACF,EAAA,CACkB,KAAK,EAAC,EAAG;EAC3B,OAAO,OAAO,OAAO,WAAW,KAAK,IAAI,EAAE,GAAG,CAAC,IAAI;CACrD;AACF;;;;;;;;;;;;;;;;AC/EO,IAAM,SAAN,cAAqB,QAAQ;CAClC,YAAY,UAA0B,CAAC,GAAG;EACxC,MAAM,OAAO;CAEf;AACF;AALa,SAAN,gBAAA,CAHN,KAAK,EACJ,eAAe,MACjB,CAAC,CAAA,GACY,MAAA;AAeN,IAAM,eAA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,IAAI,MAAM,GAAG,MAAK,wBAAyB;CAEnD,OAAO;AACT"}
@@ -0,0 +1,260 @@
1
+ import { _ as verifyAuthEvent, t as NostrIdentity, y as __exportAll } from "./NostrIdentity-DF_a_WZk.js";
2
+ import { d as isOidcProvisioningRaceConflict, l as coordinateOidcProvisioning, p as normalizeIdentityEmail } from "./ProfileCollection-Bix9yAiy.js";
3
+ import { t as ApiKey } from "./ApiKey-Br9NGBnr.js";
4
+ import { t as OidcIdentity } from "./OidcIdentity-ChkiT6hg.js";
5
+ import { n as insertOidcProvisioningIdentity, t as createOidcProvisioningPerson } from "./oidcProvisioningPrimitives-ZuVcDPt-.js";
6
+ import { resolveDatabase } from "@happyvertical/smrt-core";
7
+ import { withSystemContext } from "@happyvertical/smrt-tenancy";
8
+ //#region src/auth/resolveIdentity.ts
9
+ var resolveIdentity_exports = /* @__PURE__ */ __exportAll({
10
+ createProfileFromNostr: () => createProfileFromNostr,
11
+ createProfileFromOidc: () => createProfileFromOidc,
12
+ resolveIdentity: () => resolveIdentity,
13
+ reuseExistingOidcIdentityForProfile: () => reuseExistingOidcIdentityForProfile
14
+ });
15
+ async function resolveIdentity(context) {
16
+ const options = { db: context.db };
17
+ if (context.apiKey) {
18
+ const apiKey = await ApiKey.verify(context.apiKey, options);
19
+ if (apiKey) {
20
+ const profile = await apiKey.getProfile();
21
+ if (profile) return {
22
+ profile,
23
+ source: "api_key",
24
+ apiKey
25
+ };
26
+ }
27
+ }
28
+ if (context.oidcSession?.sub && context.oidcSession?.iss) {
29
+ const oidcIdentity = await OidcIdentity.findBySubject(context.oidcSession.iss, context.oidcSession.sub, options);
30
+ if (oidcIdentity) {
31
+ await oidcIdentity.recordUsage();
32
+ const profile = await oidcIdentity.getProfile();
33
+ if (profile) return {
34
+ profile,
35
+ source: "oidc",
36
+ oidcIdentity
37
+ };
38
+ }
39
+ }
40
+ if (context.nostrAuth?.event && context.nostrAuth?.challenge) {
41
+ const { event, challenge } = context.nostrAuth;
42
+ if (verifyAuthEvent(event, challenge).valid) {
43
+ const nostrIdentity = await NostrIdentity.findByPubkey(event.pubkey, options);
44
+ if (nostrIdentity) {
45
+ await nostrIdentity.recordUsage();
46
+ const profile = await nostrIdentity.getProfile();
47
+ if (profile) return {
48
+ profile,
49
+ source: "nostr",
50
+ nostrIdentity
51
+ };
52
+ }
53
+ }
54
+ }
55
+ if (context.actor) {
56
+ const profile = await findProfileByExternalId("github", context.actor, options);
57
+ if (profile) return {
58
+ profile,
59
+ source: "actor"
60
+ };
61
+ }
62
+ return {
63
+ profile: null,
64
+ source: "none"
65
+ };
66
+ }
67
+ async function findProfileByExternalId(provider, externalId, options) {
68
+ const { OidcIdentityCollection } = await import("./OidcIdentityCollection-Ce4yv8p0.js").then((n) => n.r);
69
+ const identities = await (await OidcIdentityCollection.create(options)).findByProvider(provider);
70
+ for (const identity of identities) if (identity.subject === externalId || identity.email?.includes(externalId)) {
71
+ const profile = await identity.getProfile();
72
+ if (profile) return profile;
73
+ }
74
+ const { ProfileCollection } = await import("./ProfileCollection-Bix9yAiy.js").then((n) => n.r);
75
+ const profiles = await (await ProfileCollection.create(options)).list({
76
+ where: { email: `${externalId}@users.noreply.github.com` },
77
+ limit: 1
78
+ });
79
+ if (profiles.length > 0) return profiles[0];
80
+ return null;
81
+ }
82
+ async function createProfileFromOidc(claims, provider, options) {
83
+ return coordinateProfileOidcProvisioning(claims, provider, options);
84
+ }
85
+ async function reuseExistingOidcIdentityForProfile(profileId, claims, provider, options) {
86
+ const normalizedClaims = normalizeOidcProfileClaims(claims);
87
+ return coordinateOidcProvisioning({
88
+ db: await resolveOidcProfileDatabase(options.db),
89
+ lockKeys: [`identity:${OidcIdentity.buildIdentityKey(normalizedClaims.iss, normalizedClaims.sub)}`],
90
+ isRaceConflict: isOidcProvisioningRaceConflict,
91
+ createTransactionError: (message, cause) => new Error(message, cause === void 0 ? void 0 : { cause }),
92
+ createConcurrencyError: (cause) => new Error("Concurrent exact OIDC identity reuse did not converge.", cause === void 0 ? void 0 : { cause }),
93
+ rebindRootResult: rebindOidcProfileResult,
94
+ provision: (tx) => withSystemContext(async () => {
95
+ const { OidcIdentityCollection } = await import("./OidcIdentityCollection-Ce4yv8p0.js").then((n) => n.r);
96
+ const identity = await (await OidcIdentityCollection.create({ db: tx })).findBySubject(normalizedClaims.iss, normalizedClaims.sub);
97
+ if (!identity) throw new Error("OidcIdentity.findOrCreate() no longer creates authentication links; use UserCollection.getOrCreateFromOidc() or createProfileFromOidc().");
98
+ if (identity.profileId !== profileId) throw new Error(`OIDC identity ${normalizedClaims.iss} subject ${normalizedClaims.sub} belongs to a different Profile.`);
99
+ const profile = await identity.getProfile();
100
+ if (!profile) throw new Error("The exact OIDC identity has no linked Profile.");
101
+ identity.provider = provider;
102
+ if (normalizedClaims.email) identity.email = normalizedClaims.email;
103
+ identity.lastUsedAt = /* @__PURE__ */ new Date();
104
+ await identity.save();
105
+ return {
106
+ profile,
107
+ oidcIdentity: identity,
108
+ created: false
109
+ };
110
+ })
111
+ });
112
+ }
113
+ async function coordinateProfileOidcProvisioning(claims, provider, options) {
114
+ const normalizedClaims = normalizeOidcProfileClaims(claims);
115
+ return coordinateOidcProvisioning({
116
+ db: await resolveOidcProfileDatabase(options.db),
117
+ lockKeys: [`identity:${OidcIdentity.buildIdentityKey(normalizedClaims.iss, normalizedClaims.sub)}`, ...normalizedClaims.email ? [`email:${normalizedClaims.email}`] : []],
118
+ isRaceConflict: isOidcProvisioningRaceConflict,
119
+ createTransactionError: (message, cause) => new Error(message, cause === void 0 ? void 0 : { cause }),
120
+ createConcurrencyError: (cause) => new Error("Concurrent OIDC Profile provisioning did not converge.", cause === void 0 ? void 0 : { cause }),
121
+ rebindRootResult: rebindOidcProfileResult,
122
+ provision: (tx) => withSystemContext(() => provisionOidcProfile(normalizedClaims, provider, {
123
+ ...options,
124
+ db: tx
125
+ }))
126
+ });
127
+ }
128
+ async function provisionOidcProfile(claims, provider, options) {
129
+ const { OidcIdentityCollection } = await import("./OidcIdentityCollection-Ce4yv8p0.js").then((n) => n.r);
130
+ const existingIdentity = await (await OidcIdentityCollection.create(options)).findBySubject(claims.iss, claims.sub);
131
+ if (existingIdentity) {
132
+ const profile2 = await existingIdentity.getProfile();
133
+ if (!profile2) throw new Error("The exact OIDC identity has no linked Profile.");
134
+ if (claims.email) existingIdentity.email = claims.email;
135
+ existingIdentity.lastUsedAt = /* @__PURE__ */ new Date();
136
+ await existingIdentity.save();
137
+ return {
138
+ profile: profile2,
139
+ oidcIdentity: existingIdentity,
140
+ created: false
141
+ };
142
+ }
143
+ const { ProfileCollection } = await import("./ProfileCollection-Bix9yAiy.js").then((n) => n.r);
144
+ const profileCollection = await ProfileCollection.create(options);
145
+ if (claims.email) {
146
+ if (await profileCollection.findUniqueGlobalPersonByEmail(claims.email)) {
147
+ if (claims.email_verified !== true) throw new Error(`OIDC email ${claims.email} is not verified and already belongs to a Profile.`);
148
+ throw new Error(`OIDC email ${claims.email} already belongs to a Profile; createProfileFromOidc() cannot prove that Profile is unowned. Use UserCollection.getOrCreateFromOidc() for owner-aware linking.`);
149
+ }
150
+ }
151
+ const profile = await createOidcProvisioningPerson(options.db, {
152
+ email: claims.email ?? "",
153
+ name: claims.name,
154
+ preferredUsername: claims.preferred_username,
155
+ subject: claims.sub
156
+ });
157
+ return {
158
+ profile,
159
+ oidcIdentity: await insertOidcProvisioningIdentity(options.db, {
160
+ email: claims.email,
161
+ issuer: claims.iss,
162
+ profileId: requireOidcProfileId(profile.id),
163
+ provider,
164
+ subject: claims.sub
165
+ }),
166
+ created: true
167
+ };
168
+ }
169
+ async function rebindOidcProfileResult(result, rootDb) {
170
+ const { OidcIdentityCollection } = await import("./OidcIdentityCollection-Ce4yv8p0.js").then((n) => n.r);
171
+ const { ProfileCollection } = await import("./ProfileCollection-Bix9yAiy.js").then((n) => n.r);
172
+ const profileId = requireOidcProfileId(result.profile.id);
173
+ const identityId = requireOidcProfileId(result.oidcIdentity.id);
174
+ const [profile, oidcIdentity] = await withSystemContext(async () => {
175
+ const profiles = await ProfileCollection.create({ db: rootDb });
176
+ const identities = await OidcIdentityCollection.create({ db: rootDb });
177
+ return Promise.all([profiles.get({ id: profileId }), identities.get({ id: identityId })]);
178
+ });
179
+ if (!profile || !oidcIdentity) throw new Error("Committed OIDC Profile provisioning result was not found.");
180
+ return {
181
+ ...result,
182
+ profile,
183
+ oidcIdentity
184
+ };
185
+ }
186
+ function normalizeOidcProfileClaims(claims) {
187
+ const sub = claims?.sub;
188
+ const iss = claims?.iss;
189
+ if (typeof sub !== "string" || sub.trim().length === 0 || typeof iss !== "string" || iss.trim().length === 0) throw new Error("Invalid OIDC claims: both \"sub\" and \"iss\" must be non-empty strings.");
190
+ const suppliedEmail = claims.email;
191
+ return {
192
+ ...claims,
193
+ sub,
194
+ iss,
195
+ email: typeof suppliedEmail === "string" && suppliedEmail.trim() ? normalizeIdentityEmail(suppliedEmail) : void 0
196
+ };
197
+ }
198
+ function requireOidcProfileId(value) {
199
+ if (typeof value !== "string" || !value) throw new Error("OIDC Profile provisioning did not produce an id.");
200
+ return value;
201
+ }
202
+ async function resolveOidcProfileDatabase(db) {
203
+ if (!db) throw new Error("OIDC Profile provisioning requires an initialized database.");
204
+ return resolveDatabase(db);
205
+ }
206
+ async function createProfileFromNostr(email, nostrData, options) {
207
+ const normalizedEmail = normalizeIdentityEmail(email);
208
+ const existingIdentity = await NostrIdentity.findByEmail(normalizedEmail, options);
209
+ if (existingIdentity) {
210
+ const profile2 = await existingIdentity.getProfile();
211
+ if (profile2) return {
212
+ profile: profile2,
213
+ nostrIdentity: existingIdentity,
214
+ created: false
215
+ };
216
+ }
217
+ const { Person } = await import("./oidcProvisioningPrimitives-ZuVcDPt-.js").then((n) => n.o);
218
+ const { ProfileTypeCollection } = await import("./oidcProvisioningPrimitives-ZuVcDPt-.js").then((n) => n.c);
219
+ let personType = await (await ProfileTypeCollection.create(options)).getBySlug("person");
220
+ if (!personType) {
221
+ const { ProfileType } = await import("./ProfileCollection-Bix9yAiy.js").then((n) => n.o);
222
+ personType = new ProfileType({
223
+ ...options,
224
+ slug: "person",
225
+ name: "Person",
226
+ description: "Individual person profile"
227
+ });
228
+ await personType.initialize();
229
+ await personType.save();
230
+ }
231
+ const profile = new Person({
232
+ ...options,
233
+ typeId: personType.id,
234
+ email: normalizedEmail,
235
+ name: normalizedEmail.split("@")[0]
236
+ });
237
+ await profile.initialize();
238
+ await profile.save();
239
+ const nostrIdentity = new NostrIdentity({
240
+ ...options,
241
+ profileId: profile.id,
242
+ pubkey: nostrData.pubkey,
243
+ encryptedPrivkey: nostrData.encryptedPrivkey,
244
+ encryptionIv: nostrData.encryptionIv,
245
+ encryptionTag: nostrData.encryptionTag,
246
+ email: normalizedEmail,
247
+ nip05Username: nostrData.nip05Username?.toLowerCase() || normalizedEmail.split("@")[0]
248
+ });
249
+ await nostrIdentity.initialize();
250
+ await nostrIdentity.save();
251
+ return {
252
+ profile,
253
+ nostrIdentity,
254
+ created: true
255
+ };
256
+ }
257
+ //#endregion
258
+ export { resolveIdentity_exports as i, createProfileFromOidc as n, resolveIdentity as r, createProfileFromNostr as t };
259
+
260
+ //# sourceMappingURL=resolveIdentity-_h_2sGqJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolveIdentity-_h_2sGqJ.js","names":["profile"],"sources":["../../src/auth/resolveIdentity.ts"],"sourcesContent":["/**\n * resolveIdentity - Resolves authentication context to a Profile\n *\n * Used by apps (blindmanpress.com) to resolve incoming auth to a Profile.\n * Modules (aedile, praeco) should receive the resolved profile from the app.\n *\n * Resolution order:\n * 1. API key header → ApiKey → Profile\n * 2. OIDC session → OidcIdentity → Profile\n * 3. Nostr auth → NostrIdentity → Profile\n * 4. Actor header (CI pass-through) → Profile lookup\n */\n\nimport {\n resolveDatabase,\n type SmrtObjectOptions,\n} from '@happyvertical/smrt-core';\nimport { withSystemContext } from '@happyvertical/smrt-tenancy';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { ApiKey } from '../models/ApiKey';\nimport { NostrIdentity } from '../models/NostrIdentity';\nimport { OidcIdentity } from '../models/OidcIdentity';\nimport type { Profile } from '../models/Profile';\nimport { normalizeIdentityEmail } from './normalizeIdentityEmail';\nimport { type NostrEvent, verifyAuthEvent } from './nostrCrypto';\nimport {\n coordinateOidcProvisioning,\n isOidcProvisioningRaceConflict,\n} from './oidcProvisioningCoordinator';\nimport {\n createOidcProvisioningPerson,\n insertOidcProvisioningIdentity,\n} from './oidcProvisioningPrimitives';\n\n/**\n * Context provided to resolveIdentity\n */\nexport interface AuthContext {\n /**\n * API key from X-API-Key header or similar\n */\n apiKey?: string | null;\n\n /**\n * OIDC session data (from @auth/sveltekit or similar)\n */\n oidcSession?: {\n sub?: string;\n iss?: string;\n email?: string;\n name?: string;\n } | null;\n\n /**\n * Actor identifier for CI pass-through identity\n * Usually the GitHub actor (username) who triggered the workflow\n */\n actor?: string | null;\n\n /**\n * Nostr authentication data (NIP-42 style)\n */\n nostrAuth?: {\n /** Signed Nostr event for authentication */\n event: NostrEvent;\n /** Expected challenge (to prevent replay attacks) */\n challenge: string;\n } | null;\n\n /**\n * Database/persistence options\n */\n db?: SmrtObjectOptions['db'];\n}\n\n/**\n * Result of identity resolution\n */\nexport interface ResolveIdentityResult {\n /**\n * The resolved profile, or null if not authenticated\n */\n profile: Profile | null;\n\n /**\n * How the identity was resolved\n */\n source: 'api_key' | 'oidc' | 'nostr' | 'actor' | 'none';\n\n /**\n * The API key record if authenticated via API key\n */\n apiKey?: ApiKey;\n\n /**\n * The OIDC identity record if authenticated via OIDC\n */\n oidcIdentity?: OidcIdentity;\n\n /**\n * The Nostr identity record if authenticated via Nostr\n */\n nostrIdentity?: NostrIdentity;\n}\n\n/**\n * Resolve authentication context to a Profile\n *\n * @param context - The authentication context from the request\n * @returns The resolved profile and metadata\n *\n * @example\n * ```typescript\n * // In SvelteKit hooks.server.ts\n * import { resolveIdentity } from '@happyvertical/smrt-profiles';\n *\n * const identityMiddleware: Handle = async ({ event, resolve }) => {\n * const session = await event.locals.auth();\n *\n * const { profile, source } = await resolveIdentity({\n * oidcSession: session,\n * apiKey: event.request.headers.get('X-API-Key'),\n * actor: event.request.headers.get('X-Actor'),\n * db: { type: 'postgres', url: DATABASE_URL },\n * });\n *\n * event.locals.profile = profile;\n * event.locals.authSource = source;\n *\n * return resolve(event);\n * };\n * ```\n */\nexport async function resolveIdentity(\n context: AuthContext,\n): Promise<ResolveIdentityResult> {\n const options: SmrtObjectOptions = { db: context.db };\n\n // 1. Check API key header first (highest priority for programmatic access)\n if (context.apiKey) {\n const apiKey = await ApiKey.verify(context.apiKey, options);\n if (apiKey) {\n const profile = await apiKey.getProfile();\n if (profile) {\n return {\n profile,\n source: 'api_key',\n apiKey,\n };\n }\n }\n }\n\n // 2. Check OIDC session (web users)\n if (context.oidcSession?.sub && context.oidcSession?.iss) {\n const oidcIdentity = await OidcIdentity.findBySubject(\n context.oidcSession.iss,\n context.oidcSession.sub,\n options,\n );\n\n if (oidcIdentity) {\n // Record usage\n await oidcIdentity.recordUsage();\n\n const profile = await oidcIdentity.getProfile();\n if (profile) {\n return {\n profile,\n source: 'oidc',\n oidcIdentity,\n };\n }\n }\n }\n\n // 3. Check Nostr auth (NIP-42 style signed event)\n if (context.nostrAuth?.event && context.nostrAuth?.challenge) {\n const { event, challenge } = context.nostrAuth;\n\n // Verify the auth event\n const verifyResult = verifyAuthEvent(event, challenge);\n if (verifyResult.valid) {\n // Look up identity by public key\n const nostrIdentity = await NostrIdentity.findByPubkey(\n event.pubkey,\n options,\n );\n\n if (nostrIdentity) {\n // Record usage\n await nostrIdentity.recordUsage();\n\n const profile = await nostrIdentity.getProfile();\n if (profile) {\n return {\n profile,\n source: 'nostr',\n nostrIdentity,\n };\n }\n }\n }\n }\n\n // 4. Check actor for CI pass-through (look up by metadata)\n if (context.actor) {\n const profile = await findProfileByExternalId(\n 'github',\n context.actor,\n options,\n );\n if (profile) {\n return {\n profile,\n source: 'actor',\n };\n }\n }\n\n // No authentication found\n return {\n profile: null,\n source: 'none',\n };\n}\n\n/**\n * Find a profile by external ID (e.g., GitHub username)\n *\n * This looks up profiles by their linked external identities or metadata.\n *\n * @param provider - The external provider (e.g., 'github')\n * @param externalId - The external identifier (e.g., GitHub username)\n * @param options - Database options\n * @returns The profile or null\n */\nasync function findProfileByExternalId(\n provider: string,\n externalId: string,\n options: SmrtObjectOptions,\n): Promise<Profile | null> {\n // First check OIDC identities (if they use the provider)\n const { OidcIdentityCollection } = await import(\n '../collections/OidcIdentityCollection'\n );\n\n const oidcCollection = await OidcIdentityCollection.create(options);\n const identities = await oidcCollection.findByProvider(provider);\n\n for (const identity of identities) {\n // Check if the subject matches the external ID\n if (\n identity.subject === externalId ||\n identity.email?.includes(externalId)\n ) {\n const profile = await identity.getProfile();\n if (profile) return profile;\n }\n }\n\n // Could also check profile metadata for external IDs\n // This would require a standardized metadata field like 'github_username'\n const { ProfileCollection } = await import(\n '../collections/ProfileCollection'\n );\n const profileCollection = await ProfileCollection.create(options);\n\n // Try to find by email that looks like a GitHub noreply\n const profiles = await profileCollection.list({\n where: {\n email: `${externalId}@users.noreply.github.com`,\n },\n limit: 1,\n });\n\n if (profiles.length > 0) {\n return profiles[0];\n }\n\n return null;\n}\n\n/**\n * Create a profile from OIDC claims if it doesn't exist\n *\n * Resolution order:\n * 1. If OIDC identity (iss + sub) already exists → return linked profile\n * 2. If the email matches an existing Profile, fail closed because this\n * package cannot prove whether a User owns it\n * 3. Otherwise, create new profile + identity\n *\n * Security considerations:\n * - Existing issuer/subject links always keep their already-linked Profile,\n * including legacy tenant-scoped or non-Person Profiles, and refresh the\n * cached identity email. This exact-link compatibility does not perform\n * email-based canonical reuse.\n * - New identities never attach to an existing email match through this\n * Profile-only helper because Profile ownership belongs to the users package.\n * Use `UserCollection.getOrCreateFromOidc()` for owner-aware verified-email\n * reuse and its supported pre-provision resolver hook.\n * - This function trusts the OIDC provider to assert correct email_verified status.\n * Only use with trusted providers.\n *\n * @param claims - OIDC token claims\n * @param provider - Provider name (e.g., 'keycloak', 'google', 'github')\n * @param options - Database options\n * @returns The created or existing profile with linked OIDC identity\n */\nexport async function createProfileFromOidc(\n claims: {\n sub: string;\n iss: string;\n email?: string;\n email_verified?: boolean;\n name?: string;\n preferred_username?: string;\n },\n provider: string,\n options: SmrtObjectOptions,\n): Promise<{ profile: Profile; oidcIdentity: OidcIdentity; created: boolean }> {\n return coordinateProfileOidcProvisioning(claims, provider, options);\n}\n\n/**\n * @internal Transactionally reuse one exact legacy issuer/subject link.\n *\n * This path cannot create or rebind authority. It intentionally preserves\n * existing tenant-scoped and non-Person Profile links; canonical global Person\n * validation remains mandatory for every path that creates a User/session.\n */\nexport async function reuseExistingOidcIdentityForProfile(\n profileId: string,\n claims: {\n sub: string;\n iss: string;\n email?: string;\n email_verified?: boolean;\n name?: string;\n preferred_username?: string;\n },\n provider: string,\n options: SmrtObjectOptions,\n): Promise<{ profile: Profile; oidcIdentity: OidcIdentity; created: false }> {\n const normalizedClaims = normalizeOidcProfileClaims(claims);\n const db = await resolveOidcProfileDatabase(options.db);\n return coordinateOidcProvisioning({\n db,\n lockKeys: [\n `identity:${OidcIdentity.buildIdentityKey(\n normalizedClaims.iss,\n normalizedClaims.sub,\n )}`,\n ],\n isRaceConflict: isOidcProvisioningRaceConflict,\n createTransactionError: (message, cause) =>\n new Error(message, cause === undefined ? undefined : { cause }),\n createConcurrencyError: (cause) =>\n new Error(\n 'Concurrent exact OIDC identity reuse did not converge.',\n cause === undefined ? undefined : { cause },\n ),\n rebindRootResult: rebindOidcProfileResult,\n provision: (tx) =>\n withSystemContext(async () => {\n const { OidcIdentityCollection } = await import(\n '../collections/OidcIdentityCollection'\n );\n const identity = await (\n await OidcIdentityCollection.create({ db: tx })\n ).findBySubject(normalizedClaims.iss, normalizedClaims.sub);\n if (!identity) {\n throw new Error(\n 'OidcIdentity.findOrCreate() no longer creates authentication links; use UserCollection.getOrCreateFromOidc() or createProfileFromOidc().',\n );\n }\n if (identity.profileId !== profileId) {\n throw new Error(\n `OIDC identity ${normalizedClaims.iss} subject ${normalizedClaims.sub} belongs to a different Profile.`,\n );\n }\n const profile = await identity.getProfile();\n if (!profile) {\n throw new Error('The exact OIDC identity has no linked Profile.');\n }\n identity.provider = provider;\n if (normalizedClaims.email) identity.email = normalizedClaims.email;\n identity.lastUsedAt = new Date();\n await identity.save();\n return { profile, oidcIdentity: identity, created: false as const };\n }),\n });\n}\n\nasync function coordinateProfileOidcProvisioning(\n claims: {\n sub: string;\n iss: string;\n email?: string;\n email_verified?: boolean;\n name?: string;\n preferred_username?: string;\n },\n provider: string,\n options: SmrtObjectOptions,\n): Promise<{ profile: Profile; oidcIdentity: OidcIdentity; created: boolean }> {\n const normalizedClaims = normalizeOidcProfileClaims(claims);\n const db = await resolveOidcProfileDatabase(options.db);\n return coordinateOidcProvisioning({\n db,\n lockKeys: [\n `identity:${OidcIdentity.buildIdentityKey(\n normalizedClaims.iss,\n normalizedClaims.sub,\n )}`,\n ...(normalizedClaims.email ? [`email:${normalizedClaims.email}`] : []),\n ],\n isRaceConflict: isOidcProvisioningRaceConflict,\n createTransactionError: (message, cause) =>\n new Error(message, cause === undefined ? undefined : { cause }),\n createConcurrencyError: (cause) =>\n new Error(\n 'Concurrent OIDC Profile provisioning did not converge.',\n cause === undefined ? undefined : { cause },\n ),\n rebindRootResult: rebindOidcProfileResult,\n provision: (tx) =>\n withSystemContext(() =>\n provisionOidcProfile(normalizedClaims, provider, {\n ...options,\n db: tx,\n }),\n ),\n });\n}\n\nasync function provisionOidcProfile(\n claims: {\n sub: string;\n iss: string;\n email?: string;\n email_verified?: boolean;\n name?: string;\n preferred_username?: string;\n },\n provider: string,\n options: SmrtObjectOptions & { db: DatabaseInterface },\n): Promise<{ profile: Profile; oidcIdentity: OidcIdentity; created: boolean }> {\n const { OidcIdentityCollection } = await import(\n '../collections/OidcIdentityCollection'\n );\n const identityCollection = await OidcIdentityCollection.create(options);\n const existingIdentity = await identityCollection.findBySubject(\n claims.iss,\n claims.sub,\n );\n if (existingIdentity) {\n const profile = await existingIdentity.getProfile();\n if (!profile) {\n throw new Error('The exact OIDC identity has no linked Profile.');\n }\n if (claims.email) existingIdentity.email = claims.email;\n existingIdentity.lastUsedAt = new Date();\n await existingIdentity.save();\n return { profile, oidcIdentity: existingIdentity, created: false };\n }\n\n const { ProfileCollection } = await import(\n '../collections/ProfileCollection'\n );\n const profileCollection = await ProfileCollection.create(options);\n if (claims.email) {\n const collision = await profileCollection.findUniqueGlobalPersonByEmail(\n claims.email,\n );\n if (collision) {\n if (claims.email_verified !== true) {\n throw new Error(\n `OIDC email ${claims.email} is not verified and already belongs to a Profile.`,\n );\n }\n throw new Error(\n `OIDC email ${claims.email} already belongs to a Profile; createProfileFromOidc() cannot prove that Profile is unowned. Use UserCollection.getOrCreateFromOidc() for owner-aware linking.`,\n );\n }\n }\n\n const profile = await createOidcProvisioningPerson(options.db, {\n email: claims.email ?? '',\n name: claims.name,\n preferredUsername: claims.preferred_username,\n subject: claims.sub,\n });\n const oidcIdentity = await insertOidcProvisioningIdentity(options.db, {\n email: claims.email,\n issuer: claims.iss,\n profileId: requireOidcProfileId(profile.id),\n provider,\n subject: claims.sub,\n });\n return { profile, oidcIdentity, created: true };\n}\n\nasync function rebindOidcProfileResult<\n T extends {\n profile: Profile;\n oidcIdentity: OidcIdentity;\n created: boolean;\n },\n>(result: T, rootDb: DatabaseInterface): Promise<T> {\n const { OidcIdentityCollection } = await import(\n '../collections/OidcIdentityCollection'\n );\n const { ProfileCollection } = await import(\n '../collections/ProfileCollection'\n );\n const profileId = requireOidcProfileId(result.profile.id);\n const identityId = requireOidcProfileId(result.oidcIdentity.id);\n const [profile, oidcIdentity] = await withSystemContext(async () => {\n const profiles = await ProfileCollection.create({ db: rootDb });\n const identities = await OidcIdentityCollection.create({ db: rootDb });\n return Promise.all([\n profiles.get({ id: profileId }),\n identities.get({ id: identityId }),\n ]);\n });\n if (!profile || !oidcIdentity) {\n throw new Error(\n 'Committed OIDC Profile provisioning result was not found.',\n );\n }\n return { ...result, profile, oidcIdentity };\n}\n\nfunction normalizeOidcProfileClaims(claims: {\n sub: string;\n iss: string;\n email?: string;\n email_verified?: boolean;\n name?: string;\n preferred_username?: string;\n}) {\n const sub = claims?.sub;\n const iss = claims?.iss;\n if (\n typeof sub !== 'string' ||\n sub.trim().length === 0 ||\n typeof iss !== 'string' ||\n iss.trim().length === 0\n ) {\n throw new Error(\n 'Invalid OIDC claims: both \"sub\" and \"iss\" must be non-empty strings.',\n );\n }\n const suppliedEmail = claims.email;\n return {\n ...claims,\n sub,\n iss,\n email:\n typeof suppliedEmail === 'string' && suppliedEmail.trim()\n ? normalizeIdentityEmail(suppliedEmail)\n : undefined,\n };\n}\n\nfunction requireOidcProfileId(value: unknown): string {\n if (typeof value !== 'string' || !value) {\n throw new Error('OIDC Profile provisioning did not produce an id.');\n }\n return value;\n}\n\nasync function resolveOidcProfileDatabase(\n db: SmrtObjectOptions['db'],\n): Promise<DatabaseInterface> {\n if (!db) {\n throw new Error(\n 'OIDC Profile provisioning requires an initialized database.',\n );\n }\n return resolveDatabase(db as Parameters<typeof resolveDatabase>[0]);\n}\n\n/**\n * Create a profile from Nostr identity (used by magic link service)\n *\n * This is typically called internally by the magic link service,\n * but can be used directly if needed.\n *\n * @param email - Email address for the profile\n * @param nostrData - Encrypted Nostr keypair data\n * @param options - Database options\n * @returns The created profile with linked Nostr identity\n */\nexport async function createProfileFromNostr(\n email: string,\n nostrData: {\n pubkey: string;\n encryptedPrivkey: string;\n encryptionIv: string;\n encryptionTag: string;\n nip05Username?: string;\n },\n options: SmrtObjectOptions,\n): Promise<{\n profile: Profile;\n nostrIdentity: NostrIdentity;\n created: boolean;\n}> {\n const normalizedEmail = normalizeIdentityEmail(email);\n\n // Check if Nostr identity already exists\n const existingIdentity = await NostrIdentity.findByEmail(\n normalizedEmail,\n options,\n );\n\n if (existingIdentity) {\n const profile = await existingIdentity.getProfile();\n if (profile) {\n return {\n profile,\n nostrIdentity: existingIdentity,\n created: false,\n };\n }\n }\n\n // Create new profile\n const { Person } = await import('../models/ProfileTypes');\n const { ProfileTypeCollection } = await import(\n '../collections/ProfileTypeCollection'\n );\n\n // Get or create the 'person' type\n const typeCollection = await ProfileTypeCollection.create(options);\n let personType = await typeCollection.getBySlug('person');\n\n if (!personType) {\n const { ProfileType } = await import('../models/ProfileType');\n personType = new ProfileType({\n ...options,\n slug: 'person',\n name: 'Person',\n description: 'Individual person profile',\n });\n await personType.initialize();\n await personType.save();\n }\n\n const profile = new Person({\n ...options,\n typeId: personType.id as string,\n email: normalizedEmail,\n name: normalizedEmail.split('@')[0], // Default name from email\n });\n await profile.initialize();\n await profile.save();\n\n // Create Nostr identity\n const nostrIdentity = new NostrIdentity({\n ...options,\n profileId: profile.id as string,\n pubkey: nostrData.pubkey,\n encryptedPrivkey: nostrData.encryptedPrivkey,\n encryptionIv: nostrData.encryptionIv,\n encryptionTag: nostrData.encryptionTag,\n email: normalizedEmail,\n nip05Username:\n nostrData.nip05Username?.toLowerCase() || normalizedEmail.split('@')[0],\n });\n await nostrIdentity.initialize();\n await nostrIdentity.save();\n\n return {\n profile,\n nostrIdentity,\n created: true,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAqIA,eAAsB,gBACpB,SACgC;CAChC,MAAM,UAA6B,EAAE,IAAI,QAAQ,GAAG;CAGpD,IAAI,QAAQ,QAAQ;EAClB,MAAM,SAAS,MAAM,OAAO,OAAO,QAAQ,QAAQ,OAAO;EAC1D,IAAI,QAAQ;GACV,MAAM,UAAU,MAAM,OAAO,WAAW;GACxC,IAAI,SACF,OAAO;IACL;IACA,QAAQ;IACR;GACF;EAEJ;CACF;CAGA,IAAI,QAAQ,aAAa,OAAO,QAAQ,aAAa,KAAK;EACxD,MAAM,eAAe,MAAM,aAAa,cACtC,QAAQ,YAAY,KACpB,QAAQ,YAAY,KACpB,OACF;EAEA,IAAI,cAAc;GAEhB,MAAM,aAAa,YAAY;GAE/B,MAAM,UAAU,MAAM,aAAa,WAAW;GAC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