@arch-cadre/core 0.0.12 → 0.0.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/auth/augment.cjs +6 -6
- package/dist/core/auth/augment.d.cts.map +1 -1
- package/dist/core/auth/augment.d.mts.map +1 -1
- package/dist/core/auth/augment.mjs +6 -6
- package/dist/core/auth/augment.mjs.map +1 -1
- package/dist/core/auth/email-verification.cjs +1 -1
- package/dist/core/auth/email-verification.mjs +1 -1
- package/dist/core/auth/logic.cjs +9 -9
- package/dist/core/auth/logic.d.cts +2 -2
- package/dist/core/auth/logic.d.mts +2 -2
- package/dist/core/auth/logic.mjs +9 -9
- package/dist/core/auth/logic.mjs.map +1 -1
- package/dist/core/auth/password-reset.cjs +2 -2
- package/dist/core/auth/password-reset.mjs +2 -2
- package/dist/core/auth/session.cjs +0 -7
- package/dist/core/auth/session.d.cts.map +1 -1
- package/dist/core/auth/session.d.mts.map +1 -1
- package/dist/core/auth/session.mjs +0 -7
- package/dist/core/auth/session.mjs.map +1 -1
- package/dist/core/bootstrap.cjs +11 -4
- package/dist/core/bootstrap.d.cts.map +1 -1
- package/dist/core/bootstrap.d.mts.map +1 -1
- package/dist/core/bootstrap.mjs +11 -4
- package/dist/core/bootstrap.mjs.map +1 -1
- package/dist/core/config.server.mjs.map +1 -1
- package/dist/core/event-bus.cjs +2 -2
- package/dist/core/event-bus.mjs +2 -2
- package/dist/core/event-bus.mjs.map +1 -1
- package/dist/core/filesystem/index.cjs +11 -0
- package/dist/core/filesystem/index.mjs +13 -0
- package/dist/core/filesystem/index.mjs.map +1 -0
- package/dist/core/filesystem/providers/local.cjs +43 -0
- package/dist/core/filesystem/providers/local.mjs +41 -0
- package/dist/core/filesystem/providers/local.mjs.map +1 -0
- package/dist/core/filesystem/service.cjs +2 -2
- package/dist/core/filesystem/service.d.cts.map +1 -1
- package/dist/core/filesystem/service.d.mts.map +1 -1
- package/dist/core/filesystem/service.mjs +2 -2
- package/dist/core/filesystem/service.mjs.map +1 -1
- package/dist/core/notifications/actions.d.cts +1 -1
- package/dist/core/notifications/actions.d.mts +1 -1
- package/dist/core/notifications/actions.mjs.map +1 -1
- package/dist/core/notifications/service.cjs +2 -2
- package/dist/core/notifications/service.mjs +2 -2
- package/dist/core/notifications/service.mjs.map +1 -1
- package/dist/server/auth/email.cjs +1 -1
- package/dist/server/auth/email.mjs +1 -1
- package/dist/server/auth/email.mjs.map +1 -1
- package/dist/server/auth/user.cjs +1 -1
- package/dist/server/auth/user.mjs +1 -1
- package/dist/server.cjs +6 -6
- package/dist/server.mjs +6 -6
- package/package.json +5 -2
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
|
|
2
2
|
//#region src/core/auth/augment.ts
|
|
3
3
|
const globalForAugment = globalThis;
|
|
4
|
-
const identityAugmenters = globalForAugment.
|
|
5
|
-
const sessionAugmenters = globalForAugment.
|
|
6
|
-
const passwordResetSessionAugmenters = globalForAugment.
|
|
7
|
-
globalForAugment.
|
|
8
|
-
globalForAugment.
|
|
9
|
-
globalForAugment.
|
|
4
|
+
const identityAugmenters = globalForAugment.__KRYO_IDENTITY_AUGMENTERS__ ?? /* @__PURE__ */ new Set();
|
|
5
|
+
const sessionAugmenters = globalForAugment.__KRYO_SESSION_AUGMENTERS__ ?? /* @__PURE__ */ new Set();
|
|
6
|
+
const passwordResetSessionAugmenters = globalForAugment.__KRYO_PASSWORD_RESET_SESSION_AUGMENTERS__ ?? /* @__PURE__ */ new Set();
|
|
7
|
+
globalForAugment.__KRYO_IDENTITY_AUGMENTERS__ = identityAugmenters;
|
|
8
|
+
globalForAugment.__KRYO_SESSION_AUGMENTERS__ = sessionAugmenters;
|
|
9
|
+
globalForAugment.__KRYO_PASSWORD_RESET_SESSION_AUGMENTERS__ = passwordResetSessionAugmenters;
|
|
10
10
|
function registerIdentityAugmenter(augmenter) {
|
|
11
11
|
identityAugmenters.add(augmenter);
|
|
12
12
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"augment.d.cts","names":[],"sources":["../../../src/core/auth/augment.ts"],"mappings":";;;;;AAA6E;KAMxE,iBAAA,IAAqB,IAAA,EAAM,IAAA,KAAS,OAAA,CAAQ,OAAA,CAAQ,QAAA;AAAA,KACpD,gBAAA,IAAoB,OAAA,EAAS,OAAA,KAAY,OAAA,CAAQ,OAAA,CAAQ,OAAA;AAAA,KACzD,6BAAA,IACH,OAAA,EAAS,oBAAA,KACN,OAAA,CAAQ,OAAA,CAAQ,oBAAA;AAAA,
|
|
1
|
+
{"version":3,"file":"augment.d.cts","names":[],"sources":["../../../src/core/auth/augment.ts"],"mappings":";;;;;AAA6E;KAMxE,iBAAA,IAAqB,IAAA,EAAM,IAAA,KAAS,OAAA,CAAQ,OAAA,CAAQ,QAAA;AAAA,KACpD,gBAAA,IAAoB,OAAA,EAAS,OAAA,KAAY,OAAA,CAAQ,OAAA,CAAQ,OAAA;AAAA,KACzD,6BAAA,IACH,OAAA,EAAS,oBAAA,KACN,OAAA,CAAQ,OAAA,CAAQ,oBAAA;AAAA,iBAuBL,yBAAA,CAA0B,SAAA,EAAW,iBAAA;AAAA,iBAIrC,wBAAA,CAAyB,SAAA,EAAW,gBAAA;AAAA,iBAIpC,qCAAA,CACd,SAAA,EAAW,6BAAA;;;;iBAQS,WAAA,CACpB,IAAA,EAAM,IAAA,EACN,YAAA,GAAe,MAAA,gBACd,OAAA,CAAQ,QAAA;AAAA,iBASW,cAAA,CAAe,OAAA,EAAS,OAAA,GAAU,OAAA,CAAQ,OAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"augment.d.mts","names":[],"sources":["../../../src/core/auth/augment.ts"],"mappings":";;;;;AAA6E;KAMxE,iBAAA,IAAqB,IAAA,EAAM,IAAA,KAAS,OAAA,CAAQ,OAAA,CAAQ,QAAA;AAAA,KACpD,gBAAA,IAAoB,OAAA,EAAS,OAAA,KAAY,OAAA,CAAQ,OAAA,CAAQ,OAAA;AAAA,KACzD,6BAAA,IACH,OAAA,EAAS,oBAAA,KACN,OAAA,CAAQ,OAAA,CAAQ,oBAAA;AAAA,
|
|
1
|
+
{"version":3,"file":"augment.d.mts","names":[],"sources":["../../../src/core/auth/augment.ts"],"mappings":";;;;;AAA6E;KAMxE,iBAAA,IAAqB,IAAA,EAAM,IAAA,KAAS,OAAA,CAAQ,OAAA,CAAQ,QAAA;AAAA,KACpD,gBAAA,IAAoB,OAAA,EAAS,OAAA,KAAY,OAAA,CAAQ,OAAA,CAAQ,OAAA;AAAA,KACzD,6BAAA,IACH,OAAA,EAAS,oBAAA,KACN,OAAA,CAAQ,OAAA,CAAQ,oBAAA;AAAA,iBAuBL,yBAAA,CAA0B,SAAA,EAAW,iBAAA;AAAA,iBAIrC,wBAAA,CAAyB,SAAA,EAAW,gBAAA;AAAA,iBAIpC,qCAAA,CACd,SAAA,EAAW,6BAAA;;;;iBAQS,WAAA,CACpB,IAAA,EAAM,IAAA,EACN,YAAA,GAAe,MAAA,gBACd,OAAA,CAAQ,QAAA;AAAA,iBASW,cAAA,CAAe,OAAA,EAAS,OAAA,GAAU,OAAA,CAAQ,OAAA"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
//#region src/core/auth/augment.ts
|
|
2
2
|
const globalForAugment = globalThis;
|
|
3
|
-
const identityAugmenters = globalForAugment.
|
|
4
|
-
const sessionAugmenters = globalForAugment.
|
|
5
|
-
const passwordResetSessionAugmenters = globalForAugment.
|
|
6
|
-
globalForAugment.
|
|
7
|
-
globalForAugment.
|
|
8
|
-
globalForAugment.
|
|
3
|
+
const identityAugmenters = globalForAugment.__KRYO_IDENTITY_AUGMENTERS__ ?? /* @__PURE__ */ new Set();
|
|
4
|
+
const sessionAugmenters = globalForAugment.__KRYO_SESSION_AUGMENTERS__ ?? /* @__PURE__ */ new Set();
|
|
5
|
+
const passwordResetSessionAugmenters = globalForAugment.__KRYO_PASSWORD_RESET_SESSION_AUGMENTERS__ ?? /* @__PURE__ */ new Set();
|
|
6
|
+
globalForAugment.__KRYO_IDENTITY_AUGMENTERS__ = identityAugmenters;
|
|
7
|
+
globalForAugment.__KRYO_SESSION_AUGMENTERS__ = sessionAugmenters;
|
|
8
|
+
globalForAugment.__KRYO_PASSWORD_RESET_SESSION_AUGMENTERS__ = passwordResetSessionAugmenters;
|
|
9
9
|
function registerIdentityAugmenter(augmenter) {
|
|
10
10
|
identityAugmenters.add(augmenter);
|
|
11
11
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"augment.mjs","names":[],"sources":["../../../src/core/auth/augment.ts"],"sourcesContent":["import type { FullUser, PasswordResetSession, Session, User } from \"./types\";\n\n/**\n * REGISTRIES FOR MODULAR EXTENSIONS\n */\n\ntype IdentityAugmenter = (user: User) => Promise<Partial<FullUser>>;\ntype SessionAugmenter = (session: Session) => Promise<Partial<Session>>;\ntype PasswordResetSessionAugmenter = (\n session: PasswordResetSession,\n) => Promise<Partial<PasswordResetSession>>;\n\nconst globalForAugment = globalThis as unknown as {\n
|
|
1
|
+
{"version":3,"file":"augment.mjs","names":[],"sources":["../../../src/core/auth/augment.ts"],"sourcesContent":["import type { FullUser, PasswordResetSession, Session, User } from \"./types\";\n\n/**\n * REGISTRIES FOR MODULAR EXTENSIONS\n */\n\ntype IdentityAugmenter = (user: User) => Promise<Partial<FullUser>>;\ntype SessionAugmenter = (session: Session) => Promise<Partial<Session>>;\ntype PasswordResetSessionAugmenter = (\n session: PasswordResetSession,\n) => Promise<Partial<PasswordResetSession>>;\n\nconst globalForAugment = globalThis as unknown as {\n __KRYO_IDENTITY_AUGMENTERS__: Set<IdentityAugmenter> | undefined;\n __KRYO_SESSION_AUGMENTERS__: Set<SessionAugmenter> | undefined;\n __KRYO_PASSWORD_RESET_SESSION_AUGMENTERS__:\n | Set<PasswordResetSessionAugmenter>\n | undefined;\n};\n\nconst identityAugmenters =\n globalForAugment.__KRYO_IDENTITY_AUGMENTERS__ ?? new Set<IdentityAugmenter>();\nconst sessionAugmenters =\n globalForAugment.__KRYO_SESSION_AUGMENTERS__ ?? new Set<SessionAugmenter>();\nconst passwordResetSessionAugmenters =\n globalForAugment.__KRYO_PASSWORD_RESET_SESSION_AUGMENTERS__ ??\n new Set<PasswordResetSessionAugmenter>();\n\nglobalForAugment.__KRYO_IDENTITY_AUGMENTERS__ = identityAugmenters;\nglobalForAugment.__KRYO_SESSION_AUGMENTERS__ = sessionAugmenters;\nglobalForAugment.__KRYO_PASSWORD_RESET_SESSION_AUGMENTERS__ =\n passwordResetSessionAugmenters;\n\nexport function registerIdentityAugmenter(augmenter: IdentityAugmenter) {\n identityAugmenters.add(augmenter);\n}\n\nexport function registerSessionAugmenter(augmenter: SessionAugmenter) {\n sessionAugmenters.add(augmenter);\n}\n\nexport function registerPasswordResetSessionAugmenter(\n augmenter: PasswordResetSessionAugmenter,\n) {\n passwordResetSessionAugmenters.add(augmenter);\n}\n\n/**\n * EXECUTION FUNCTIONS\n */\nexport async function augmentUser(\n user: User,\n coreRbacData?: Record<string, any>,\n): Promise<FullUser> {\n let augmentedData = coreRbacData || {};\n for (const augmenter of identityAugmenters) {\n const data = await augmenter(user);\n augmentedData = { ...augmentedData, ...data };\n }\n return { ...user, ...augmentedData } as FullUser;\n}\n\nexport async function augmentSession(session: Session): Promise<Session> {\n let augmentedData = {};\n for (const augmenter of sessionAugmenters) {\n const data = await augmenter(session);\n augmentedData = { ...augmentedData, ...data };\n }\n return { ...session, ...augmentedData } as Session;\n}\n\nexport async function augmentPasswordResetSession(\n session: PasswordResetSession,\n): Promise<PasswordResetSession> {\n let augmentedData = {};\n for (const augmenter of passwordResetSessionAugmenters) {\n const data = await augmenter(session);\n augmentedData = { ...augmentedData, ...data };\n }\n return { ...session, ...augmentedData } as PasswordResetSession;\n}\n"],"mappings":";AAYA,MAAM,mBAAmB;AAQzB,MAAM,qBACJ,iBAAiB,gDAAgC,IAAI,KAAwB;AAC/E,MAAM,oBACJ,iBAAiB,+CAA+B,IAAI,KAAuB;AAC7E,MAAM,iCACJ,iBAAiB,8DACjB,IAAI,KAAoC;AAE1C,iBAAiB,+BAA+B;AAChD,iBAAiB,8BAA8B;AAC/C,iBAAiB,6CACf;AAEF,SAAgB,0BAA0B,WAA8B;AACtE,oBAAmB,IAAI,UAAU;;AAGnC,SAAgB,yBAAyB,WAA6B;AACpE,mBAAkB,IAAI,UAAU;;AAGlC,SAAgB,sCACd,WACA;AACA,gCAA+B,IAAI,UAAU;;;;;AAM/C,eAAsB,YACpB,MACA,cACmB;CACnB,IAAI,gBAAgB,gBAAgB,EAAE;AACtC,MAAK,MAAM,aAAa,oBAAoB;EAC1C,MAAM,OAAO,MAAM,UAAU,KAAK;AAClC,kBAAgB;GAAE,GAAG;GAAe,GAAG;GAAM;;AAE/C,QAAO;EAAE,GAAG;EAAM,GAAG;EAAe;;AAGtC,eAAsB,eAAe,SAAoC;CACvE,IAAI,gBAAgB,EAAE;AACtB,MAAK,MAAM,aAAa,mBAAmB;EACzC,MAAM,OAAO,MAAM,UAAU,QAAQ;AACrC,kBAAgB;GAAE,GAAG;GAAe,GAAG;GAAM;;AAE/C,QAAO;EAAE,GAAG;EAAS,GAAG;EAAe;;AAGzC,eAAsB,4BACpB,SAC+B;CAC/B,IAAI,gBAAgB,EAAE;AACtB,MAAK,MAAM,aAAa,gCAAgC;EACtD,MAAM,OAAO,MAAM,UAAU,QAAQ;AACrC,kBAAgB;GAAE,GAAG;GAAe,GAAG;GAAM;;AAE/C,QAAO;EAAE,GAAG;EAAS,GAAG;EAAe"}
|
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
|
|
4
4
|
const require_inject = require('../../server/database/inject.cjs');
|
|
5
5
|
const require_schema = require('../../server/database/schema.cjs');
|
|
6
|
-
const require_index = require('../../server/emails/index.cjs');
|
|
7
6
|
const require_encode = require('./utils/encode.cjs');
|
|
7
|
+
const require_index = require('../../server/emails/index.cjs');
|
|
8
8
|
const require_logic = require('./logic.cjs');
|
|
9
9
|
const require_session = require('./session.cjs');
|
|
10
10
|
let drizzle_orm = require("drizzle-orm");
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
import { db } from "../../server/database/inject.mjs";
|
|
4
4
|
import { emailVerificationTable } from "../../server/database/schema.mjs";
|
|
5
|
-
import { sendVerifyEmail } from "../../server/emails/index.mjs";
|
|
6
5
|
import { generateRandomOTP } from "./utils/encode.mjs";
|
|
6
|
+
import { sendVerifyEmail } from "../../server/emails/index.mjs";
|
|
7
7
|
import { registerSecurityRequirement } from "./logic.mjs";
|
|
8
8
|
import { getCurrentSession } from "./session.mjs";
|
|
9
9
|
import { and, eq } from "drizzle-orm";
|
package/dist/core/auth/logic.cjs
CHANGED
|
@@ -5,9 +5,9 @@ const require_validation = require('./validation.cjs');
|
|
|
5
5
|
const require_event_bus = require('../event-bus.cjs');
|
|
6
6
|
const require_inject = require('../../server/database/inject.cjs');
|
|
7
7
|
const require_schema = require('../../server/database/schema.cjs');
|
|
8
|
+
const require_augment = require('./augment.cjs');
|
|
8
9
|
const require_password = require('../../server/auth/password.cjs');
|
|
9
10
|
const require_user = require('../../server/auth/user.cjs');
|
|
10
|
-
const require_augment = require('./augment.cjs');
|
|
11
11
|
const require_email_verification = require('./email-verification.cjs');
|
|
12
12
|
const require_session = require('./session.cjs');
|
|
13
13
|
let drizzle_orm = require("drizzle-orm");
|
|
@@ -38,14 +38,14 @@ async function coreRbacAugmenter(user) {
|
|
|
38
38
|
}
|
|
39
39
|
}
|
|
40
40
|
const globalForAuth = globalThis;
|
|
41
|
-
const authValidators = globalForAuth.
|
|
42
|
-
const securityRequirements = globalForAuth.
|
|
43
|
-
const passwordResetValidators = globalForAuth.
|
|
44
|
-
const emailVerificationValidators = globalForAuth.
|
|
45
|
-
globalForAuth.
|
|
46
|
-
globalForAuth.
|
|
47
|
-
globalForAuth.
|
|
48
|
-
globalForAuth.
|
|
41
|
+
const authValidators = globalForAuth.__KRYO_AUTH_VALIDATORS__ ?? /* @__PURE__ */ new Set();
|
|
42
|
+
const securityRequirements = globalForAuth.__KRYO_SECURITY_REQUIREMENTS__ ?? /* @__PURE__ */ new Set();
|
|
43
|
+
const passwordResetValidators = globalForAuth.__KRYO_PASSWORD_RESET_VALIDATORS__ ?? /* @__PURE__ */ new Set();
|
|
44
|
+
const emailVerificationValidators = globalForAuth.__KRYO_EMAIL_VERIFICATION_VALIDATORS__ ?? /* @__PURE__ */ new Set();
|
|
45
|
+
globalForAuth.__KRYO_AUTH_VALIDATORS__ = authValidators;
|
|
46
|
+
globalForAuth.__KRYO_SECURITY_REQUIREMENTS__ = securityRequirements;
|
|
47
|
+
globalForAuth.__KRYO_PASSWORD_RESET_VALIDATORS__ = passwordResetValidators;
|
|
48
|
+
globalForAuth.__KRYO_EMAIL_VERIFICATION_VALIDATORS__ = emailVerificationValidators;
|
|
49
49
|
async function registerAuthValidator(validator) {
|
|
50
50
|
authValidators.add(validator);
|
|
51
51
|
}
|
|
@@ -55,10 +55,10 @@ declare function signUp(data: RegisterInput): Promise<{
|
|
|
55
55
|
session: {
|
|
56
56
|
[x: string]: any;
|
|
57
57
|
id: string;
|
|
58
|
+
active_organization_id: string | null;
|
|
58
59
|
createdAt: Date;
|
|
59
60
|
updatedAt: Date | null;
|
|
60
61
|
userId: string;
|
|
61
|
-
active_organization_id: string | null;
|
|
62
62
|
expiresAt: Date;
|
|
63
63
|
};
|
|
64
64
|
user: {
|
|
@@ -83,10 +83,10 @@ declare function finalizeLogin(userId: string, flags: SessionFlags): Promise<{
|
|
|
83
83
|
session: {
|
|
84
84
|
[x: string]: any;
|
|
85
85
|
id: string;
|
|
86
|
+
active_organization_id: string | null;
|
|
86
87
|
createdAt: Date;
|
|
87
88
|
updatedAt: Date | null;
|
|
88
89
|
userId: string;
|
|
89
|
-
active_organization_id: string | null;
|
|
90
90
|
expiresAt: Date;
|
|
91
91
|
} | null;
|
|
92
92
|
user: {
|
|
@@ -55,10 +55,10 @@ declare function signUp(data: RegisterInput): Promise<{
|
|
|
55
55
|
session: {
|
|
56
56
|
[x: string]: any;
|
|
57
57
|
id: string;
|
|
58
|
+
active_organization_id: string | null;
|
|
58
59
|
createdAt: Date;
|
|
59
60
|
updatedAt: Date | null;
|
|
60
61
|
userId: string;
|
|
61
|
-
active_organization_id: string | null;
|
|
62
62
|
expiresAt: Date;
|
|
63
63
|
};
|
|
64
64
|
user: {
|
|
@@ -83,10 +83,10 @@ declare function finalizeLogin(userId: string, flags: SessionFlags): Promise<{
|
|
|
83
83
|
session: {
|
|
84
84
|
[x: string]: any;
|
|
85
85
|
id: string;
|
|
86
|
+
active_organization_id: string | null;
|
|
86
87
|
createdAt: Date;
|
|
87
88
|
updatedAt: Date | null;
|
|
88
89
|
userId: string;
|
|
89
|
-
active_organization_id: string | null;
|
|
90
90
|
expiresAt: Date;
|
|
91
91
|
} | null;
|
|
92
92
|
user: {
|
package/dist/core/auth/logic.mjs
CHANGED
|
@@ -4,9 +4,9 @@ import { loginSchema, registerSchema } from "./validation.mjs";
|
|
|
4
4
|
import { eventBus } from "../event-bus.mjs";
|
|
5
5
|
import { db } from "../../server/database/inject.mjs";
|
|
6
6
|
import { permissionsTable, rolesTable, rolesToPermissionsTable, usersToPermissionsTable, usersToRolesTable } from "../../server/database/schema.mjs";
|
|
7
|
+
import { augmentSession, augmentUser, registerIdentityAugmenter, registerPasswordResetSessionAugmenter, registerSessionAugmenter } from "./augment.mjs";
|
|
7
8
|
import { verifyPasswordHash, verifyPasswordStrength } from "../../server/auth/password.mjs";
|
|
8
9
|
import { createUser, getUserById, getUserFromEmail, getUserPasswordHash, verifyUsernameInput } from "../../server/auth/user.mjs";
|
|
9
|
-
import { augmentSession, augmentUser, registerIdentityAugmenter, registerPasswordResetSessionAugmenter, registerSessionAugmenter } from "./augment.mjs";
|
|
10
10
|
import { createEmailVerificationRequest, sendVerificationEmail, setEmailVerificationRequestCookie } from "./email-verification.mjs";
|
|
11
11
|
import { createSession, deleteSessionTokenCookie, generateSessionToken, getCurrentSession, invalidateSession, setSessionTokenCookie } from "./session.mjs";
|
|
12
12
|
import { eq, inArray } from "drizzle-orm";
|
|
@@ -37,14 +37,14 @@ async function coreRbacAugmenter(user) {
|
|
|
37
37
|
}
|
|
38
38
|
}
|
|
39
39
|
const globalForAuth = globalThis;
|
|
40
|
-
const authValidators = globalForAuth.
|
|
41
|
-
const securityRequirements = globalForAuth.
|
|
42
|
-
const passwordResetValidators = globalForAuth.
|
|
43
|
-
const emailVerificationValidators = globalForAuth.
|
|
44
|
-
globalForAuth.
|
|
45
|
-
globalForAuth.
|
|
46
|
-
globalForAuth.
|
|
47
|
-
globalForAuth.
|
|
40
|
+
const authValidators = globalForAuth.__KRYO_AUTH_VALIDATORS__ ?? /* @__PURE__ */ new Set();
|
|
41
|
+
const securityRequirements = globalForAuth.__KRYO_SECURITY_REQUIREMENTS__ ?? /* @__PURE__ */ new Set();
|
|
42
|
+
const passwordResetValidators = globalForAuth.__KRYO_PASSWORD_RESET_VALIDATORS__ ?? /* @__PURE__ */ new Set();
|
|
43
|
+
const emailVerificationValidators = globalForAuth.__KRYO_EMAIL_VERIFICATION_VALIDATORS__ ?? /* @__PURE__ */ new Set();
|
|
44
|
+
globalForAuth.__KRYO_AUTH_VALIDATORS__ = authValidators;
|
|
45
|
+
globalForAuth.__KRYO_SECURITY_REQUIREMENTS__ = securityRequirements;
|
|
46
|
+
globalForAuth.__KRYO_PASSWORD_RESET_VALIDATORS__ = passwordResetValidators;
|
|
47
|
+
globalForAuth.__KRYO_EMAIL_VERIFICATION_VALIDATORS__ = emailVerificationValidators;
|
|
48
48
|
async function registerAuthValidator(validator) {
|
|
49
49
|
authValidators.add(validator);
|
|
50
50
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logic.mjs","names":[],"sources":["../../../src/core/auth/logic.ts"],"sourcesContent":["\"use server\";\n\nimport { eq, inArray } from \"drizzle-orm\";\nimport {\n verifyPasswordHash,\n verifyPasswordStrength,\n} from \"../../server/auth/password\";\nimport {\n createUser,\n getUserById,\n getUserFromEmail,\n getUserPasswordHash,\n verifyUsernameInput,\n} from \"../../server/auth/user\";\nimport { db } from \"../../server/database/inject\";\nimport {\n permissionsTable,\n rolesTable,\n rolesToPermissionsTable,\n usersToPermissionsTable,\n usersToRolesTable,\n} from \"../../server/database/schema\";\nimport { eventBus } from \"../event-bus\";\nimport {\n augmentSession,\n augmentUser,\n registerIdentityAugmenter,\n registerPasswordResetSessionAugmenter,\n registerSessionAugmenter,\n} from \"./augment\";\nimport {\n createEmailVerificationRequest,\n sendVerificationEmail,\n setEmailVerificationRequestCookie,\n} from \"./email-verification\";\nimport {\n createSession,\n deleteSessionTokenCookie,\n generateSessionToken,\n getCurrentSession,\n invalidateSession,\n setSessionTokenCookie,\n} from \"./session\";\nimport type {\n AuthResponse,\n FullUser,\n Session,\n SessionFlags,\n User,\n UserPermission,\n UserRole,\n} from \"./types\";\nimport {\n type LoginInput,\n loginSchema,\n type RegisterInput,\n registerSchema,\n} from \"./validation\";\n\n/**\n * Podstawowy moduł rozszerzający tożsamość dla ról i uprawnień\n */\nasync function coreRbacAugmenter(user: User): Promise<Record<string, any>> {\n try {\n // 1. Fetch direct roles\n const userRoles = await db\n .select({ name: rolesTable.name })\n .from(usersToRolesTable)\n .innerJoin(rolesTable, eq(usersToRolesTable.roleId, rolesTable.id))\n .where(eq(usersToRolesTable.userId, user.id));\n\n const roles = userRoles.map((r) => r.name);\n\n // 2. Fetch direct permissions\n const userDirectPerms = await db\n .select({ name: permissionsTable.name })\n .from(usersToPermissionsTable)\n .innerJoin(\n permissionsTable,\n eq(usersToPermissionsTable.permissionId, permissionsTable.id),\n )\n .where(eq(usersToPermissionsTable.userId, user.id));\n\n const directPerms = userDirectPerms.map((p) => p.name);\n\n // 3. Fetch permissions from roles\n let rolePerms: string[] = [];\n if (roles.length > 0) {\n const roleIdsResult = await db\n .select({ id: rolesTable.id })\n .from(rolesTable)\n .where(inArray(rolesTable.name, roles));\n\n const roleIds = roleIdsResult.map((r) => r.id);\n\n if (roleIds.length > 0) {\n const rolePermsData = await db\n .select({ name: permissionsTable.name })\n .from(rolesToPermissionsTable)\n .innerJoin(\n permissionsTable,\n eq(rolesToPermissionsTable.permissionId, permissionsTable.id),\n )\n .where(inArray(rolesToPermissionsTable.roleId, roleIds));\n rolePerms = rolePermsData.map((p) => p.name);\n }\n }\n\n return {\n roles,\n permissions: Array.from(new Set([...directPerms, ...rolePerms])),\n };\n } catch (error) {\n console.error(\"[Auth:RBAC] Failed to augment user:\", error);\n return { roles: [], permissions: [] };\n }\n}\n\n/**\n * Registry for login validators (e.g. 2FA module)\n */\ntype AuthValidator = (userId: string) => Promise<AuthResponse | null>;\n\n/**\n * Registry for Security Requirements (e.g. checking if 2FA is needed for a session)\n */\ntype SecurityRequirement = (\n session: Session,\n user: FullUser,\n) => Promise<{ satisfied: boolean; redirect?: string } | null>;\n\n/**\n * Registry for password reset validators (e.g. 2FA module requiring check during reset)\n */\ntype PasswordResetValidator = (userId: string) => Promise<AuthResponse | null>;\n\n/**\n * Registry for email verification validators\n */\ntype EmailVerificationValidator = (\n userId: string,\n) => Promise<AuthResponse | null>;\n\nconst globalForAuth = globalThis as unknown as {\n __WINKLY_AUTH_VALIDATORS__: Set<AuthValidator> | undefined;\n __WINKLY_SECURITY_REQUIREMENTS__: Set<SecurityRequirement> | undefined;\n __WINKLY_PASSWORD_RESET_VALIDATORS__: Set<PasswordResetValidator> | undefined;\n __WINKLY_EMAIL_VERIFICATION_VALIDATORS__:\n | Set<EmailVerificationValidator>\n | undefined;\n};\n\nconst authValidators =\n globalForAuth.__WINKLY_AUTH_VALIDATORS__ ?? new Set<AuthValidator>();\nconst securityRequirements =\n globalForAuth.__WINKLY_SECURITY_REQUIREMENTS__ ??\n new Set<SecurityRequirement>();\nconst passwordResetValidators =\n globalForAuth.__WINKLY_PASSWORD_RESET_VALIDATORS__ ??\n new Set<PasswordResetValidator>();\nconst emailVerificationValidators =\n globalForAuth.__WINKLY_EMAIL_VERIFICATION_VALIDATORS__ ??\n new Set<EmailVerificationValidator>();\n\nglobalForAuth.__WINKLY_AUTH_VALIDATORS__ = authValidators;\nglobalForAuth.__WINKLY_SECURITY_REQUIREMENTS__ = securityRequirements;\nglobalForAuth.__WINKLY_PASSWORD_RESET_VALIDATORS__ = passwordResetValidators;\nglobalForAuth.__WINKLY_EMAIL_VERIFICATION_VALIDATORS__ =\n emailVerificationValidators;\n\nexport async function registerAuthValidator(validator: AuthValidator) {\n authValidators.add(validator);\n}\n\nexport async function registerPasswordResetValidator(\n validator: PasswordResetValidator,\n) {\n passwordResetValidators.add(validator);\n}\n\nexport async function registerEmailVerificationValidator(\n validator: EmailVerificationValidator,\n) {\n emailVerificationValidators.add(validator);\n}\n\nexport {\n registerIdentityAugmenter,\n registerSessionAugmenter,\n registerPasswordResetSessionAugmenter,\n augmentUser,\n augmentSession,\n};\n\nexport async function registerSecurityRequirement(\n requirement: SecurityRequirement,\n) {\n securityRequirements.add(requirement);\n}\n\nexport async function runPasswordResetValidators(\n userId: string,\n): Promise<AuthResponse | null> {\n for (const validator of passwordResetValidators) {\n const interception = await validator(userId);\n if (interception) return interception;\n }\n return null;\n}\n\nexport async function runEmailVerificationValidators(\n userId: string,\n): Promise<AuthResponse | null> {\n for (const validator of emailVerificationValidators) {\n const interception = await validator(userId);\n if (interception) return interception;\n }\n return null;\n}\n\n/**\n * Augments a base user with data from all registered modules.\n * This is now just a wrapper that includes core RBAC data.\n */\nexport async function performFullUserAugmentation(\n user: User,\n): Promise<FullUser> {\n const coreRbacData = await coreRbacAugmenter(user);\n return await augmentUser(user, coreRbacData);\n}\n\n/**\n * Checks if the current session satisfies all registered security requirements.\n */\nexport async function checkSecurity(\n session: Session,\n user: FullUser,\n requiredRoles?: UserRole[],\n requiredPermissions?: UserPermission[],\n fallbackRedirect?: string,\n) {\n if (!user) {\n console.warn(\"User is required for security check\");\n return { satisfied: false, redirect: fallbackRedirect ?? \"/signin\" };\n }\n\n const userRoles = Array.isArray(user.roles) ? user.roles : [];\n const userPermissions = Array.isArray(user.permissions)\n ? user.permissions\n : [];\n\n // 1. Core Role Check (At least one role must match)\n if (requiredRoles && requiredRoles.length > 0) {\n const hasRole = requiredRoles.some((role) => userRoles.includes(role));\n if (!hasRole) {\n console.warn(`User lacks required roles: ${requiredRoles.join(\", \")}`);\n return {\n satisfied: false,\n redirect: fallbackRedirect,\n };\n }\n }\n\n // 2. Core Permission Check (ALL permissions must match)\n if (requiredPermissions && requiredPermissions.length > 0) {\n const hasAllPermissions = requiredPermissions.every((perm) =>\n userPermissions.includes(perm),\n );\n if (!hasAllPermissions) {\n console.warn(\n `User lacks required permissions: ${requiredPermissions.join(\", \")}`,\n );\n\n return {\n satisfied: false,\n redirect: fallbackRedirect,\n };\n }\n }\n\n // 3. Modular Requirements Check\n if (securityRequirements) {\n for (const requirement of securityRequirements) {\n try {\n const result = await requirement(session, user);\n if (result && !result.satisfied) {\n return {\n ...result,\n redirect: result.redirect ?? fallbackRedirect,\n };\n }\n } catch (error) {\n console.error(\"[Auth:Security] Requirement failed:\", error);\n }\n }\n }\n return { satisfied: true };\n}\n\n/**\n * Sign In Logic\n */\nexport async function signIn(data: LoginInput): Promise<AuthResponse> {\n const { email, password } = await loginSchema.parseAsync(data);\n\n const user = await getUserFromEmail(email);\n if (!user) {\n return { status: \"ERROR\", message: \"Invalid email or password\" };\n }\n\n const passwordHash = await getUserPasswordHash(user.id);\n if (!passwordHash || !(await verifyPasswordHash(passwordHash, password))) {\n return { status: \"ERROR\", message: \"Invalid email or password\" };\n }\n\n // Interception Layer\n for (const validator of authValidators) {\n const interception = await validator(user.id);\n if (interception) return interception;\n }\n\n const sessionFlags: SessionFlags = {};\n const sessionToken = await generateSessionToken();\n const session = await createSession(sessionToken, user.id, sessionFlags);\n await setSessionTokenCookie(sessionToken, session.expiresAt);\n\n const fullUser = await performFullUserAugmentation(user);\n await eventBus.publish(\"auth:session-created\", { session, user: fullUser });\n\n return {\n status: \"SUCCESS\",\n session: { ...session },\n user: { ...fullUser },\n };\n}\n\n/**\n * Sign Up Logic\n */\nexport async function signUp(data: RegisterInput) {\n const { email, username, password } = registerSchema.parse(data);\n\n if (!(await verifyUsernameInput(username))) {\n throw new Error(\"Invalid username\");\n }\n\n if (!(await verifyPasswordStrength(password))) {\n throw new Error(\"Weak password\");\n }\n\n const user = await createUser(email, username, password);\n const verificationRequest = await createEmailVerificationRequest(\n user.id,\n user.email,\n );\n\n await sendVerificationEmail(\n verificationRequest.email,\n verificationRequest.code,\n );\n await setEmailVerificationRequestCookie(verificationRequest);\n\n const sessionFlags: SessionFlags = {};\n const sessionToken = await generateSessionToken();\n const session = await createSession(sessionToken, user.id, sessionFlags);\n await setSessionTokenCookie(sessionToken, session.expiresAt);\n\n const fullUser = await performFullUserAugmentation(user);\n await eventBus.publish(\"auth:session-created\", { session, user: fullUser });\n\n return {\n session: { ...session },\n user: { ...fullUser },\n };\n}\n\n/**\n * Finalizes login after a challenge\n */\nexport async function finalizeLogin(userId: string, flags: SessionFlags) {\n const sessionToken = await generateSessionToken();\n const session = await createSession(sessionToken, userId, flags);\n await setSessionTokenCookie(sessionToken, session.expiresAt);\n\n const user = await getUserById(userId);\n\n if (user) {\n await eventBus.publish(\"auth:session-created\", { session, user });\n }\n\n return {\n session: session ? { ...session } : null,\n user: user ? { ...user } : null,\n };\n}\n\n/**\n * Sign Out\n */\nexport async function signOut() {\n const { session, user } = await getCurrentSession();\n if (session) {\n if (user) {\n await eventBus.publish(\"auth:signed-out\", { userId: user.id });\n }\n await invalidateSession(session.id);\n await deleteSessionTokenCookie();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA8DA,eAAe,kBAAkB,MAA0C;AACzE,KAAI;EAQF,MAAM,SANY,MAAM,GACrB,OAAO,EAAE,MAAM,WAAW,MAAM,CAAC,CACjC,KAAK,kBAAkB,CACvB,UAAU,YAAY,GAAG,kBAAkB,QAAQ,WAAW,GAAG,CAAC,CAClE,MAAM,GAAG,kB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sources":["../../../src/core/auth/logic.ts"],"sourcesContent":["\"use server\";\n\nimport { eq, inArray } from \"drizzle-orm\";\nimport {\n verifyPasswordHash,\n verifyPasswordStrength,\n} from \"../../server/auth/password\";\nimport {\n createUser,\n getUserById,\n getUserFromEmail,\n getUserPasswordHash,\n verifyUsernameInput,\n} from \"../../server/auth/user\";\nimport { db } from \"../../server/database/inject\";\nimport {\n permissionsTable,\n rolesTable,\n rolesToPermissionsTable,\n usersToPermissionsTable,\n usersToRolesTable,\n} from \"../../server/database/schema\";\nimport { eventBus } from \"../event-bus\";\nimport {\n augmentSession,\n augmentUser,\n registerIdentityAugmenter,\n registerPasswordResetSessionAugmenter,\n registerSessionAugmenter,\n} from \"./augment\";\nimport {\n createEmailVerificationRequest,\n sendVerificationEmail,\n setEmailVerificationRequestCookie,\n} from \"./email-verification\";\nimport {\n createSession,\n deleteSessionTokenCookie,\n generateSessionToken,\n getCurrentSession,\n invalidateSession,\n setSessionTokenCookie,\n} from \"./session\";\nimport type {\n AuthResponse,\n FullUser,\n Session,\n SessionFlags,\n User,\n UserPermission,\n UserRole,\n} from \"./types\";\nimport {\n type LoginInput,\n loginSchema,\n type RegisterInput,\n registerSchema,\n} from \"./validation\";\n\n/**\n * Podstawowy moduł rozszerzający tożsamość dla ról i uprawnień\n */\nasync function coreRbacAugmenter(user: User): Promise<Record<string, any>> {\n try {\n // 1. Fetch direct roles\n const userRoles = await db\n .select({ name: rolesTable.name })\n .from(usersToRolesTable)\n .innerJoin(rolesTable, eq(usersToRolesTable.roleId, rolesTable.id))\n .where(eq(usersToRolesTable.userId, user.id));\n\n const roles = userRoles.map((r) => r.name);\n\n // 2. Fetch direct permissions\n const userDirectPerms = await db\n .select({ name: permissionsTable.name })\n .from(usersToPermissionsTable)\n .innerJoin(\n permissionsTable,\n eq(usersToPermissionsTable.permissionId, permissionsTable.id),\n )\n .where(eq(usersToPermissionsTable.userId, user.id));\n\n const directPerms = userDirectPerms.map((p) => p.name);\n\n // 3. Fetch permissions from roles\n let rolePerms: string[] = [];\n if (roles.length > 0) {\n const roleIdsResult = await db\n .select({ id: rolesTable.id })\n .from(rolesTable)\n .where(inArray(rolesTable.name, roles));\n\n const roleIds = roleIdsResult.map((r) => r.id);\n\n if (roleIds.length > 0) {\n const rolePermsData = await db\n .select({ name: permissionsTable.name })\n .from(rolesToPermissionsTable)\n .innerJoin(\n permissionsTable,\n eq(rolesToPermissionsTable.permissionId, permissionsTable.id),\n )\n .where(inArray(rolesToPermissionsTable.roleId, roleIds));\n rolePerms = rolePermsData.map((p) => p.name);\n }\n }\n\n return {\n roles,\n permissions: Array.from(new Set([...directPerms, ...rolePerms])),\n };\n } catch (error) {\n console.error(\"[Auth:RBAC] Failed to augment user:\", error);\n return { roles: [], permissions: [] };\n }\n}\n\n/**\n * Registry for login validators (e.g. 2FA module)\n */\ntype AuthValidator = (userId: string) => Promise<AuthResponse | null>;\n\n/**\n * Registry for Security Requirements (e.g. checking if 2FA is needed for a session)\n */\ntype SecurityRequirement = (\n session: Session,\n user: FullUser,\n) => Promise<{ satisfied: boolean; redirect?: string } | null>;\n\n/**\n * Registry for password reset validators (e.g. 2FA module requiring check during reset)\n */\ntype PasswordResetValidator = (userId: string) => Promise<AuthResponse | null>;\n\n/**\n * Registry for email verification validators\n */\ntype EmailVerificationValidator = (\n userId: string,\n) => Promise<AuthResponse | null>;\n\nconst globalForAuth = globalThis as unknown as {\n __KRYO_AUTH_VALIDATORS__: Set<AuthValidator> | undefined;\n __KRYO_SECURITY_REQUIREMENTS__: Set<SecurityRequirement> | undefined;\n __KRYO_PASSWORD_RESET_VALIDATORS__: Set<PasswordResetValidator> | undefined;\n __KRYO_EMAIL_VERIFICATION_VALIDATORS__:\n | Set<EmailVerificationValidator>\n | undefined;\n};\n\nconst authValidators =\n globalForAuth.__KRYO_AUTH_VALIDATORS__ ?? new Set<AuthValidator>();\nconst securityRequirements =\n globalForAuth.__KRYO_SECURITY_REQUIREMENTS__ ??\n new Set<SecurityRequirement>();\nconst passwordResetValidators =\n globalForAuth.__KRYO_PASSWORD_RESET_VALIDATORS__ ??\n new Set<PasswordResetValidator>();\nconst emailVerificationValidators =\n globalForAuth.__KRYO_EMAIL_VERIFICATION_VALIDATORS__ ??\n new Set<EmailVerificationValidator>();\n\nglobalForAuth.__KRYO_AUTH_VALIDATORS__ = authValidators;\nglobalForAuth.__KRYO_SECURITY_REQUIREMENTS__ = securityRequirements;\nglobalForAuth.__KRYO_PASSWORD_RESET_VALIDATORS__ = passwordResetValidators;\nglobalForAuth.__KRYO_EMAIL_VERIFICATION_VALIDATORS__ =\n emailVerificationValidators;\n\nexport async function registerAuthValidator(validator: AuthValidator) {\n authValidators.add(validator);\n}\n\nexport async function registerPasswordResetValidator(\n validator: PasswordResetValidator,\n) {\n passwordResetValidators.add(validator);\n}\n\nexport async function registerEmailVerificationValidator(\n validator: EmailVerificationValidator,\n) {\n emailVerificationValidators.add(validator);\n}\n\nexport {\n registerIdentityAugmenter,\n registerSessionAugmenter,\n registerPasswordResetSessionAugmenter,\n augmentUser,\n augmentSession,\n};\n\nexport async function registerSecurityRequirement(\n requirement: SecurityRequirement,\n) {\n securityRequirements.add(requirement);\n}\n\nexport async function runPasswordResetValidators(\n userId: string,\n): Promise<AuthResponse | null> {\n for (const validator of passwordResetValidators) {\n const interception = await validator(userId);\n if (interception) return interception;\n }\n return null;\n}\n\nexport async function runEmailVerificationValidators(\n userId: string,\n): Promise<AuthResponse | null> {\n for (const validator of emailVerificationValidators) {\n const interception = await validator(userId);\n if (interception) return interception;\n }\n return null;\n}\n\n/**\n * Augments a base user with data from all registered modules.\n * This is now just a wrapper that includes core RBAC data.\n */\nexport async function performFullUserAugmentation(\n user: User,\n): Promise<FullUser> {\n const coreRbacData = await coreRbacAugmenter(user);\n return await augmentUser(user, coreRbacData);\n}\n\n/**\n * Checks if the current session satisfies all registered security requirements.\n */\nexport async function checkSecurity(\n session: Session,\n user: FullUser,\n requiredRoles?: UserRole[],\n requiredPermissions?: UserPermission[],\n fallbackRedirect?: string,\n) {\n if (!user) {\n console.warn(\"User is required for security check\");\n return { satisfied: false, redirect: fallbackRedirect ?? \"/signin\" };\n }\n\n const userRoles = Array.isArray(user.roles) ? user.roles : [];\n const userPermissions = Array.isArray(user.permissions)\n ? user.permissions\n : [];\n\n // 1. Core Role Check (At least one role must match)\n if (requiredRoles && requiredRoles.length > 0) {\n const hasRole = requiredRoles.some((role) => userRoles.includes(role));\n if (!hasRole) {\n console.warn(`User lacks required roles: ${requiredRoles.join(\", \")}`);\n return {\n satisfied: false,\n redirect: fallbackRedirect,\n };\n }\n }\n\n // 2. Core Permission Check (ALL permissions must match)\n if (requiredPermissions && requiredPermissions.length > 0) {\n const hasAllPermissions = requiredPermissions.every((perm) =>\n userPermissions.includes(perm),\n );\n if (!hasAllPermissions) {\n console.warn(\n `User lacks required permissions: ${requiredPermissions.join(\", \")}`,\n );\n\n return {\n satisfied: false,\n redirect: fallbackRedirect,\n };\n }\n }\n\n // 3. Modular Requirements Check\n if (securityRequirements) {\n for (const requirement of securityRequirements) {\n try {\n const result = await requirement(session, user);\n if (result && !result.satisfied) {\n return {\n ...result,\n redirect: result.redirect ?? fallbackRedirect,\n };\n }\n } catch (error) {\n console.error(\"[Auth:Security] Requirement failed:\", error);\n }\n }\n }\n return { satisfied: true };\n}\n\n/**\n * Sign In Logic\n */\nexport async function signIn(data: LoginInput): Promise<AuthResponse> {\n const { email, password } = await loginSchema.parseAsync(data);\n\n const user = await getUserFromEmail(email);\n if (!user) {\n return { status: \"ERROR\", message: \"Invalid email or password\" };\n }\n\n const passwordHash = await getUserPasswordHash(user.id);\n if (!passwordHash || !(await verifyPasswordHash(passwordHash, password))) {\n return { status: \"ERROR\", message: \"Invalid email or password\" };\n }\n\n // Interception Layer\n for (const validator of authValidators) {\n const interception = await validator(user.id);\n if (interception) return interception;\n }\n\n const sessionFlags: SessionFlags = {};\n const sessionToken = await generateSessionToken();\n const session = await createSession(sessionToken, user.id, sessionFlags);\n await setSessionTokenCookie(sessionToken, session.expiresAt);\n\n const fullUser = await performFullUserAugmentation(user);\n await eventBus.publish(\"auth:session-created\", { session, user: fullUser });\n\n return {\n status: \"SUCCESS\",\n session: { ...session },\n user: { ...fullUser },\n };\n}\n\n/**\n * Sign Up Logic\n */\nexport async function signUp(data: RegisterInput) {\n const { email, username, password } = registerSchema.parse(data);\n\n if (!(await verifyUsernameInput(username))) {\n throw new Error(\"Invalid username\");\n }\n\n if (!(await verifyPasswordStrength(password))) {\n throw new Error(\"Weak password\");\n }\n\n const user = await createUser(email, username, password);\n const verificationRequest = await createEmailVerificationRequest(\n user.id,\n user.email,\n );\n\n await sendVerificationEmail(\n verificationRequest.email,\n verificationRequest.code,\n );\n await setEmailVerificationRequestCookie(verificationRequest);\n\n const sessionFlags: SessionFlags = {};\n const sessionToken = await generateSessionToken();\n const session = await createSession(sessionToken, user.id, sessionFlags);\n await setSessionTokenCookie(sessionToken, session.expiresAt);\n\n const fullUser = await performFullUserAugmentation(user);\n await eventBus.publish(\"auth:session-created\", { session, user: fullUser });\n\n return {\n session: { ...session },\n user: { ...fullUser },\n };\n}\n\n/**\n * Finalizes login after a challenge\n */\nexport async function finalizeLogin(userId: string, flags: SessionFlags) {\n const sessionToken = await generateSessionToken();\n const session = await createSession(sessionToken, userId, flags);\n await setSessionTokenCookie(sessionToken, session.expiresAt);\n\n const user = await getUserById(userId);\n\n if (user) {\n await eventBus.publish(\"auth:session-created\", { session, user });\n }\n\n return {\n session: session ? { ...session } : null,\n user: user ? { ...user } : null,\n };\n}\n\n/**\n * Sign Out\n */\nexport async function signOut() {\n const { session, user } = await getCurrentSession();\n if (session) {\n if (user) {\n await eventBus.publish(\"auth:signed-out\", { userId: user.id });\n }\n await invalidateSession(session.id);\n await deleteSessionTokenCookie();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA8DA,eAAe,kBAAkB,MAA0C;AACzE,KAAI;EAQF,MAAM,SANY,MAAM,GACrB,OAAO,EAAE,MAAM,WAAW,MAAM,C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,CAAC;AAEhE,QAAM,kBAAkB,QAAQ,GAAG;AACnC,QAAM,0BAA0B"}
|
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
|
|
4
4
|
const require_inject = require('../../server/database/inject.cjs');
|
|
5
5
|
const require_schema = require('../../server/database/schema.cjs');
|
|
6
|
-
const require_index = require('../../server/emails/index.cjs');
|
|
7
|
-
const require_encode = require('./utils/encode.cjs');
|
|
8
6
|
const require_augment = require('./augment.cjs');
|
|
7
|
+
const require_encode = require('./utils/encode.cjs');
|
|
8
|
+
const require_index = require('../../server/emails/index.cjs');
|
|
9
9
|
const require_logic = require('./logic.cjs');
|
|
10
10
|
let drizzle_orm = require("drizzle-orm");
|
|
11
11
|
let _oslojs_crypto_sha2 = require("@oslojs/crypto/sha2");
|
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
import { db } from "../../server/database/inject.mjs";
|
|
4
4
|
import { passwordResetSessionTable, userTable } from "../../server/database/schema.mjs";
|
|
5
|
-
import { sendResetPassword } from "../../server/emails/index.mjs";
|
|
6
|
-
import { generateRandomOTP } from "./utils/encode.mjs";
|
|
7
5
|
import { augmentPasswordResetSession } from "./augment.mjs";
|
|
6
|
+
import { generateRandomOTP } from "./utils/encode.mjs";
|
|
7
|
+
import { sendResetPassword } from "../../server/emails/index.mjs";
|
|
8
8
|
import { performFullUserAugmentation } from "./logic.mjs";
|
|
9
9
|
import { eq } from "drizzle-orm";
|
|
10
10
|
import { sha256 } from "@oslojs/crypto/sha2";
|
|
@@ -5,7 +5,6 @@ const require_inject = require('../../server/database/inject.cjs');
|
|
|
5
5
|
const require_schema = require('../../server/database/schema.cjs');
|
|
6
6
|
const require_augment = require('./augment.cjs');
|
|
7
7
|
const require_logic = require('./logic.cjs');
|
|
8
|
-
const require_bootstrap = require('../bootstrap.cjs');
|
|
9
8
|
let drizzle_orm = require("drizzle-orm");
|
|
10
9
|
let _oslojs_crypto_sha2 = require("@oslojs/crypto/sha2");
|
|
11
10
|
let _oslojs_encoding = require("@oslojs/encoding");
|
|
@@ -24,7 +23,6 @@ async function getIPAddress() {
|
|
|
24
23
|
* Validates the session token.
|
|
25
24
|
*/
|
|
26
25
|
async function validateSessionToken(token) {
|
|
27
|
-
await require_bootstrap.ensureSystemInitialized();
|
|
28
26
|
const sessionId = (0, _oslojs_encoding.encodeHexLowerCase)((0, _oslojs_crypto_sha2.sha256)(new TextEncoder().encode(token)));
|
|
29
27
|
const [row] = await require_inject.db.select({
|
|
30
28
|
session: require_schema.sessionTable,
|
|
@@ -65,14 +63,12 @@ const getCurrentSession = async () => {
|
|
|
65
63
|
* Invalidates a single session.
|
|
66
64
|
*/
|
|
67
65
|
async function invalidateSession(sessionId) {
|
|
68
|
-
await require_bootstrap.ensureSystemInitialized();
|
|
69
66
|
await require_inject.db.delete(require_schema.sessionTable).where((0, drizzle_orm.eq)(require_schema.sessionTable.id, sessionId));
|
|
70
67
|
}
|
|
71
68
|
/**
|
|
72
69
|
* Invalidates all user sessions.
|
|
73
70
|
*/
|
|
74
71
|
async function invalidateUserSessions(userId) {
|
|
75
|
-
await require_bootstrap.ensureSystemInitialized();
|
|
76
72
|
await require_inject.db.delete(require_schema.sessionTable).where((0, drizzle_orm.eq)(require_schema.sessionTable.userId, userId));
|
|
77
73
|
}
|
|
78
74
|
/**
|
|
@@ -105,7 +101,6 @@ async function generateSessionToken() {
|
|
|
105
101
|
* Creates a new session in the database.
|
|
106
102
|
*/
|
|
107
103
|
async function createSession(token, userId, flags) {
|
|
108
|
-
await require_bootstrap.ensureSystemInitialized();
|
|
109
104
|
const sessionId = (0, _oslojs_encoding.encodeHexLowerCase)((0, _oslojs_crypto_sha2.sha256)(new TextEncoder().encode(token)));
|
|
110
105
|
const [session] = await require_inject.db.insert(require_schema.sessionTable).values({
|
|
111
106
|
id: sessionId,
|
|
@@ -130,7 +125,6 @@ async function sessionSignOut() {
|
|
|
130
125
|
* Get all active sessions for a user.
|
|
131
126
|
*/
|
|
132
127
|
async function getUserSessions(userId, currentSessionId) {
|
|
133
|
-
await require_bootstrap.ensureSystemInitialized();
|
|
134
128
|
return (await require_inject.db.select().from(require_schema.sessionTable).where((0, drizzle_orm.eq)(require_schema.sessionTable.userId, userId))).map((session) => ({
|
|
135
129
|
id: session.id,
|
|
136
130
|
createdAt: session.createdAt,
|
|
@@ -142,7 +136,6 @@ async function getUserSessions(userId, currentSessionId) {
|
|
|
142
136
|
* Invalidate all sessions for a user except the specified current one.
|
|
143
137
|
*/
|
|
144
138
|
async function invalidateOtherSessions(userId, currentSessionId) {
|
|
145
|
-
await require_bootstrap.ensureSystemInitialized();
|
|
146
139
|
await require_inject.db.delete(require_schema.sessionTable).where((0, drizzle_orm.and)((0, drizzle_orm.eq)(require_schema.sessionTable.userId, userId), (0, drizzle_orm.ne)(require_schema.sessionTable.id, currentSessionId)));
|
|
147
140
|
}
|
|
148
141
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.d.cts","names":[],"sources":["../../../src/core/auth/session.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"session.d.cts","names":[],"sources":["../../../src/core/auth/session.ts"],"mappings":";;;;;AA2BA;iBAAsB,YAAA,CAAA,GAAgB,OAAA;;;;iBAOhB,oBAAA,CACpB,KAAA,WACC,OAAA,CAAQ,WAAA;;;;cAyCE,iBAAA,QAA8B,OAAA,CAAQ,WAAA;;;;iBAc7B,iBAAA,CAAkB,SAAA,WAAoB,OAAA;AAd5D;;;AAAA,iBAqBsB,sBAAA,CAAuB,MAAA,WAAiB,OAAA;;AAP9D;;iBAcsB,qBAAA,CACpB,KAAA,UACA,SAAA,EAAW,IAAA,GACV,OAAA;;;AAVH;iBAwBsB,wBAAA,CAAA,GAA4B,OAAA;;;;iBAQ5B,oBAAA,CAAA,GAAwB,OAAA;;;;iBASxB,aAAA,CACpB,KAAA,UACA,MAAA,UACA,KAAA,EAAO,YAAA,GACN,OAAA,CAAQ,OAAA;;;;iBAmBW,cAAA,CAAA,GAAc,OAAA;;AAxCpC;;iBAsDsB,eAAA,CACpB,MAAA,UACA,gBAAA,WACC,OAAA,CAAQ,WAAA;;;AAjDX;iBAkEsB,uBAAA,CACpB,MAAA,UACA,gBAAA,WACC,OAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.d.mts","names":[],"sources":["../../../src/core/auth/session.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"session.d.mts","names":[],"sources":["../../../src/core/auth/session.ts"],"mappings":";;;;;AA2BA;iBAAsB,YAAA,CAAA,GAAgB,OAAA;;;;iBAOhB,oBAAA,CACpB,KAAA,WACC,OAAA,CAAQ,WAAA;;;;cAyCE,iBAAA,QAA8B,OAAA,CAAQ,WAAA;;;;iBAc7B,iBAAA,CAAkB,SAAA,WAAoB,OAAA;AAd5D;;;AAAA,iBAqBsB,sBAAA,CAAuB,MAAA,WAAiB,OAAA;;AAP9D;;iBAcsB,qBAAA,CACpB,KAAA,UACA,SAAA,EAAW,IAAA,GACV,OAAA;;;AAVH;iBAwBsB,wBAAA,CAAA,GAA4B,OAAA;;;;iBAQ5B,oBAAA,CAAA,GAAwB,OAAA;;;;iBASxB,aAAA,CACpB,KAAA,UACA,MAAA,UACA,KAAA,EAAO,YAAA,GACN,OAAA,CAAQ,OAAA;;;;iBAmBW,cAAA,CAAA,GAAc,OAAA;;AAxCpC;;iBAsDsB,eAAA,CACpB,MAAA,UACA,gBAAA,WACC,OAAA,CAAQ,WAAA;;;AAjDX;iBAkEsB,uBAAA,CACpB,MAAA,UACA,gBAAA,WACC,OAAA"}
|
|
@@ -4,7 +4,6 @@ import { db } from "../../server/database/inject.mjs";
|
|
|
4
4
|
import { sessionTable, userTable } from "../../server/database/schema.mjs";
|
|
5
5
|
import { augmentSession } from "./augment.mjs";
|
|
6
6
|
import { performFullUserAugmentation } from "./logic.mjs";
|
|
7
|
-
import { ensureSystemInitialized } from "../bootstrap.mjs";
|
|
8
7
|
import { and, eq, ne } from "drizzle-orm";
|
|
9
8
|
import { sha256 } from "@oslojs/crypto/sha2";
|
|
10
9
|
import { encodeBase32LowerCaseNoPadding, encodeHexLowerCase } from "@oslojs/encoding";
|
|
@@ -23,7 +22,6 @@ async function getIPAddress() {
|
|
|
23
22
|
* Validates the session token.
|
|
24
23
|
*/
|
|
25
24
|
async function validateSessionToken(token) {
|
|
26
|
-
await ensureSystemInitialized();
|
|
27
25
|
const sessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(token)));
|
|
28
26
|
const [row] = await db.select({
|
|
29
27
|
session: sessionTable,
|
|
@@ -64,14 +62,12 @@ const getCurrentSession = async () => {
|
|
|
64
62
|
* Invalidates a single session.
|
|
65
63
|
*/
|
|
66
64
|
async function invalidateSession(sessionId) {
|
|
67
|
-
await ensureSystemInitialized();
|
|
68
65
|
await db.delete(sessionTable).where(eq(sessionTable.id, sessionId));
|
|
69
66
|
}
|
|
70
67
|
/**
|
|
71
68
|
* Invalidates all user sessions.
|
|
72
69
|
*/
|
|
73
70
|
async function invalidateUserSessions(userId) {
|
|
74
|
-
await ensureSystemInitialized();
|
|
75
71
|
await db.delete(sessionTable).where(eq(sessionTable.userId, userId));
|
|
76
72
|
}
|
|
77
73
|
/**
|
|
@@ -104,7 +100,6 @@ async function generateSessionToken() {
|
|
|
104
100
|
* Creates a new session in the database.
|
|
105
101
|
*/
|
|
106
102
|
async function createSession(token, userId, flags) {
|
|
107
|
-
await ensureSystemInitialized();
|
|
108
103
|
const sessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(token)));
|
|
109
104
|
const [session] = await db.insert(sessionTable).values({
|
|
110
105
|
id: sessionId,
|
|
@@ -129,7 +124,6 @@ async function sessionSignOut() {
|
|
|
129
124
|
* Get all active sessions for a user.
|
|
130
125
|
*/
|
|
131
126
|
async function getUserSessions(userId, currentSessionId) {
|
|
132
|
-
await ensureSystemInitialized();
|
|
133
127
|
return (await db.select().from(sessionTable).where(eq(sessionTable.userId, userId))).map((session) => ({
|
|
134
128
|
id: session.id,
|
|
135
129
|
createdAt: session.createdAt,
|
|
@@ -141,7 +135,6 @@ async function getUserSessions(userId, currentSessionId) {
|
|
|
141
135
|
* Invalidate all sessions for a user except the specified current one.
|
|
142
136
|
*/
|
|
143
137
|
async function invalidateOtherSessions(userId, currentSessionId) {
|
|
144
|
-
await ensureSystemInitialized();
|
|
145
138
|
await db.delete(sessionTable).where(and(eq(sessionTable.userId, userId), ne(sessionTable.id, currentSessionId)));
|
|
146
139
|
}
|
|
147
140
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.mjs","names":[],"sources":["../../../src/core/auth/session.ts"],"sourcesContent":["\"use server\";\n\nimport { sha256 } from \"@oslojs/crypto/sha2\";\nimport {\n encodeBase32LowerCaseNoPadding,\n encodeHexLowerCase,\n} from \"@oslojs/encoding\";\nimport { addDays } from \"date-fns\";\nimport { and, eq, ne } from \"drizzle-orm\";\nimport { cookies, headers } from \"next/headers\";\nimport { redirect } from \"next/navigation\";\nimport { db } from \"../../server/database/inject\";\nimport { sessionTable, userTable } from \"../../server/database/schema\";\nimport {
|
|
1
|
+
{"version":3,"file":"session.mjs","names":[],"sources":["../../../src/core/auth/session.ts"],"sourcesContent":["\"use server\";\n\nimport { sha256 } from \"@oslojs/crypto/sha2\";\nimport {\n encodeBase32LowerCaseNoPadding,\n encodeHexLowerCase,\n} from \"@oslojs/encoding\";\nimport { addDays } from \"date-fns\";\nimport { and, eq, ne } from \"drizzle-orm\";\nimport { cookies, headers } from \"next/headers\";\nimport { redirect } from \"next/navigation\";\nimport { db } from \"../../server/database/inject\";\nimport { sessionTable, userTable } from \"../../server/database/schema\";\nimport { augmentSession } from \"./augment\";\nimport { performFullUserAugmentation } from \"./logic\";\n\nimport type {\n AuthSession,\n Session,\n SessionFlags,\n User,\n UserSession,\n} from \"./types\";\n\n/**\n * Returns the user's IP address.\n */\nexport async function getIPAddress(): Promise<string | null> {\n return (await headers()).get(\"x-forwarded-for\");\n}\n\n/**\n * Validates the session token.\n */\nexport async function validateSessionToken(\n token: string,\n): Promise<AuthSession> {\n const sessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(token)));\n\n const [row] = await db\n .select({\n session: sessionTable,\n user: userTable,\n })\n .from(sessionTable)\n .innerJoin(userTable, eq(sessionTable.userId, userTable.id))\n .where(eq(sessionTable.id, sessionId));\n\n if (!row || !row.user) {\n return { session: null, user: null };\n }\n\n const { session: baseSession, user: baseUser } = row;\n\n // STRICTLY remove non-serializable and sensitive fields\n const { password, recovery_code, ...safeUser } = baseUser;\n\n // Check if session is expired\n if (new Date() > baseSession.expiresAt) {\n await db.delete(sessionTable).where(eq(sessionTable.id, baseSession.id));\n return { session: null, user: null };\n }\n\n // AUGMENT (EXTENSIBILITY POINTS)\n const augmentedUser = await performFullUserAugmentation(safeUser as User);\n const augmentedSession = await augmentSession(baseSession as Session);\n\n // ENSURE PLAIN OBJECTS for Client Components\n return {\n session: augmentedSession ? { ...augmentedSession } : null,\n user: augmentedUser ? { ...augmentedUser } : null,\n };\n}\n\n/**\n * Returns the current user session from cookies.\n */\nexport const getCurrentSession = async (): Promise<AuthSession> => {\n const cookieStore = await cookies();\n const token = cookieStore.get(\"session\")?.value ?? null;\n\n if (token === null) {\n return { session: null, user: null };\n }\n\n return await validateSessionToken(token);\n};\n\n/**\n * Invalidates a single session.\n */\nexport async function invalidateSession(sessionId: string): Promise<void> {\n await db.delete(sessionTable).where(eq(sessionTable.id, sessionId));\n}\n\n/**\n * Invalidates all user sessions.\n */\nexport async function invalidateUserSessions(userId: string): Promise<void> {\n await db.delete(sessionTable).where(eq(sessionTable.userId, userId));\n}\n\n/**\n * Sets the session token in a cookie.\n */\nexport async function setSessionTokenCookie(\n token: string,\n expiresAt: Date,\n): Promise<void> {\n const cookieStore = await cookies();\n cookieStore.set(\"session\", token, {\n httpOnly: true,\n path: \"/\",\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"lax\",\n expires: expiresAt,\n });\n}\n\n/**\n * Removes the session token cookie.\n */\nexport async function deleteSessionTokenCookie(): Promise<void> {\n const cookieStore = await cookies();\n cookieStore.delete(\"session\");\n}\n\n/**\n * Generates a new random session token.\n */\nexport async function generateSessionToken(): Promise<string> {\n const tokenBytes = new Uint8Array(20);\n crypto.getRandomValues(tokenBytes);\n return encodeBase32LowerCaseNoPadding(tokenBytes).toLowerCase();\n}\n\n/**\n * Creates a new session in the database.\n */\nexport async function createSession(\n token: string,\n userId: string,\n flags: SessionFlags,\n): Promise<Session> {\n const sessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(token)));\n\n const [session] = await db\n .insert(sessionTable)\n .values({\n id: sessionId,\n expiresAt: new Date(addDays(new Date(), 7)),\n active_organization_id: flags.activeOrganizationId,\n userId: userId,\n })\n .returning();\n\n return session;\n}\n\n/**\n * Signs the user out and redirects to the sign-in page.\n */\nexport async function sessionSignOut() {\n const { session } = await getCurrentSession();\n\n if (session) {\n await invalidateSession(session.id);\n await deleteSessionTokenCookie();\n }\n\n redirect(\"/signin\");\n}\n\n/**\n * Get all active sessions for a user.\n */\nexport async function getUserSessions(\n userId: string,\n currentSessionId: string,\n): Promise<UserSession[]> {\n const sessions = await db\n .select()\n .from(sessionTable)\n .where(eq(sessionTable.userId, userId));\n\n return sessions.map((session) => ({\n id: session.id,\n createdAt: session.createdAt,\n expiresAt: session.expiresAt,\n isCurrent: session.id === currentSessionId,\n }));\n}\n\n/**\n * Invalidate all sessions for a user except the specified current one.\n */\nexport async function invalidateOtherSessions(\n userId: string,\n currentSessionId: string,\n): Promise<void> {\n await db\n .delete(sessionTable)\n .where(\n and(\n eq(sessionTable.userId, userId),\n ne(sessionTable.id, currentSessionId),\n ),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA2BA,eAAsB,eAAuC;AAC3D,SAAQ,MAAM,SAAS,EAAE,IAAI,kBAAkB;;;;;AAMjD,eAAsB,qBACpB,OACsB;CACtB,MAAM,YAAY,mBAAmB,OAAO,IA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_event_bus = require('./event-bus.cjs');
|
|
2
2
|
const require_inject = require('../server/database/inject.cjs');
|
|
3
3
|
const require_email_verification = require('./auth/email-verification.cjs');
|
|
4
|
-
const require_setup = require('./setup.cjs');
|
|
5
4
|
const require_service = require('./notifications/service.cjs');
|
|
5
|
+
const require_local = require('./filesystem/providers/local.cjs');
|
|
6
|
+
const require_service$1 = require('./filesystem/service.cjs');
|
|
7
|
+
require('./filesystem/index.cjs');
|
|
8
|
+
const require_setup = require('./setup.cjs');
|
|
6
9
|
|
|
7
10
|
//#region src/core/bootstrap.ts
|
|
8
11
|
async function ensureSystemInitialized(providedDb) {
|
|
@@ -15,9 +18,13 @@ async function ensureSystemInitialized(providedDb) {
|
|
|
15
18
|
try {
|
|
16
19
|
console.log("[Kryo:Bootstrap] Starting system initialization...");
|
|
17
20
|
if (!g.__KRYO_DB__) console.warn("[Kryo:Bootstrap] DB not detected during bootstrap start. Trying to continue...");
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
+
if (await require_setup.isSystemInstalled()) {
|
|
22
|
+
require_service.notificationService.init();
|
|
23
|
+
await require_email_verification.initEmailVerification();
|
|
24
|
+
const local = new require_local.LocalFileProvider();
|
|
25
|
+
require_service$1.filesystemService.registerProvider(local);
|
|
26
|
+
require_service$1.filesystemService.setDefaultProvider(local.id);
|
|
27
|
+
} else console.log("[Kryo:Bootstrap] System not installed. Skipping module initialization.");
|
|
21
28
|
await require_event_bus.eventBus.publish("system:start", { runtime: "nodejs" });
|
|
22
29
|
console.log("[Kryo:Bootstrap] System initialized successfully.");
|
|
23
30
|
g.__KRYO_INITIALIZED__ = true;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bootstrap.d.cts","names":[],"sources":["../../src/core/bootstrap.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"bootstrap.d.cts","names":[],"sources":["../../src/core/bootstrap.ts"],"mappings":";iBAQsB,uBAAA,CAAwB,UAAA,SAAgB,OAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bootstrap.d.mts","names":[],"sources":["../../src/core/bootstrap.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"bootstrap.d.mts","names":[],"sources":["../../src/core/bootstrap.ts"],"mappings":";iBAQsB,uBAAA,CAAwB,UAAA,SAAgB,OAAA"}
|
package/dist/core/bootstrap.mjs
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { eventBus } from "./event-bus.mjs";
|
|
2
2
|
import { injectDb } from "../server/database/inject.mjs";
|
|
3
3
|
import { initEmailVerification } from "./auth/email-verification.mjs";
|
|
4
|
-
import { isSystemInstalled } from "./setup.mjs";
|
|
5
4
|
import { notificationService } from "./notifications/service.mjs";
|
|
5
|
+
import { LocalFileProvider } from "./filesystem/providers/local.mjs";
|
|
6
|
+
import { filesystemService } from "./filesystem/service.mjs";
|
|
7
|
+
import "./filesystem/index.mjs";
|
|
8
|
+
import { isSystemInstalled } from "./setup.mjs";
|
|
6
9
|
|
|
7
10
|
//#region src/core/bootstrap.ts
|
|
8
11
|
async function ensureSystemInitialized(providedDb) {
|
|
@@ -15,9 +18,13 @@ async function ensureSystemInitialized(providedDb) {
|
|
|
15
18
|
try {
|
|
16
19
|
console.log("[Kryo:Bootstrap] Starting system initialization...");
|
|
17
20
|
if (!g.__KRYO_DB__) console.warn("[Kryo:Bootstrap] DB not detected during bootstrap start. Trying to continue...");
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
+
if (await isSystemInstalled()) {
|
|
22
|
+
notificationService.init();
|
|
23
|
+
await initEmailVerification();
|
|
24
|
+
const local = new LocalFileProvider();
|
|
25
|
+
filesystemService.registerProvider(local);
|
|
26
|
+
filesystemService.setDefaultProvider(local.id);
|
|
27
|
+
} else console.log("[Kryo:Bootstrap] System not installed. Skipping module initialization.");
|
|
21
28
|
await eventBus.publish("system:start", { runtime: "nodejs" });
|
|
22
29
|
console.log("[Kryo:Bootstrap] System initialized successfully.");
|
|
23
30
|
g.__KRYO_INITIALIZED__ = true;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bootstrap.mjs","names":[],"sources":["../../src/core/bootstrap.ts"],"sourcesContent":["import { injectDb } from \"../server/database/inject\";\nimport { initEmailVerification } from \"./auth/email-verification\";\nimport { eventBus } from \"./event-bus\";\nimport { notificationService } from \"./notifications/service\";\nimport { isSystemInstalled } from \"./setup\";\n\nexport async function ensureSystemInitialized(providedDb?: any) {\n if (typeof window !== \"undefined\") return;\n\n const g = globalThis as any;\n\n // 1. Immediate injection if provided\n if (providedDb) {\n
|
|
1
|
+
{"version":3,"file":"bootstrap.mjs","names":[],"sources":["../../src/core/bootstrap.ts"],"sourcesContent":["import { injectDb } from \"../server/database/inject\";\nimport { initEmailVerification } from \"./auth/email-verification\";\nimport { eventBus } from \"./event-bus\";\nimport { filesystemService } from \"./filesystem\";\nimport { LocalFileProvider } from \"./filesystem/providers/local\";\nimport { notificationService } from \"./notifications/service\";\nimport { isSystemInstalled } from \"./setup\";\n\nexport async function ensureSystemInitialized(providedDb?: any) {\n if (typeof window !== \"undefined\") return;\n\n const g = globalThis as any;\n\n // 1. Immediate injection if provided\n if (providedDb) {\n injectDb(providedDb);\n }\n\n // 2. Prevent infinite recursion and double initialization\n if (g.__KRYO_INITIALIZED__) return;\n if (g.__KRYO_INITIALIZING__) return; // Already in progress, don't block/deadlock\n\n g.__KRYO_INITIALIZING__ = true;\n\n try {\n console.log(\"[Kryo:Bootstrap] Starting system initialization...\");\n\n // Check if we have DB after any possible injection\n if (!g.__KRYO_DB__) {\n console.warn(\n \"[Kryo:Bootstrap] DB not detected during bootstrap start. Trying to continue...\",\n );\n }\n\n // Check if system is installed before initializing modules\n if (await isSystemInstalled()) {\n // Order matters: services first, then modules (which use services)\n notificationService.init();\n await initEmailVerification();\n\n // Auto-register local filesystem provider as a fallback\n const local = new LocalFileProvider();\n\n filesystemService.registerProvider(local);\n filesystemService.setDefaultProvider(local.id);\n } else {\n console.log(\n \"[Kryo:Bootstrap] System not installed. Skipping module initialization.\",\n );\n }\n\n await eventBus.publish(\"system:start\", { runtime: \"nodejs\" });\n\n console.log(\"[Kryo:Bootstrap] System initialized successfully.\");\n g.__KRYO_INITIALIZED__ = true;\n } catch (error) {\n console.error(\"[Kryo:Bootstrap] Initialization failed:\", error);\n } finally {\n g.__KRYO_INITIALIZING__ = false;\n }\n}\n"],"mappings":";;;;;;;;;;AAQA,eAAsB,wBAAwB,YAAkB;AAC9D,KAAI,OAAO,WAAW,YAAa;CAEnC,MAAM,IAAI;AAGV,KAAI,WACF,UAAS,WAAW;AAItB,KAAI,EAAE,qBAAsB;AAC5B,KAAI,EAAE,sBAAuB;AAE7B,GAAE,wBAAwB;AAE1B,KAAI;AACF,UAAQ,IAAI,qDAAqD;AAGjE,MAAI,CAAC,EAAE,YACL,SAAQ,KACN,iFACD;AAIH,MAAI,MAAM,mBAAmB,EAAE;AAE7B,uBAAoB,MAAM;AAC1B,SAAM,uBAAuB;GAG7B,MAAM,QAAQ,IAAI,mBAAmB;AAErC,qBAAkB,iBAAiB,MAAM;AACzC,qBAAkB,mBAAmB,MAAM,GAAG;QAE9C,SAAQ,IACN,yEACD;AAGH,QAAM,SAAS,QAAQ,gBAAgB,EAAE,SAAS,UAAU,CAAC;AAE7D,UAAQ,IAAI,oDAAoD;AAChE,IAAE,uBAAuB;UAClB,OAAO;AACd,UAAQ,MAAM,2CAA2C,MAAM;WACvD;AACR,IAAE,wBAAwB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.server.mjs","names":[],"sources":["../../src/core/config.server.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { DEFAULT_CONFIG, type KryoConfig } from \"./config\";\n\nlet cachedConfig: KryoConfig | null = null;\n\n/**\n * Loads the Kryo configuration from kryo.config.ts or kryo.config.js in the current working directory.\n * SERVER ONLY.\n */\nexport async function getKryoConfig(): Promise<KryoConfig> {\n // Prevent this from ever running on the client even if imported\n if (typeof window !== \"undefined\") {\n throw new Error(\"getKryoConfig can only be called on the server.\");\n }\n\n // Use memory cache in production\n if (process.env.NODE_ENV === \"production\" && cachedConfig) {\n return cachedConfig;\n }\n\n const cwd = process.cwd();\n const configPathTS = path.join(cwd, \"kryo.config.ts\");\n const configPathJS = path.join(cwd, \"kryo.config.js\");\n const configPathMJS = path.join(cwd, \"kryo.config.mjs\");\n\n let loadedConfig: Partial<KryoConfig> = {};\n\n try {\n // Dynamic import jiti only on server to avoid bundling issues\n const { createJiti } = await import(\"jiti\");\n const jiti = createJiti(cwd, {\n fsCache: false,\n moduleCache: false,\n });\n\n if (fs.existsSync(configPathTS)) {\n const cacheBuster = `?t=${Date.now()}`;\n const imported: any = await jiti.import(\n `file://${configPathTS}${cacheBuster}`,\n { default: true },\n );\n loadedConfig = imported.default || imported;\n } else if (fs.existsSync(configPathMJS)) {\n const imported: any = await jiti.import(configPathMJS, { default: true });\n loadedConfig = imported.default || imported;\n } else if (fs.existsSync(configPathJS)) {\n const imported: any = await jiti.import(configPathJS, { default: true });\n loadedConfig = imported.default || imported;\n }\n } catch (error) {\n console.warn(\n \"[Kryo:Config] Could not load kryo.config.ts, using defaults.\",\n error,\n );\n }\n\n const finalConfig = { ...DEFAULT_CONFIG, ...loadedConfig };\n\n if (process.env.NODE_ENV === \"production\") {\n cachedConfig = finalConfig;\n }\n\n return finalConfig;\n}\n\n/**\n * Helper returning the absolute path to the modules directory.\n * SERVER ONLY.\n */\nexport async function getModulesDir(): Promise<string> {\n const config = await getKryoConfig();\n const dir = config.modulesDirectory || \"modules\";\n return path.isAbsolute(dir) ? dir : path.join(process.cwd(), dir);\n}\n"],"mappings":";;;;;AAIA,IAAI,eAAkC;;;;;AAMtC,eAAsB,gBAAqC;AAEzD,KAAI,OAAO,WAAW,YACpB,OAAM,IAAI,MAAM,kDAAkD;AAIpE,KAAI,QAAQ,IAAI,aAAa,gBAAgB,aAC3C,QAAO;CAGT,MAAM,MAAM,QAAQ,KAAK;CACzB,MAAM,eAAe,KAAK,KAAK,KAAK,iBAAiB;CACrD,MAAM,eAAe,KAAK,KAAK,KAAK,iBAAiB;CACrD,MAAM,gBAAgB,KAAK,KAAK,KAAK,kBAAkB;CAEvD,IAAI,eAAoC,EAAE;AAE1C,KAAI;EAEF,MAAM,EAAE,eAAe,MAAM,OAAO;EACpC,MAAM,OAAO,WAAW,KAAK;GAC3B,SAAS;GACT,aAAa;GACd,CAAC;AAEF,MAAI,GAAG,WAAW,aAAa,EAAE;GAC/B,MAAM,cAAc,MAAM,KAAK,KAAK;GACpC,MAAM,WAAgB,MAAM,KAAK,OAC/B,UAAU,eAAe,eACzB,EAAE,SAAS,MAAM,CAClB;AACD,kBAAe,SAAS,WAAW;aAC1B,GAAG,WAAW,cAAc,EAAE;GACvC,MAAM,WAAgB,MAAM,KAAK,OAAO,eAAe,EAAE,SAAS,MAAM,CAAC;AACzE,kBAAe,SAAS,WAAW;aAC1B,GAAG,WAAW,aAAa,EAAE;GACtC,MAAM,WAAgB,MAAM,KAAK,OAAO,cAAc,EAAE,SAAS,MAAM,CAAC;AACxE,kBAAe,SAAS,WAAW;;UAE9B,OAAO;AACd,UAAQ,KACN,gEACA,MACD;;CAGH,MAAM,cAAc;EAAE,GAAG;EAAgB,GAAG;EAAc;AAE1D,KAAI,QAAQ,IAAI,aAAa,aAC3B,gBAAe;AAGjB,QAAO;;;;;;AAOT,eAAsB,gBAAiC;
|
|
1
|
+
{"version":3,"file":"config.server.mjs","names":[],"sources":["../../src/core/config.server.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { DEFAULT_CONFIG, type KryoConfig } from \"./config\";\n\nlet cachedConfig: KryoConfig | null = null;\n\n/**\n * Loads the Kryo configuration from kryo.config.ts or kryo.config.js in the current working directory.\n * SERVER ONLY.\n */\nexport async function getKryoConfig(): Promise<KryoConfig> {\n // Prevent this from ever running on the client even if imported\n if (typeof window !== \"undefined\") {\n throw new Error(\"getKryoConfig can only be called on the server.\");\n }\n\n // Use memory cache in production\n if (process.env.NODE_ENV === \"production\" && cachedConfig) {\n return cachedConfig;\n }\n\n const cwd = process.cwd();\n const configPathTS = path.join(cwd, \"kryo.config.ts\");\n const configPathJS = path.join(cwd, \"kryo.config.js\");\n const configPathMJS = path.join(cwd, \"kryo.config.mjs\");\n\n let loadedConfig: Partial<KryoConfig> = {};\n\n try {\n // Dynamic import jiti only on server to avoid bundling issues\n const { createJiti } = await import(\"jiti\");\n const jiti = createJiti(cwd, {\n fsCache: false,\n moduleCache: false,\n });\n\n if (fs.existsSync(configPathTS)) {\n const cacheBuster = `?t=${Date.now()}`;\n const imported: any = await jiti.import(\n `file://${configPathTS}${cacheBuster}`,\n { default: true },\n );\n loadedConfig = imported.default || imported;\n } else if (fs.existsSync(configPathMJS)) {\n const imported: any = await jiti.import(configPathMJS, { default: true });\n loadedConfig = imported.default || imported;\n } else if (fs.existsSync(configPathJS)) {\n const imported: any = await jiti.import(configPathJS, { default: true });\n loadedConfig = imported.default || imported;\n }\n } catch (error) {\n console.warn(\n \"[Kryo:Config] Could not load kryo.config.ts, using defaults.\",\n error,\n );\n }\n\n const finalConfig = { ...DEFAULT_CONFIG, ...loadedConfig };\n\n if (process.env.NODE_ENV === \"production\") {\n cachedConfig = finalConfig;\n }\n\n return finalConfig;\n}\n\n/**\n * Helper returning the absolute path to the modules directory.\n * SERVER ONLY.\n */\nexport async function getModulesDir(): Promise<string> {\n const config = await getKryoConfig();\n\n const dir = config.modulesDirectory || \"modules\";\n return path.isAbsolute(dir) ? dir : path.join(process.cwd(), dir);\n}\n"],"mappings":";;;;;AAIA,IAAI,eAAkC;;;;;AAMtC,eAAsB,gBAAqC;AAEzD,KAAI,OAAO,WAAW,YACpB,OAAM,IAAI,MAAM,kDAAkD;AAIpE,KAAI,QAAQ,IAAI,aAAa,gBAAgB,aAC3C,QAAO;CAGT,MAAM,MAAM,QAAQ,KAAK;CACzB,MAAM,eAAe,KAAK,KAAK,KAAK,iBAAiB;CACrD,MAAM,eAAe,KAAK,KAAK,KAAK,iBAAiB;CACrD,MAAM,gBAAgB,KAAK,KAAK,KAAK,kBAAkB;CAEvD,IAAI,eAAoC,EAAE;AAE1C,KAAI;EAEF,MAAM,EAAE,eAAe,MAAM,OAAO;EACpC,MAAM,OAAO,WAAW,KAAK;GAC3B,SAAS;GACT,aAAa;GACd,CAAC;AAEF,MAAI,GAAG,WAAW,aAAa,EAAE;GAC/B,MAAM,cAAc,MAAM,KAAK,KAAK;GACpC,MAAM,WAAgB,MAAM,KAAK,OAC/B,UAAU,eAAe,eACzB,EAAE,SAAS,MAAM,CAClB;AACD,kBAAe,SAAS,WAAW;aAC1B,GAAG,WAAW,cAAc,EAAE;GACvC,MAAM,WAAgB,MAAM,KAAK,OAAO,eAAe,EAAE,SAAS,MAAM,CAAC;AACzE,kBAAe,SAAS,WAAW;aAC1B,GAAG,WAAW,aAAa,EAAE;GACtC,MAAM,WAAgB,MAAM,KAAK,OAAO,cAAc,EAAE,SAAS,MAAM,CAAC;AACxE,kBAAe,SAAS,WAAW;;UAE9B,OAAO;AACd,UAAQ,KACN,gEACA,MACD;;CAGH,MAAM,cAAc;EAAE,GAAG;EAAgB,GAAG;EAAc;AAE1D,KAAI,QAAQ,IAAI,aAAa,aAC3B,gBAAe;AAGjB,QAAO;;;;;;AAOT,eAAsB,gBAAiC;CAGrD,MAAM,OAFS,MAAM,eAAe,EAEjB,oBAAoB;AACvC,QAAO,KAAK,WAAW,IAAI,GAAG,MAAM,KAAK,KAAK,QAAQ,KAAK,EAAE,IAAI"}
|
package/dist/core/event-bus.cjs
CHANGED
|
@@ -41,8 +41,8 @@ var EventBus = class {
|
|
|
41
41
|
}
|
|
42
42
|
};
|
|
43
43
|
const globalForEventBus = globalThis;
|
|
44
|
-
const eventBus = globalForEventBus.
|
|
45
|
-
globalForEventBus.
|
|
44
|
+
const eventBus = globalForEventBus.__KRYO_EVENT_BUS__ ?? new EventBus();
|
|
45
|
+
globalForEventBus.__KRYO_EVENT_BUS__ = eventBus;
|
|
46
46
|
|
|
47
47
|
//#endregion
|
|
48
48
|
exports.eventBus = eventBus;
|
package/dist/core/event-bus.mjs
CHANGED
|
@@ -40,8 +40,8 @@ var EventBus = class {
|
|
|
40
40
|
}
|
|
41
41
|
};
|
|
42
42
|
const globalForEventBus = globalThis;
|
|
43
|
-
const eventBus = globalForEventBus.
|
|
44
|
-
globalForEventBus.
|
|
43
|
+
const eventBus = globalForEventBus.__KRYO_EVENT_BUS__ ?? new EventBus();
|
|
44
|
+
globalForEventBus.__KRYO_EVENT_BUS__ = eventBus;
|
|
45
45
|
|
|
46
46
|
//#endregion
|
|
47
47
|
export { eventBus };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-bus.mjs","names":[],"sources":["../../src/core/event-bus.ts"],"sourcesContent":["import type { EventHandler, SystemEvent } from \"./types\";\n\n/**\n * EventBus (Pub/Sub) - Global Singleton Pattern.\n */\nclass EventBus {\n private handlers: Map<string, Map<string, EventHandler>> = new Map();\n\n public subscribe<T>(\n eventType: string,\n subscriberId: string,\n handler: EventHandler<T>,\n ): void {\n if (!this.handlers.has(eventType)) {\n this.handlers.set(eventType, new Map());\n }\n const eventHandlers = this.handlers.get(eventType);\n eventHandlers?.set(subscriberId, handler);\n console.log(\n `[Event Bus] Subscriber \"${subscriberId}\" added for \"${eventType}\"`,\n );\n }\n\n public unsubscribe(eventType: string, subscriberId: string): void {\n this.handlers.get(eventType)?.delete(subscriberId);\n console.log(\n `[Event Bus] Subscriber \"${subscriberId}\" removed from \"${eventType}\"`,\n );\n }\n\n public clearAll(): void {\n console.log(\"[Event Bus] Resetting all listeners...\");\n this.handlers.clear();\n }\n\n public async publish<T>(\n eventType: string,\n payload: T,\n source: string = \"system\",\n ): Promise<void> {\n const eventHandlers = this.handlers.get(eventType);\n if (!eventHandlers) return;\n\n const handlers = Array.from(eventHandlers.values());\n\n console.log(\n `[Event Bus] Publishing \"${eventType}\" to ${handlers.length} subscribers`,\n );\n\n const event: SystemEvent<T> = {\n type: eventType,\n payload,\n timestamp: Date.now(),\n source,\n };\n\n await Promise.all(\n handlers.map(async (handler) => {\n try {\n await handler(event);\n } catch (error) {\n console.error(`[Event Bus] Handler Error for ${eventType}:`, error);\n }\n }),\n );\n }\n}\n\n// Ensure global singleton\nconst globalForEventBus = globalThis as unknown as {\n
|
|
1
|
+
{"version":3,"file":"event-bus.mjs","names":[],"sources":["../../src/core/event-bus.ts"],"sourcesContent":["import type { EventHandler, SystemEvent } from \"./types\";\n\n/**\n * EventBus (Pub/Sub) - Global Singleton Pattern.\n */\nclass EventBus {\n private handlers: Map<string, Map<string, EventHandler>> = new Map();\n\n public subscribe<T>(\n eventType: string,\n subscriberId: string,\n handler: EventHandler<T>,\n ): void {\n if (!this.handlers.has(eventType)) {\n this.handlers.set(eventType, new Map());\n }\n const eventHandlers = this.handlers.get(eventType);\n eventHandlers?.set(subscriberId, handler);\n console.log(\n `[Event Bus] Subscriber \"${subscriberId}\" added for \"${eventType}\"`,\n );\n }\n\n public unsubscribe(eventType: string, subscriberId: string): void {\n this.handlers.get(eventType)?.delete(subscriberId);\n console.log(\n `[Event Bus] Subscriber \"${subscriberId}\" removed from \"${eventType}\"`,\n );\n }\n\n public clearAll(): void {\n console.log(\"[Event Bus] Resetting all listeners...\");\n this.handlers.clear();\n }\n\n public async publish<T>(\n eventType: string,\n payload: T,\n source: string = \"system\",\n ): Promise<void> {\n const eventHandlers = this.handlers.get(eventType);\n if (!eventHandlers) return;\n\n const handlers = Array.from(eventHandlers.values());\n\n console.log(\n `[Event Bus] Publishing \"${eventType}\" to ${handlers.length} subscribers`,\n );\n\n const event: SystemEvent<T> = {\n type: eventType,\n payload,\n timestamp: Date.now(),\n source,\n };\n\n await Promise.all(\n handlers.map(async (handler) => {\n try {\n await handler(event);\n } catch (error) {\n console.error(`[Event Bus] Handler Error for ${eventType}:`, error);\n }\n }),\n );\n }\n}\n\n// Ensure global singleton\nconst globalForEventBus = globalThis as unknown as {\n __KRYO_EVENT_BUS__: EventBus | undefined;\n};\n\nexport const eventBus = globalForEventBus.__KRYO_EVENT_BUS__ ?? new EventBus();\n\nglobalForEventBus.__KRYO_EVENT_BUS__ = eventBus;\n"],"mappings":";;;;AAKA,IAAM,WAAN,MAAe;;kCAC8C,IAAI,KAAK;;CAEpE,AAAO,UACL,WACA,cACA,SACM;AACN,MAAI,CAAC,KAAK,SAAS,IAAI,UAAU,CAC/B,MAAK,SAAS,IAAI,2BAAW,IAAI,KAAK,CAAC;AAGzC,EADsB,KAAK,SAAS,IAAI,UAAU,EACnC,IAAI,cAAc,QAAQ;AACzC,UAAQ,IACN,2BAA2B,aAAa,eAAe,UAAU,GAClE;;CAGH,AAAO,YAAY,WAAmB,cAA4B;AAChE,OAAK,SAAS,IAAI,UAAU,EAAE,OAAO,aAAa;AAClD,UAAQ,IACN,2BAA2B,aAAa,kBAAkB,UAAU,GACrE;;CAGH,AAAO,WAAiB;AACtB,UAAQ,IAAI,yCAAyC;AACrD,OAAK,SAAS,OAAO;;CAGvB,MAAa,QACX,WACA,SACA,SAAiB,UACF;EACf,MAAM,gBAAgB,KAAK,SAAS,IAAI,UAAU;AAClD,MAAI,CAAC,cAAe;EAEpB,MAAM,WAAW,MAAM,KAAK,cAAc,QAAQ,CAAC;AAEnD,UAAQ,IACN,2BAA2B,UAAU,OAAO,SAAS,OAAO,cAC7D;EAED,MAAM,QAAwB;GAC5B,MAAM;GACN;GACA,WAAW,KAAK,KAAK;GACrB;GACD;AAED,QAAM,QAAQ,IACZ,SAAS,IAAI,OAAO,YAAY;AAC9B,OAAI;AACF,UAAM,QAAQ,MAAM;YACb,OAAO;AACd,YAAQ,MAAM,iCAAiC,UAAU,IAAI,MAAM;;IAErE,CACH;;;AAKL,MAAM,oBAAoB;AAI1B,MAAa,WAAW,kBAAkB,sBAAsB,IAAI,UAAU;AAE9E,kBAAkB,qBAAqB"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const require_local = require('./providers/local.cjs');
|
|
2
|
+
const require_service = require('./service.cjs');
|
|
3
|
+
|
|
4
|
+
//#region src/core/filesystem/index.ts
|
|
5
|
+
if (typeof window === "undefined") {
|
|
6
|
+
const local = new require_local.LocalFileProvider();
|
|
7
|
+
require_service.filesystemService.registerProvider(local);
|
|
8
|
+
require_service.filesystemService.setDefaultProvider(local.id);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
//#endregion
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { LocalFileProvider } from "./providers/local.mjs";
|
|
2
|
+
import { filesystemService } from "./service.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/core/filesystem/index.ts
|
|
5
|
+
if (typeof window === "undefined") {
|
|
6
|
+
const local = new LocalFileProvider();
|
|
7
|
+
filesystemService.registerProvider(local);
|
|
8
|
+
filesystemService.setDefaultProvider(local.id);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
//#endregion
|
|
12
|
+
export { };
|
|
13
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/core/filesystem/index.ts"],"sourcesContent":["import { LocalFileProvider } from \"./providers/local\";\nimport { filesystemService } from \"./service\";\n\nexport * from \"./types\";\nexport { filesystemService };\n\n// Auto-register local provider\nif (typeof window === \"undefined\") {\n const local = new LocalFileProvider();\n\n filesystemService.registerProvider(local);\n filesystemService.setDefaultProvider(local.id);\n}\n"],"mappings":";;;;AAOA,IAAI,OAAO,WAAW,aAAa;CACjC,MAAM,QAAQ,IAAI,mBAAmB;AAErC,mBAAkB,iBAAiB,MAAM;AACzC,mBAAkB,mBAAmB,MAAM,GAAG"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
|
|
2
|
+
let node_fs = require("node:fs");
|
|
3
|
+
node_fs = require_runtime.__toESM(node_fs);
|
|
4
|
+
let node_path = require("node:path");
|
|
5
|
+
node_path = require_runtime.__toESM(node_path);
|
|
6
|
+
|
|
7
|
+
//#region src/core/filesystem/providers/local.ts
|
|
8
|
+
var LocalFileProvider = class {
|
|
9
|
+
constructor() {
|
|
10
|
+
this.id = "local";
|
|
11
|
+
this.name = "Local Filesystem";
|
|
12
|
+
}
|
|
13
|
+
generateUniqueImageName(name) {
|
|
14
|
+
const cleanName = name.replace(/\s+/g, "-").toLowerCase();
|
|
15
|
+
const suffix = Math.floor(Math.random() * Date.now()).toString(36);
|
|
16
|
+
const index = cleanName.lastIndexOf(".");
|
|
17
|
+
return index < 0 ? `${cleanName}-${suffix}` : `${cleanName.slice(0, index)}-${suffix}${cleanName.slice(index)}`;
|
|
18
|
+
}
|
|
19
|
+
async upload(file) {
|
|
20
|
+
try {
|
|
21
|
+
const storageFolder = process.env.FILE_STORAGE_FOLDER ?? "public/storage";
|
|
22
|
+
if (!node_fs.default.existsSync(storageFolder)) node_fs.default.mkdirSync(storageFolder, { recursive: true });
|
|
23
|
+
const name = this.generateUniqueImageName(file.name);
|
|
24
|
+
const filePath = node_path.default.join(storageFolder, name);
|
|
25
|
+
const buffer = await file.arrayBuffer();
|
|
26
|
+
node_fs.default.writeFileSync(filePath, Buffer.from(buffer));
|
|
27
|
+
return {
|
|
28
|
+
name,
|
|
29
|
+
url: `${storageFolder}/${name}`.replace("public", ""),
|
|
30
|
+
type: file.type,
|
|
31
|
+
size: file.size,
|
|
32
|
+
service: "local",
|
|
33
|
+
serviceId: filePath
|
|
34
|
+
};
|
|
35
|
+
} catch (error) {
|
|
36
|
+
console.error("Error uploading file", error);
|
|
37
|
+
return { error: "Error uploading file" };
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
//#endregion
|
|
43
|
+
exports.LocalFileProvider = LocalFileProvider;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
//#region src/core/filesystem/providers/local.ts
|
|
5
|
+
var LocalFileProvider = class {
|
|
6
|
+
constructor() {
|
|
7
|
+
this.id = "local";
|
|
8
|
+
this.name = "Local Filesystem";
|
|
9
|
+
}
|
|
10
|
+
generateUniqueImageName(name) {
|
|
11
|
+
const cleanName = name.replace(/\s+/g, "-").toLowerCase();
|
|
12
|
+
const suffix = Math.floor(Math.random() * Date.now()).toString(36);
|
|
13
|
+
const index = cleanName.lastIndexOf(".");
|
|
14
|
+
return index < 0 ? `${cleanName}-${suffix}` : `${cleanName.slice(0, index)}-${suffix}${cleanName.slice(index)}`;
|
|
15
|
+
}
|
|
16
|
+
async upload(file) {
|
|
17
|
+
try {
|
|
18
|
+
const storageFolder = process.env.FILE_STORAGE_FOLDER ?? "public/storage";
|
|
19
|
+
if (!fs.existsSync(storageFolder)) fs.mkdirSync(storageFolder, { recursive: true });
|
|
20
|
+
const name = this.generateUniqueImageName(file.name);
|
|
21
|
+
const filePath = path.join(storageFolder, name);
|
|
22
|
+
const buffer = await file.arrayBuffer();
|
|
23
|
+
fs.writeFileSync(filePath, Buffer.from(buffer));
|
|
24
|
+
return {
|
|
25
|
+
name,
|
|
26
|
+
url: `${storageFolder}/${name}`.replace("public", ""),
|
|
27
|
+
type: file.type,
|
|
28
|
+
size: file.size,
|
|
29
|
+
service: "local",
|
|
30
|
+
serviceId: filePath
|
|
31
|
+
};
|
|
32
|
+
} catch (error) {
|
|
33
|
+
console.error("Error uploading file", error);
|
|
34
|
+
return { error: "Error uploading file" };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
//#endregion
|
|
40
|
+
export { LocalFileProvider };
|
|
41
|
+
//# sourceMappingURL=local.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"local.mjs","names":[],"sources":["../../../../src/core/filesystem/providers/local.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { IStorageProvider, StorageResult } from \"../types\";\n\nexport class LocalFileProvider implements IStorageProvider {\n public id = \"local\";\n public name = \"Local Filesystem\";\n\n private generateUniqueImageName(name: string) {\n const cleanName = name.replace(/\\s+/g, \"-\").toLowerCase();\n const suffix = Math.floor(Math.random() * Date.now()).toString(36);\n const index = cleanName.lastIndexOf(\".\");\n\n return index < 0\n ? `${cleanName}-${suffix}`\n : `${cleanName.slice(0, index)}-${suffix}${cleanName.slice(index)}`;\n }\n\n public async upload(file: File): Promise<StorageResult> {\n try {\n const storageFolder = process.env.FILE_STORAGE_FOLDER ?? \"public/storage\";\n\n if (!fs.existsSync(storageFolder)) {\n fs.mkdirSync(storageFolder, { recursive: true });\n }\n\n const name = this.generateUniqueImageName(file.name);\n const filePath = path.join(storageFolder, name);\n const buffer = await file.arrayBuffer();\n fs.writeFileSync(filePath, Buffer.from(buffer));\n\n const url = `${storageFolder}/${name}`.replace(\"public\", \"\");\n\n return {\n name: name,\n url,\n type: file.type,\n size: file.size,\n service: \"local\",\n serviceId: filePath,\n };\n } catch (error) {\n console.error(\"Error uploading file\", error);\n return { error: \"Error uploading file\" };\n }\n }\n}\n"],"mappings":";;;;AAIA,IAAa,oBAAb,MAA2D;;YAC7C;cACE;;CAEd,AAAQ,wBAAwB,MAAc;EAC5C,MAAM,YAAY,KAAK,QAAQ,QAAQ,IAAI,CAAC,aAAa;EACzD,MAAM,SAAS,KAAK,MAAM,KAAK,QAAQ,GAAG,KAAK,KAAK,CAAC,CAAC,SAAS,GAAG;EAClE,MAAM,QAAQ,UAAU,YAAY,IAAI;AAExC,SAAO,QAAQ,IACX,GAAG,UAAU,GAAG,WAChB,GAAG,UAAU,MAAM,GAAG,MAAM,CAAC,GAAG,SAAS,UAAU,MAAM,MAAM;;CAGrE,MAAa,OAAO,MAAoC;AACtD,MAAI;GACF,MAAM,gBAAgB,QAAQ,IAAI,uBAAuB;AAEzD,OAAI,CAAC,GAAG,WAAW,cAAc,CAC/B,IAAG,UAAU,eAAe,EAAE,WAAW,MAAM,CAAC;GAGlD,MAAM,OAAO,KAAK,wBAAwB,KAAK,KAAK;GACpD,MAAM,WAAW,KAAK,KAAK,eAAe,KAAK;GAC/C,MAAM,SAAS,MAAM,KAAK,aAAa;AACvC,MAAG,cAAc,UAAU,OAAO,KAAK,OAAO,CAAC;AAI/C,UAAO;IACC;IACN,KAJU,GAAG,cAAc,GAAG,OAAO,QAAQ,UAAU,GAAG;IAK1D,MAAM,KAAK;IACX,MAAM,KAAK;IACX,SAAS;IACT,WAAW;IACZ;WACM,OAAO;AACd,WAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAO,EAAE,OAAO,wBAAwB"}
|
|
@@ -36,8 +36,8 @@ var FilesystemService = class {
|
|
|
36
36
|
}
|
|
37
37
|
};
|
|
38
38
|
const globalForFilesystem = globalThis;
|
|
39
|
-
const filesystemService = globalForFilesystem.
|
|
40
|
-
globalForFilesystem.
|
|
39
|
+
const filesystemService = globalForFilesystem.__KRYO_FILESYSTEM_SERVICE__ ?? new FilesystemService();
|
|
40
|
+
globalForFilesystem.__KRYO_FILESYSTEM_SERVICE__ = filesystemService;
|
|
41
41
|
|
|
42
42
|
//#endregion
|
|
43
43
|
exports.filesystemService = filesystemService;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.d.cts","names":[],"sources":["../../../src/core/filesystem/service.ts"],"mappings":";;;cAEM,iBAAA;EAAA,QACI,SAAA;EAAA,QACA,iBAAA;EAED,gBAAA,CAAiB,QAAA,EAAU,gBAAA;EAQ3B,kBAAA,CAAmB,EAAA;EAUnB,kBAAA,CAAmB,EAAA;EAOb,MAAA,CAAO,IAAA,EAAM,IAAA,EAAM,UAAA,YAAsB,OAAA,CAAQ,aAAA;
|
|
1
|
+
{"version":3,"file":"service.d.cts","names":[],"sources":["../../../src/core/filesystem/service.ts"],"mappings":";;;cAEM,iBAAA;EAAA,QACI,SAAA;EAAA,QACA,iBAAA;EAED,gBAAA,CAAiB,QAAA,EAAU,gBAAA;EAQ3B,kBAAA,CAAmB,EAAA;EAUnB,kBAAA,CAAmB,EAAA;EAOb,MAAA,CAAO,IAAA,EAAM,IAAA,EAAM,UAAA,YAAsB,OAAA,CAAQ,aAAA;EAiBvD,YAAA,CAAA;;;;;cAaI,iBAAA,EAAiB,iBAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.d.mts","names":[],"sources":["../../../src/core/filesystem/service.ts"],"mappings":";;;cAEM,iBAAA;EAAA,QACI,SAAA;EAAA,QACA,iBAAA;EAED,gBAAA,CAAiB,QAAA,EAAU,gBAAA;EAQ3B,kBAAA,CAAmB,EAAA;EAUnB,kBAAA,CAAmB,EAAA;EAOb,MAAA,CAAO,IAAA,EAAM,IAAA,EAAM,UAAA,YAAsB,OAAA,CAAQ,aAAA;
|
|
1
|
+
{"version":3,"file":"service.d.mts","names":[],"sources":["../../../src/core/filesystem/service.ts"],"mappings":";;;cAEM,iBAAA;EAAA,QACI,SAAA;EAAA,QACA,iBAAA;EAED,gBAAA,CAAiB,QAAA,EAAU,gBAAA;EAQ3B,kBAAA,CAAmB,EAAA;EAUnB,kBAAA,CAAmB,EAAA;EAOb,MAAA,CAAO,IAAA,EAAM,IAAA,EAAM,UAAA,YAAsB,OAAA,CAAQ,aAAA;EAiBvD,YAAA,CAAA;;;;;cAaI,iBAAA,EAAiB,iBAAA"}
|
|
@@ -35,8 +35,8 @@ var FilesystemService = class {
|
|
|
35
35
|
}
|
|
36
36
|
};
|
|
37
37
|
const globalForFilesystem = globalThis;
|
|
38
|
-
const filesystemService = globalForFilesystem.
|
|
39
|
-
globalForFilesystem.
|
|
38
|
+
const filesystemService = globalForFilesystem.__KRYO_FILESYSTEM_SERVICE__ ?? new FilesystemService();
|
|
39
|
+
globalForFilesystem.__KRYO_FILESYSTEM_SERVICE__ = filesystemService;
|
|
40
40
|
|
|
41
41
|
//#endregion
|
|
42
42
|
export { filesystemService };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.mjs","names":[],"sources":["../../../src/core/filesystem/service.ts"],"sourcesContent":["import type { IStorageProvider, StorageResult } from \"./types\";\n\nclass FilesystemService {\n private providers: Map<string, IStorageProvider> = new Map();\n private defaultProviderId: string | null = null;\n\n public registerProvider(provider: IStorageProvider) {\n this.providers.set(provider.id, provider);\n if (!this.defaultProviderId || this.defaultProviderId === \"local\") {\n this.defaultProviderId = provider.id;\n }\n console.log(`[Filesystem] Provider registered: ${provider.id}`);\n }\n\n public unregisterProvider(id: string) {\n this.providers.delete(id);\n if (this.defaultProviderId === id) {\n this.defaultProviderId = this.providers.has(\"local\")\n ? \"local\"\n : Array.from(this.providers.keys())[0] || null;\n }\n console.log(`[Filesystem] Provider unregistered: ${id}`);\n }\n\n public setDefaultProvider(id: string) {\n if (this.providers.has(id)) {\n this.defaultProviderId = id;\n console.log(`[Filesystem] Default provider set to: ${id}`);\n }\n }\n\n public async upload(file: File, providerId?: string): Promise<StorageResult> {\n let id = providerId || this.defaultProviderId;\n\n // Fallback logic\n if (!id || !this.providers.has(id)) {\n id = \"local\";\n }\n\n const provider = this.providers.get(id);\n if (!provider) {\n return { error: \"No storage provider available (local fallback failed)\" };\n }\n\n return await provider.upload(file);\n }\n\n public getProviders() {\n return Array.from(this.providers.values()).map((p) => ({\n id: p.id,\n name: p.name,\n }));\n }\n}\n\n// Global Singleton Pattern\nconst globalForFilesystem = globalThis as unknown as {\n
|
|
1
|
+
{"version":3,"file":"service.mjs","names":[],"sources":["../../../src/core/filesystem/service.ts"],"sourcesContent":["import type { IStorageProvider, StorageResult } from \"./types\";\n\nclass FilesystemService {\n private providers: Map<string, IStorageProvider> = new Map();\n private defaultProviderId: string | null = null;\n\n public registerProvider(provider: IStorageProvider) {\n this.providers.set(provider.id, provider);\n if (!this.defaultProviderId || this.defaultProviderId === \"local\") {\n this.defaultProviderId = provider.id;\n }\n console.log(`[Filesystem] Provider registered: ${provider.id}`);\n }\n\n public unregisterProvider(id: string) {\n this.providers.delete(id);\n if (this.defaultProviderId === id) {\n this.defaultProviderId = this.providers.has(\"local\")\n ? \"local\"\n : Array.from(this.providers.keys())[0] || null;\n }\n console.log(`[Filesystem] Provider unregistered: ${id}`);\n }\n\n public setDefaultProvider(id: string) {\n if (this.providers.has(id)) {\n this.defaultProviderId = id;\n console.log(`[Filesystem] Default provider set to: ${id}`);\n }\n }\n\n public async upload(file: File, providerId?: string): Promise<StorageResult> {\n let id = providerId || this.defaultProviderId;\n\n // Fallback logic\n if (!id || !this.providers.has(id)) {\n id = \"local\";\n }\n\n const provider = this.providers.get(id);\n\n if (!provider) {\n return { error: \"No storage provider available (local fallback failed)\" };\n }\n\n return await provider.upload(file);\n }\n\n public getProviders() {\n return Array.from(this.providers.values()).map((p) => ({\n id: p.id,\n name: p.name,\n }));\n }\n}\n\n// Global Singleton Pattern\nconst globalForFilesystem = globalThis as unknown as {\n __KRYO_FILESYSTEM_SERVICE__: FilesystemService | undefined;\n};\n\nexport const filesystemService =\n globalForFilesystem.__KRYO_FILESYSTEM_SERVICE__ ?? new FilesystemService();\n\nglobalForFilesystem.__KRYO_FILESYSTEM_SERVICE__ = filesystemService;\n"],"mappings":";AAEA,IAAM,oBAAN,MAAwB;;mCAC6B,IAAI,KAAK;2BACjB;;CAE3C,AAAO,iBAAiB,UAA4B;AAClD,OAAK,UAAU,IAAI,SAAS,IAAI,SAAS;AACzC,MAAI,CAAC,KAAK,qBAAqB,KAAK,sBAAsB,QACxD,MAAK,oBAAoB,SAAS;AAEpC,UAAQ,IAAI,qCAAqC,SAAS,KAAK;;CAGjE,AAAO,mBAAmB,IAAY;AACpC,OAAK,UAAU,OAAO,GAAG;AACzB,MAAI,KAAK,sBAAsB,GAC7B,MAAK,oBAAoB,KAAK,UAAU,IAAI,QAAQ,GAChD,UACA,MAAM,KAAK,KAAK,UAAU,MAAM,CAAC,CAAC,MAAM;AAE9C,UAAQ,IAAI,uCAAuC,KAAK;;CAG1D,AAAO,mBAAmB,IAAY;AACpC,MAAI,KAAK,UAAU,IAAI,GAAG,EAAE;AAC1B,QAAK,oBAAoB;AACzB,WAAQ,IAAI,yCAAyC,KAAK;;;CAI9D,MAAa,OAAO,MAAY,YAA6C;EAC3E,IAAI,KAAK,cAAc,KAAK;AAG5B,MAAI,CAAC,MAAM,CAAC,KAAK,UAAU,IAAI,GAAG,CAChC,MAAK;EAGP,MAAM,WAAW,KAAK,UAAU,IAAI,GAAG;AAEvC,MAAI,CAAC,SACH,QAAO,EAAE,OAAO,yDAAyD;AAG3E,SAAO,MAAM,SAAS,OAAO,KAAK;;CAGpC,AAAO,eAAe;AACpB,SAAO,MAAM,KAAK,KAAK,UAAU,QAAQ,CAAC,CAAC,KAAK,OAAO;GACrD,IAAI,EAAE;GACN,MAAM,EAAE;GACT,EAAE;;;AAKP,MAAM,sBAAsB;AAI5B,MAAa,oBACX,oBAAoB,+BAA+B,IAAI,mBAAmB;AAE5E,oBAAoB,8BAA8B"}
|
|
@@ -19,10 +19,10 @@ declare function createNotification(data: CreateNotificationPayload): Promise<{
|
|
|
19
19
|
createdAt: Date;
|
|
20
20
|
updatedAt: Date | null;
|
|
21
21
|
userId: string;
|
|
22
|
+
type: string | null;
|
|
22
23
|
title: string;
|
|
23
24
|
content: string | null;
|
|
24
25
|
target: string | null;
|
|
25
|
-
type: string | null;
|
|
26
26
|
isRead: boolean;
|
|
27
27
|
resourceId: string | null;
|
|
28
28
|
resourceType: string | null;
|
|
@@ -19,10 +19,10 @@ declare function createNotification(data: CreateNotificationPayload): Promise<{
|
|
|
19
19
|
createdAt: Date;
|
|
20
20
|
updatedAt: Date | null;
|
|
21
21
|
userId: string;
|
|
22
|
+
type: string | null;
|
|
22
23
|
title: string;
|
|
23
24
|
content: string | null;
|
|
24
25
|
target: string | null;
|
|
25
|
-
type: string | null;
|
|
26
26
|
isRead: boolean;
|
|
27
27
|
resourceId: string | null;
|
|
28
28
|
resourceType: string | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"actions.mjs","names":[],"sources":["../../../src/core/notifications/actions.ts"],"sourcesContent":["\"use server\";\n\nimport { desc, eq } from \"drizzle-orm\";\nimport {
|
|
1
|
+
{"version":3,"file":"actions.mjs","names":[],"sources":["../../../src/core/notifications/actions.ts"],"sourcesContent":["\"use server\";\n\nimport { desc, eq } from \"drizzle-orm\";\nimport { db } from \"../../server/database/inject\";\nimport { notificationTable } from \"../../server/database/schema\";\nimport { getCurrentSession } from \"../auth/session\";\nimport type { CreateNotificationPayload } from \"./types\";\n\nexport async function getUserNotifications() {\n const { user } = await getCurrentSession();\n if (!user) return null;\n\n return await db\n .select()\n .from(notificationTable)\n .where(eq(notificationTable.userId, user.id))\n .orderBy(desc(notificationTable.createdAt));\n}\n\nexport async function createNotification(data: CreateNotificationPayload) {\n const [notification] = await db\n .insert(notificationTable)\n .values({\n ...data,\n isRead: false,\n })\n .returning();\n\n return notification;\n}\n\nexport async function markNotificationAsRead(id: string) {\n const [updated] = await db\n .update(notificationTable)\n .set({ isRead: true })\n .where(eq(notificationTable.id, id))\n .returning();\n\n return updated;\n}\n\nexport async function markAllNotificationsAsRead() {\n const { user } = await getCurrentSession();\n if (!user) return null;\n\n return await db\n .update(notificationTable)\n .set({ isRead: true })\n .where(eq(notificationTable.userId, user.id))\n .returning();\n}\n"],"mappings":";;;;;;;;AAQA,eAAsB,uBAAuB;CAC3C,MAAM,EAAE,SAAS,MAAM,mBAAmB;AAC1C,KAAI,CAAC,KAAM,QAAO;AAElB,QAAO,MAAM,GACV,QAAQ,CACR,KAAK,kBAAkB,CACvB,MAAM,GAAG,kBAAkB,QAAQ,KAAK,GAAG,CAAC,CAC5C,QAAQ,KAAK,kBAAkB,UAAU,CAAC;;AAG/C,eAAsB,mBAAmB,MAAiC;CACxE,MAAM,CAAC,gBAAgB,MAAM,GAC1B,OAAO,kBAAkB,CACzB,OAAO;EACN,GAAG;EACH,QAAQ;EACT,CAAC,CACD,WAAW;AAEd,QAAO;;AAGT,eAAsB,uBAAuB,IAAY;CACvD,MAAM,CAAC,WAAW,MAAM,GACrB,OAAO,kBAAkB,CACzB,IAAI,EAAE,QAAQ,MAAM,CAAC,CACrB,MAAM,GAAG,kBAAkB,IAAI,GAAG,CAAC,CACnC,WAAW;AAEd,QAAO;;AAGT,eAAsB,6BAA6B;CACjD,MAAM,EAAE,SAAS,MAAM,mBAAmB;AAC1C,KAAI,CAAC,KAAM,QAAO;AAElB,QAAO,MAAM,GACV,OAAO,kBAAkB,CACzB,IAAI,EAAE,QAAQ,MAAM,CAAC,CACrB,MAAM,GAAG,kBAAkB,QAAQ,KAAK,GAAG,CAAC,CAC5C,WAAW"}
|
|
@@ -23,8 +23,8 @@ var NotificationService = class {
|
|
|
23
23
|
}
|
|
24
24
|
};
|
|
25
25
|
const globalForNotifications = globalThis;
|
|
26
|
-
const notificationService = globalForNotifications.
|
|
27
|
-
globalForNotifications.
|
|
26
|
+
const notificationService = globalForNotifications.__KRYO_NOTIFICATION_SERVICE__ ?? new NotificationService();
|
|
27
|
+
globalForNotifications.__KRYO_NOTIFICATION_SERVICE__ = notificationService;
|
|
28
28
|
|
|
29
29
|
//#endregion
|
|
30
30
|
exports.notificationService = notificationService;
|
|
@@ -23,8 +23,8 @@ var NotificationService = class {
|
|
|
23
23
|
}
|
|
24
24
|
};
|
|
25
25
|
const globalForNotifications = globalThis;
|
|
26
|
-
const notificationService = globalForNotifications.
|
|
27
|
-
globalForNotifications.
|
|
26
|
+
const notificationService = globalForNotifications.__KRYO_NOTIFICATION_SERVICE__ ?? new NotificationService();
|
|
27
|
+
globalForNotifications.__KRYO_NOTIFICATION_SERVICE__ = notificationService;
|
|
28
28
|
|
|
29
29
|
//#endregion
|
|
30
30
|
export { notificationService };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.mjs","names":[],"sources":["../../../src/core/notifications/service.ts"],"sourcesContent":["import { eventBus } from \"../event-bus\";\nimport { createNotification } from \"./actions\";\nimport type { CreateNotificationPayload } from \"./types\";\n\nclass NotificationService {\n private initialized = false;\n\n public init() {\n if (this.initialized) {\n // console.log(\"[Notification Service] Already initialized.\");\n return;\n }\n\n console.log(\"[Notification Service] Subscribing to notification:send...\");\n\n eventBus.subscribe(\n \"notification:send\",\n \"notification-service\",\n async (event) => {\n console.log(\n \"[Notification Service] Received notification:send event\",\n event.payload,\n );\n try {\n // const { createNotification } = await import(\"./actions\");\n const result = await createNotification(\n event.payload as CreateNotificationPayload,\n );\n console.log(\n \"[Notification Service] Notification created successfully:\",\n result.id,\n );\n } catch (error) {\n console.error(\n \"[Notification Service] Failed to process notification:send\",\n error,\n );\n }\n },\n );\n\n this.initialized = true;\n console.log(\"[NotificationService] Initialized and listening for events.\");\n }\n}\n\n// Global Singleton Pattern\nconst globalForNotifications = globalThis as unknown as {\n
|
|
1
|
+
{"version":3,"file":"service.mjs","names":[],"sources":["../../../src/core/notifications/service.ts"],"sourcesContent":["import { eventBus } from \"../event-bus\";\nimport { createNotification } from \"./actions\";\nimport type { CreateNotificationPayload } from \"./types\";\n\nclass NotificationService {\n private initialized = false;\n\n public init() {\n if (this.initialized) {\n // console.log(\"[Notification Service] Already initialized.\");\n return;\n }\n\n console.log(\"[Notification Service] Subscribing to notification:send...\");\n\n eventBus.subscribe(\n \"notification:send\",\n \"notification-service\",\n async (event) => {\n console.log(\n \"[Notification Service] Received notification:send event\",\n event.payload,\n );\n try {\n // const { createNotification } = await import(\"./actions\");\n const result = await createNotification(\n event.payload as CreateNotificationPayload,\n );\n console.log(\n \"[Notification Service] Notification created successfully:\",\n result.id,\n );\n } catch (error) {\n console.error(\n \"[Notification Service] Failed to process notification:send\",\n error,\n );\n }\n },\n );\n\n this.initialized = true;\n console.log(\"[NotificationService] Initialized and listening for events.\");\n }\n}\n\n// Global Singleton Pattern\nconst globalForNotifications = globalThis as unknown as {\n __KRYO_NOTIFICATION_SERVICE__: NotificationService | undefined;\n};\n\nexport const notificationService =\n globalForNotifications.__KRYO_NOTIFICATION_SERVICE__ ??\n new NotificationService();\n\nglobalForNotifications.__KRYO_NOTIFICATION_SERVICE__ = notificationService;\n"],"mappings":";;;;AAIA,IAAM,sBAAN,MAA0B;;qBACF;;CAEtB,AAAO,OAAO;AACZ,MAAI,KAAK,YAEP;AAGF,UAAQ,IAAI,6DAA6D;AAEzE,WAAS,UACP,qBACA,wBACA,OAAO,UAAU;AACf,WAAQ,IACN,2DACA,MAAM,QACP;AACD,OAAI;IAEF,MAAM,SAAS,MAAM,mBACnB,MAAM,QACP;AACD,YAAQ,IACN,6DACA,OAAO,GACR;YACM,OAAO;AACd,YAAQ,MACN,8DACA,MACD;;IAGN;AAED,OAAK,cAAc;AACnB,UAAQ,IAAI,8DAA8D;;;AAK9E,MAAM,yBAAyB;AAI/B,MAAa,sBACX,uBAAuB,iCACvB,IAAI,qBAAqB;AAE3B,uBAAuB,gCAAgC"}
|
|
@@ -8,7 +8,7 @@ let drizzle_orm = require("drizzle-orm");
|
|
|
8
8
|
* Validates the email format and length.
|
|
9
9
|
*/
|
|
10
10
|
function verifyEmailInput(email) {
|
|
11
|
-
return /^.+@.+\..+$/.test(email) && email.length < 256;
|
|
11
|
+
return /^.+@.+\..+$/.test(email) && email.length < 256 && email.length > 0;
|
|
12
12
|
}
|
|
13
13
|
/**
|
|
14
14
|
* Checks if an email address is already in use.
|
|
@@ -7,7 +7,7 @@ import { count, eq } from "drizzle-orm";
|
|
|
7
7
|
* Validates the email format and length.
|
|
8
8
|
*/
|
|
9
9
|
function verifyEmailInput(email) {
|
|
10
|
-
return /^.+@.+\..+$/.test(email) && email.length < 256;
|
|
10
|
+
return /^.+@.+\..+$/.test(email) && email.length < 256 && email.length > 0;
|
|
11
11
|
}
|
|
12
12
|
/**
|
|
13
13
|
* Checks if an email address is already in use.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"email.mjs","names":[],"sources":["../../../src/server/auth/email.ts"],"sourcesContent":["import { count, eq } from \"drizzle-orm\";\nimport { db } from \"../database/inject\";\nimport { userTable } from \"../database/schema\";\n\n/**\n * Validates the email format and length.\n */\nexport function verifyEmailInput(email: string): boolean {\n return /^.+@.+\\..+$/.test(email) && email.length < 256;\n}\n\n/**\n * Checks if an email address is already in use.\n * @returns True if the email is available, false otherwise.\n */\nexport async function checkEmailAvailability(email: string): Promise<boolean> {\n const [entries] = await db\n .select({ count: count() })\n .from(userTable)\n .where(eq(userTable.email, email));\n\n return entries.count === 0;\n}\n"],"mappings":";;;;;;;;AAOA,SAAgB,iBAAiB,OAAwB;AACvD,QAAO,cAAc,KAAK,MAAM,IAAI,MAAM,SAAS;;;;;;
|
|
1
|
+
{"version":3,"file":"email.mjs","names":[],"sources":["../../../src/server/auth/email.ts"],"sourcesContent":["import { count, eq } from \"drizzle-orm\";\nimport { db } from \"../database/inject\";\nimport { userTable } from \"../database/schema\";\n\n/**\n * Validates the email format and length.\n */\nexport function verifyEmailInput(email: string): boolean {\n return /^.+@.+\\..+$/.test(email) && email.length < 256 && email.length > 0;\n}\n\n/**\n * Checks if an email address is already in use.\n * @returns True if the email is available, false otherwise.\n */\nexport async function checkEmailAvailability(email: string): Promise<boolean> {\n const [entries] = await db\n .select({ count: count() })\n .from(userTable)\n .where(eq(userTable.email, email));\n\n return entries.count === 0;\n}\n"],"mappings":";;;;;;;;AAOA,SAAgB,iBAAiB,OAAwB;AACvD,QAAO,cAAc,KAAK,MAAM,IAAI,MAAM,SAAS,OAAO,MAAM,SAAS;;;;;;AAO3E,eAAsB,uBAAuB,OAAiC;CAC5E,MAAM,CAAC,WAAW,MAAM,GACrB,OAAO,EAAE,OAAO,OAAO,EAAE,CAAC,CAC1B,KAAK,UAAU,CACf,MAAM,GAAG,UAAU,OAAO,MAAM,CAAC;AAEpC,QAAO,QAAQ,UAAU"}
|
|
@@ -3,10 +3,10 @@
|
|
|
3
3
|
const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
|
|
4
4
|
const require_inject = require('../database/inject.cjs');
|
|
5
5
|
const require_schema = require('../database/schema.cjs');
|
|
6
|
-
const require_index = require('../emails/index.cjs');
|
|
7
6
|
const require_password = require('./password.cjs');
|
|
8
7
|
const require_encode = require('../../core/auth/utils/encode.cjs');
|
|
9
8
|
const require_encryption = require('../../core/auth/utils/encryption.cjs');
|
|
9
|
+
const require_index = require('../emails/index.cjs');
|
|
10
10
|
let drizzle_orm = require("drizzle-orm");
|
|
11
11
|
|
|
12
12
|
//#region src/server/auth/user.ts
|
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
import { db } from "../database/inject.mjs";
|
|
4
4
|
import { rolesTable, userTable, usersToRolesTable } from "../database/schema.mjs";
|
|
5
|
-
import { sendRecoveryCode } from "../emails/index.mjs";
|
|
6
5
|
import { hashPassword } from "./password.mjs";
|
|
7
6
|
import { generateRandomRecoveryCode } from "../../core/auth/utils/encode.mjs";
|
|
8
7
|
import { decryptToString, encryptString } from "../../core/auth/utils/encryption.mjs";
|
|
8
|
+
import { sendRecoveryCode } from "../emails/index.mjs";
|
|
9
9
|
import { and, eq } from "drizzle-orm";
|
|
10
10
|
|
|
11
11
|
//#region src/server/auth/user.ts
|
package/dist/server.cjs
CHANGED
|
@@ -3,22 +3,22 @@ const require_validation = require('./core/auth/validation.cjs');
|
|
|
3
3
|
const require_event_bus = require('./core/event-bus.cjs');
|
|
4
4
|
const require_inject = require('./server/database/inject.cjs');
|
|
5
5
|
const require_schema = require('./server/database/schema.cjs');
|
|
6
|
-
const
|
|
6
|
+
const require_augment = require('./core/auth/augment.cjs');
|
|
7
7
|
const require_password = require('./server/auth/password.cjs');
|
|
8
8
|
const require_encode = require('./core/auth/utils/encode.cjs');
|
|
9
9
|
const require_encryption = require('./core/auth/utils/encryption.cjs');
|
|
10
|
+
const require_index = require('./server/emails/index.cjs');
|
|
10
11
|
const require_user = require('./server/auth/user.cjs');
|
|
11
|
-
const require_augment = require('./core/auth/augment.cjs');
|
|
12
|
-
const require_logic = require('./core/auth/logic.cjs');
|
|
13
12
|
const require_email_verification = require('./core/auth/email-verification.cjs');
|
|
14
|
-
const
|
|
15
|
-
const require_bootstrap = require('./core/bootstrap.cjs');
|
|
13
|
+
const require_logic = require('./core/auth/logic.cjs');
|
|
16
14
|
const require_session = require('./core/auth/session.cjs');
|
|
17
15
|
const require_actions = require('./core/notifications/actions.cjs');
|
|
18
16
|
const require_password_reset = require('./core/auth/password-reset.cjs');
|
|
19
17
|
const require_rbac = require('./core/auth/rbac.cjs');
|
|
20
|
-
const require_config_server = require('./core/config.server.cjs');
|
|
21
18
|
const require_service = require('./core/filesystem/service.cjs');
|
|
19
|
+
const require_setup = require('./core/setup.cjs');
|
|
20
|
+
const require_bootstrap = require('./core/bootstrap.cjs');
|
|
21
|
+
const require_config_server = require('./core/config.server.cjs');
|
|
22
22
|
const require_email = require('./server/auth/email.cjs');
|
|
23
23
|
|
|
24
24
|
exports.assignPermissionToRole = require_rbac.assignPermissionToRole;
|
package/dist/server.mjs
CHANGED
|
@@ -2,22 +2,22 @@ import { forgotPasswordSchema, loginSchema, passkeysSetupSchema, recoveryCodeVer
|
|
|
2
2
|
import { eventBus } from "./core/event-bus.mjs";
|
|
3
3
|
import { db, injectDb } from "./server/database/inject.mjs";
|
|
4
4
|
import { coreSchema, emailVerificationTable, notificationTable, passwordResetSessionTable, permissionsTable, relations, rolesTable, rolesToPermissionsTable, sessionTable, systemModulesTable, userTable, usersToPermissionsTable, usersToRolesTable } from "./server/database/schema.mjs";
|
|
5
|
-
import {
|
|
5
|
+
import { augmentSession, augmentUser, registerIdentityAugmenter, registerPasswordResetSessionAugmenter, registerSessionAugmenter } from "./core/auth/augment.mjs";
|
|
6
6
|
import { hashPassword, verifyPasswordHash, verifyPasswordStrength } from "./server/auth/password.mjs";
|
|
7
7
|
import { generateRandomOTP, generateRandomRecoveryCode } from "./core/auth/utils/encode.mjs";
|
|
8
8
|
import { decrypt, decryptToString, encrypt, encryptString } from "./core/auth/utils/encryption.mjs";
|
|
9
|
+
import { send2FACode, sendRecoveryCode, sendResetPassword, sendVerifyEmail } from "./server/emails/index.mjs";
|
|
9
10
|
import { createOAuthUser, createUser, getUserById, getUserFromEmail, getUserPasswordHash, getUserRecoverCode, resetUserRecoveryCode, setUserAsEmailVerifiedIfEmailMatches, updateUserAwatar, updateUserEmailAndSetEmailAsVerified, updateUserName, updateUserPassword, verifyUsernameInput } from "./server/auth/user.mjs";
|
|
10
|
-
import { augmentSession, augmentUser, registerIdentityAugmenter, registerPasswordResetSessionAugmenter, registerSessionAugmenter } from "./core/auth/augment.mjs";
|
|
11
|
-
import { checkSecurity, finalizeLogin, performFullUserAugmentation, registerAuthValidator, registerEmailVerificationValidator, registerPasswordResetValidator, registerSecurityRequirement, runEmailVerificationValidators, runPasswordResetValidators, signIn, signOut, signUp } from "./core/auth/logic.mjs";
|
|
12
11
|
import { createEmailVerificationRequest, deleteEmailVerificationRequestCookie, deleteUserEmailVerificationRequest, getUserEmailVerificationRequest, getUserEmailVerificationRequestFromRequest, initEmailVerification, sendVerificationEmail, setEmailVerificationRequestCookie } from "./core/auth/email-verification.mjs";
|
|
13
|
-
import {
|
|
14
|
-
import { ensureSystemInitialized } from "./core/bootstrap.mjs";
|
|
12
|
+
import { checkSecurity, finalizeLogin, performFullUserAugmentation, registerAuthValidator, registerEmailVerificationValidator, registerPasswordResetValidator, registerSecurityRequirement, runEmailVerificationValidators, runPasswordResetValidators, signIn, signOut, signUp } from "./core/auth/logic.mjs";
|
|
15
13
|
import { createSession, deleteSessionTokenCookie, generateSessionToken, getCurrentSession, getIPAddress, getUserSessions, invalidateOtherSessions, invalidateSession, invalidateUserSessions, sessionSignOut, setSessionTokenCookie, validateSessionToken } from "./core/auth/session.mjs";
|
|
16
14
|
import { createNotification, getUserNotifications, markAllNotificationsAsRead, markNotificationAsRead } from "./core/notifications/actions.mjs";
|
|
17
15
|
import { createPasswordResetSession, deletePasswordResetSessionTokenCookie, getCurrentPasswordResetSession, invalidateUserPasswordResetSessions, sendPasswordResetEmail, setPasswordResetSessionAsEmailVerified, setPasswordResetSessionTokenCookie, validatePasswordResetSessionToken } from "./core/auth/password-reset.mjs";
|
|
18
16
|
import { assignPermissionToRole, assignPermissionToUser, assignRoleToUser, createPermission, createRole, deletePermission, deleteRole, getPermissions, getRoleById, getRolePermissions, getRoles, getUserRbacData, revokePermissionFromRole, revokePermissionFromUser, revokeRoleFromUser } from "./core/auth/rbac.mjs";
|
|
19
|
-
import { getKryoConfig, getModulesDir } from "./core/config.server.mjs";
|
|
20
17
|
import { filesystemService } from "./core/filesystem/service.mjs";
|
|
18
|
+
import { isSystemInstalled } from "./core/setup.mjs";
|
|
19
|
+
import { ensureSystemInitialized } from "./core/bootstrap.mjs";
|
|
20
|
+
import { getKryoConfig, getModulesDir } from "./core/config.server.mjs";
|
|
21
21
|
import { checkEmailAvailability, verifyEmailInput } from "./server/auth/email.mjs";
|
|
22
22
|
|
|
23
23
|
export { assignPermissionToRole, assignPermissionToUser, assignRoleToUser, augmentSession, augmentUser, checkEmailAvailability, checkSecurity, coreSchema, createEmailVerificationRequest, createNotification, createOAuthUser, createPasswordResetSession, createPermission, createRole, createSession, createUser, db, decrypt, decryptToString, deleteEmailVerificationRequestCookie, deletePasswordResetSessionTokenCookie, deletePermission, deleteRole, deleteSessionTokenCookie, deleteUserEmailVerificationRequest, emailVerificationTable, encrypt, encryptString, ensureSystemInitialized, eventBus, filesystemService, finalizeLogin, forgotPasswordSchema, generateRandomOTP, generateRandomRecoveryCode, generateSessionToken, getCurrentPasswordResetSession, getCurrentSession, getIPAddress, getKryoConfig, getModulesDir, getPermissions, getRoleById, getRolePermissions, getRoles, getUserById, getUserEmailVerificationRequest, getUserEmailVerificationRequestFromRequest, getUserFromEmail, getUserNotifications, getUserPasswordHash, getUserRbacData, getUserRecoverCode, getUserSessions, hashPassword, initEmailVerification, injectDb, invalidateOtherSessions, invalidateSession, invalidateUserPasswordResetSessions, invalidateUserSessions, isSystemInstalled, loginSchema, markAllNotificationsAsRead, markNotificationAsRead, notificationTable, passkeysSetupSchema, passwordResetSessionTable, performFullUserAugmentation, permissionsTable, recoveryCodeVerifySchema, registerAuthValidator, registerEmailVerificationValidator, registerIdentityAugmenter, registerPasswordResetSessionAugmenter, registerPasswordResetValidator, registerSchema, registerSecurityRequirement, registerSessionAugmenter, relations, resetPasswordSchema, resetUserRecoveryCode, revokePermissionFromRole, revokePermissionFromUser, revokeRoleFromUser, rolesTable, rolesToPermissionsTable, runEmailVerificationValidators, runPasswordResetValidators, send2FACode, sendPasswordResetEmail, sendRecoveryCode, sendResetPassword, sendVerificationEmail, sendVerifyEmail, sessionSignOut, sessionTable, setEmailVerificationRequestCookie, setPasswordResetSessionAsEmailVerified, setPasswordResetSessionTokenCookie, setSessionTokenCookie, setUserAsEmailVerifiedIfEmailMatches, signIn, signOut, signUp, systemModulesTable, totpSetupSchema, totpVerifySchema, updateUserAwatar, updateUserEmailAndSetEmailAsVerified, updateUserName, updateUserPassword, userTable, usersToPermissionsTable, usersToRolesTable, validatePasswordResetSessionToken, validateSessionToken, verifyEmailInput, verifyEmailSchema, verifyPasswordHash, verifyPasswordStrength, verifyUsernameInput };
|
package/package.json
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@arch-cadre/core",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.16",
|
|
4
|
+
"type": "module",
|
|
4
5
|
"description": "Core logic for Kryo framework",
|
|
5
6
|
"exports": {
|
|
6
7
|
".": {
|
|
@@ -17,6 +18,9 @@
|
|
|
17
18
|
"dist"
|
|
18
19
|
],
|
|
19
20
|
"scripts": {
|
|
21
|
+
"clean": "rm -rf ./dist",
|
|
22
|
+
"switch:dev": "node scripts/switchToSrc.js",
|
|
23
|
+
"switch:prod": "node scripts/switchToDist.js",
|
|
20
24
|
"release": "npm publish --access public --no-git-checks",
|
|
21
25
|
"dev:unbuild": "unbuild --stub",
|
|
22
26
|
"build:unbuild": "unbuild",
|
|
@@ -43,7 +47,6 @@
|
|
|
43
47
|
"swr": "^2.3.8"
|
|
44
48
|
},
|
|
45
49
|
"devDependencies": {
|
|
46
|
-
"@biomejs/biome": "2.3.8",
|
|
47
50
|
"@types/bcryptjs": "^3.0.0",
|
|
48
51
|
"@types/pg": "^8.16.0",
|
|
49
52
|
"@types/react": "^19",
|