@axova/shared 1.0.0
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/CONFIGURATION_GUIDE.md +1 -0
- package/README.md +384 -0
- package/SCHEMA_ORGANIZATION.md +209 -0
- package/dist/configs/index.d.ts +85 -0
- package/dist/configs/index.js +555 -0
- package/dist/events/kafka.d.ts +40 -0
- package/dist/events/kafka.js +311 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +41 -0
- package/dist/interfaces/customer-events.d.ts +85 -0
- package/dist/interfaces/customer-events.js +2 -0
- package/dist/interfaces/inventory-events.d.ts +453 -0
- package/dist/interfaces/inventory-events.js +3 -0
- package/dist/interfaces/inventory-types.d.ts +894 -0
- package/dist/interfaces/inventory-types.js +3 -0
- package/dist/interfaces/order-events.d.ts +320 -0
- package/dist/interfaces/order-events.js +3 -0
- package/dist/lib/auditLogger.d.ts +162 -0
- package/dist/lib/auditLogger.js +626 -0
- package/dist/lib/authOrganization.d.ts +24 -0
- package/dist/lib/authOrganization.js +110 -0
- package/dist/lib/db.d.ts +6 -0
- package/dist/lib/db.js +88 -0
- package/dist/middleware/serviceAuth.d.ts +60 -0
- package/dist/middleware/serviceAuth.js +272 -0
- package/dist/middleware/storeOwnership.d.ts +15 -0
- package/dist/middleware/storeOwnership.js +156 -0
- package/dist/middleware/storeValidationMiddleware.d.ts +44 -0
- package/dist/middleware/storeValidationMiddleware.js +180 -0
- package/dist/middleware/userAuth.d.ts +27 -0
- package/dist/middleware/userAuth.js +218 -0
- package/dist/schemas/admin/admin-schema.d.ts +741 -0
- package/dist/schemas/admin/admin-schema.js +111 -0
- package/dist/schemas/ai-moderation/ai-moderation-schema.d.ts +648 -0
- package/dist/schemas/ai-moderation/ai-moderation-schema.js +88 -0
- package/dist/schemas/common/common-schemas.d.ts +436 -0
- package/dist/schemas/common/common-schemas.js +94 -0
- package/dist/schemas/compliance/compliance-schema.d.ts +3388 -0
- package/dist/schemas/compliance/compliance-schema.js +472 -0
- package/dist/schemas/compliance/kyc-schema.d.ts +2642 -0
- package/dist/schemas/compliance/kyc-schema.js +361 -0
- package/dist/schemas/customer/customer-schema.d.ts +2727 -0
- package/dist/schemas/customer/customer-schema.js +399 -0
- package/dist/schemas/index.d.ts +27 -0
- package/dist/schemas/index.js +138 -0
- package/dist/schemas/inventory/inventory-tables.d.ts +9476 -0
- package/dist/schemas/inventory/inventory-tables.js +1470 -0
- package/dist/schemas/inventory/lot-tables.d.ts +3281 -0
- package/dist/schemas/inventory/lot-tables.js +608 -0
- package/dist/schemas/order/order-schema.d.ts +5825 -0
- package/dist/schemas/order/order-schema.js +954 -0
- package/dist/schemas/product/discount-relations.d.ts +15 -0
- package/dist/schemas/product/discount-relations.js +34 -0
- package/dist/schemas/product/discount-schema.d.ts +1975 -0
- package/dist/schemas/product/discount-schema.js +297 -0
- package/dist/schemas/product/product-relations.d.ts +41 -0
- package/dist/schemas/product/product-relations.js +133 -0
- package/dist/schemas/product/product-schema.d.ts +4544 -0
- package/dist/schemas/product/product-schema.js +671 -0
- package/dist/schemas/store/store-audit-schema.d.ts +4135 -0
- package/dist/schemas/store/store-audit-schema.js +556 -0
- package/dist/schemas/store/store-schema.d.ts +3100 -0
- package/dist/schemas/store/store-schema.js +381 -0
- package/dist/schemas/store/store-settings-schema.d.ts +665 -0
- package/dist/schemas/store/store-settings-schema.js +141 -0
- package/dist/schemas/types.d.ts +50 -0
- package/dist/schemas/types.js +3 -0
- package/dist/types/events.d.ts +2396 -0
- package/dist/types/events.js +505 -0
- package/dist/utils/errorHandler.d.ts +12 -0
- package/dist/utils/errorHandler.js +36 -0
- package/dist/utils/subdomain.d.ts +6 -0
- package/dist/utils/subdomain.js +20 -0
- package/nul +8 -0
- package/package.json +43 -0
- package/src/configs/index.ts +654 -0
- package/src/events/kafka.ts +429 -0
- package/src/index.ts +26 -0
- package/src/interfaces/customer-events.ts +106 -0
- package/src/interfaces/inventory-events.ts +545 -0
- package/src/interfaces/inventory-types.ts +1004 -0
- package/src/interfaces/order-events.ts +381 -0
- package/src/lib/auditLogger.ts +1117 -0
- package/src/lib/authOrganization.ts +153 -0
- package/src/lib/db.ts +64 -0
- package/src/middleware/serviceAuth.ts +328 -0
- package/src/middleware/storeOwnership.ts +199 -0
- package/src/middleware/storeValidationMiddleware.ts +247 -0
- package/src/middleware/userAuth.ts +248 -0
- package/src/schemas/admin/admin-schema.ts +208 -0
- package/src/schemas/ai-moderation/ai-moderation-schema.ts +180 -0
- package/src/schemas/common/common-schemas.ts +108 -0
- package/src/schemas/compliance/compliance-schema.ts +927 -0
- package/src/schemas/compliance/kyc-schema.ts +649 -0
- package/src/schemas/customer/customer-schema.ts +576 -0
- package/src/schemas/index.ts +189 -0
- package/src/schemas/inventory/inventory-tables.ts +1927 -0
- package/src/schemas/inventory/lot-tables.ts +799 -0
- package/src/schemas/order/order-schema.ts +1400 -0
- package/src/schemas/product/discount-relations.ts +44 -0
- package/src/schemas/product/discount-schema.ts +464 -0
- package/src/schemas/product/product-relations.ts +187 -0
- package/src/schemas/product/product-schema.ts +955 -0
- package/src/schemas/store/ethiopian_business_api.md.resolved +212 -0
- package/src/schemas/store/store-audit-schema.ts +1257 -0
- package/src/schemas/store/store-schema.ts +661 -0
- package/src/schemas/store/store-settings-schema.ts +231 -0
- package/src/schemas/types.ts +67 -0
- package/src/types/events.ts +646 -0
- package/src/utils/errorHandler.ts +44 -0
- package/src/utils/subdomain.ts +19 -0
- package/tsconfig.json +21 -0
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { createId } from "@paralleldrive/cuid2";
|
|
2
|
+
import { APIError } from "../utils/errorHandler";
|
|
3
|
+
|
|
4
|
+
export interface AuthOrganizationCreateRequest {
|
|
5
|
+
name: string;
|
|
6
|
+
slug: string;
|
|
7
|
+
logo?: string;
|
|
8
|
+
metadata?: Record<string, unknown>;
|
|
9
|
+
userId?: string;
|
|
10
|
+
keepCurrentActiveOrganization?: boolean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface AuthOrganizationResponse {
|
|
14
|
+
id: string;
|
|
15
|
+
name: string;
|
|
16
|
+
slug: string;
|
|
17
|
+
logo?: string;
|
|
18
|
+
metadata?: Record<string, unknown>;
|
|
19
|
+
createdAt: Date;
|
|
20
|
+
updatedAt?: Date;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Creates an organization using the auth service
|
|
25
|
+
* @param organizationData Organization data to create
|
|
26
|
+
* @param headers Authentication headers to forward
|
|
27
|
+
* @returns Promise resolving to created organization data
|
|
28
|
+
*/
|
|
29
|
+
export const createAuthOrganization = async (
|
|
30
|
+
organizationData: AuthOrganizationCreateRequest,
|
|
31
|
+
headers?: Record<string, string>,
|
|
32
|
+
): Promise<AuthOrganizationResponse> => {
|
|
33
|
+
try {
|
|
34
|
+
console.log("Creating organization:", {
|
|
35
|
+
name: organizationData.name,
|
|
36
|
+
slug: organizationData.slug,
|
|
37
|
+
userId: organizationData.userId,
|
|
38
|
+
hasHeaders: !!headers,
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// Prepare payload matching auth service expectations
|
|
42
|
+
const payload = {
|
|
43
|
+
name: organizationData.name,
|
|
44
|
+
slug: organizationData.slug,
|
|
45
|
+
...(organizationData.logo && { logo: organizationData.logo }),
|
|
46
|
+
...(organizationData.metadata && { metadata: organizationData.metadata }),
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
// Make direct HTTP request to auth service
|
|
50
|
+
const authBaseUrl =
|
|
51
|
+
process.env.NEXT_PUBLIC_AUTH_URL || "http://localhost:4000";
|
|
52
|
+
const url = `${authBaseUrl}/api/auth/organization/create`;
|
|
53
|
+
|
|
54
|
+
const fetchOptions: RequestInit = {
|
|
55
|
+
method: "POST",
|
|
56
|
+
headers: {
|
|
57
|
+
"Content-Type": "application/json",
|
|
58
|
+
...headers,
|
|
59
|
+
},
|
|
60
|
+
body: JSON.stringify(payload),
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
console.log("Sending request to auth service:", url);
|
|
64
|
+
const response = await fetch(url, fetchOptions);
|
|
65
|
+
|
|
66
|
+
console.log("Auth service response:", {
|
|
67
|
+
status: response.status,
|
|
68
|
+
statusText: response.statusText,
|
|
69
|
+
ok: response.ok,
|
|
70
|
+
headers: Object.fromEntries(response.headers.entries()),
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
// Check HTTP response status
|
|
74
|
+
if (!response.ok) {
|
|
75
|
+
const errorText = await response.text();
|
|
76
|
+
console.error("Auth service HTTP error:", {
|
|
77
|
+
status: response.status,
|
|
78
|
+
statusText: response.statusText,
|
|
79
|
+
body: errorText,
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
throw new APIError(
|
|
83
|
+
`Auth service error: ${response.status} ${response.statusText}`,
|
|
84
|
+
response.status,
|
|
85
|
+
{ code: "AUTH_HTTP_ERROR", response: errorText },
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Parse JSON response
|
|
90
|
+
let responseData: any;
|
|
91
|
+
try {
|
|
92
|
+
responseData = await response.json();
|
|
93
|
+
} catch (parseError) {
|
|
94
|
+
console.error("Failed to parse auth service response:", parseError);
|
|
95
|
+
throw new APIError("Invalid response format from auth service", 500, {
|
|
96
|
+
code: "JSON_PARSE_ERROR",
|
|
97
|
+
originalError: parseError,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Auth service returns organization data directly
|
|
102
|
+
// Check if response has the required organization fields
|
|
103
|
+
if (responseData.id && responseData.name) {
|
|
104
|
+
console.log("Organization created successfully:", {
|
|
105
|
+
id: responseData.id,
|
|
106
|
+
name: responseData.name,
|
|
107
|
+
slug: responseData.slug,
|
|
108
|
+
});
|
|
109
|
+
} else {
|
|
110
|
+
console.error("Invalid organization response:", responseData);
|
|
111
|
+
throw new APIError(
|
|
112
|
+
"Invalid organization data format from auth service",
|
|
113
|
+
500,
|
|
114
|
+
{ code: "INVALID_ORGANIZATION_DATA", response: responseData },
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Return structured organization data (responseData contains the org data directly)
|
|
119
|
+
return {
|
|
120
|
+
id: responseData.id,
|
|
121
|
+
name: responseData.name,
|
|
122
|
+
slug: responseData.slug,
|
|
123
|
+
logo: responseData.logo || undefined,
|
|
124
|
+
metadata: responseData.metadata,
|
|
125
|
+
createdAt: new Date(responseData.createdAt),
|
|
126
|
+
updatedAt: undefined,
|
|
127
|
+
};
|
|
128
|
+
} catch (error: any) {
|
|
129
|
+
console.error("Organization creation failed:", {
|
|
130
|
+
message: error.message,
|
|
131
|
+
status: error.status || error.statusCode,
|
|
132
|
+
code: error.code,
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
// Handle different error types
|
|
136
|
+
if (error instanceof APIError) {
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (error.message && error.message.includes("JSON")) {
|
|
141
|
+
throw new APIError("Invalid response format from auth service", 500, {
|
|
142
|
+
code: "JSON_PARSE_ERROR",
|
|
143
|
+
originalError: error.message,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
throw new APIError(
|
|
148
|
+
error.message || "Failed to create organization",
|
|
149
|
+
error.status || error.statusCode || 500,
|
|
150
|
+
{ code: "ORGANIZATION_CREATION_FAILED", originalError: error },
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
};
|
package/src/lib/db.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import * as dotenv from "dotenv";
|
|
2
|
+
import { drizzle } from "drizzle-orm/node-postgres";
|
|
3
|
+
import { Pool } from "pg";
|
|
4
|
+
|
|
5
|
+
// Load environment variables from .env file
|
|
6
|
+
dotenv.config();
|
|
7
|
+
|
|
8
|
+
// Configure PostgreSQL connection
|
|
9
|
+
const connectionString = process.env.DATABASE_URL;
|
|
10
|
+
|
|
11
|
+
if (!connectionString) {
|
|
12
|
+
throw new Error("DATABASE_URL environment variable is not set");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Configure PostgreSQL to handle timestamps and dates properly
|
|
16
|
+
const pool = new Pool({
|
|
17
|
+
connectionString,
|
|
18
|
+
ssl:
|
|
19
|
+
process.env.NODE_ENV === "production"
|
|
20
|
+
? { rejectUnauthorized: false }
|
|
21
|
+
: false,
|
|
22
|
+
// Connection pool configuration to prevent "Connection is closed" errors
|
|
23
|
+
max: 20, // Maximum number of clients in the pool
|
|
24
|
+
min: 2, // Minimum number of clients in the pool
|
|
25
|
+
idleTimeoutMillis: 30000, // Close idle clients after 30 seconds
|
|
26
|
+
connectionTimeoutMillis: 10000, // Wait 10 seconds for a connection
|
|
27
|
+
// Keep connections alive
|
|
28
|
+
keepAlive: true,
|
|
29
|
+
keepAliveInitialDelayMillis: 10000,
|
|
30
|
+
// Add parsing configuration for timestamps
|
|
31
|
+
types: {
|
|
32
|
+
getTypeParser: (typeId: number, _format?: string) => {
|
|
33
|
+
// Handle dates and timestamps to ensure they're properly converted to JavaScript Date objects
|
|
34
|
+
if (
|
|
35
|
+
typeId === 1082 ||
|
|
36
|
+
typeId === 1083 ||
|
|
37
|
+
typeId === 1114 ||
|
|
38
|
+
typeId === 1184
|
|
39
|
+
) {
|
|
40
|
+
return (val: string) => (val === null ? null : new Date(val));
|
|
41
|
+
}
|
|
42
|
+
return undefined;
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
// Add error handler to the pool
|
|
48
|
+
pool.on("error", (err) => {
|
|
49
|
+
console.error("❌ Unexpected database pool error:", err);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
pool.on("connect", () => {
|
|
53
|
+
if (process.env.NODE_ENV === "development") {
|
|
54
|
+
console.log("✅ Database pool connection established");
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
// Create a Drizzle ORM instance
|
|
59
|
+
export const db = drizzle(pool, {
|
|
60
|
+
logger: process.env.NODE_ENV === "development",
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
// Exported for testing
|
|
64
|
+
export { pool };
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import type { FastifyReply, FastifyRequest } from "fastify";
|
|
2
|
+
import jwt from "jsonwebtoken";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
|
|
5
|
+
// Service claims schema
|
|
6
|
+
export const ServiceClaimsSchema = z.object({
|
|
7
|
+
service: z.string(),
|
|
8
|
+
permissions: z.array(z.string()),
|
|
9
|
+
iat: z.number(),
|
|
10
|
+
exp: z.number(),
|
|
11
|
+
iss: z.literal("axova-platform"),
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
export type ServiceClaims = z.infer<typeof ServiceClaimsSchema>;
|
|
15
|
+
|
|
16
|
+
// Service authentication configuration
|
|
17
|
+
export interface ServiceAuthConfig {
|
|
18
|
+
internalSecret: string;
|
|
19
|
+
tokenExpiry?: string; // Default: '1h'
|
|
20
|
+
requiredPermissions?: string[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Extended request interface
|
|
24
|
+
export interface AuthenticatedRequest extends FastifyRequest {
|
|
25
|
+
serviceClaims?: ServiceClaims;
|
|
26
|
+
isServiceAuthenticated?: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Service authentication class
|
|
30
|
+
export class ServiceAuthenticator {
|
|
31
|
+
private secret: string;
|
|
32
|
+
private tokenExpiry: string;
|
|
33
|
+
|
|
34
|
+
constructor(config: ServiceAuthConfig) {
|
|
35
|
+
this.secret = config.internalSecret;
|
|
36
|
+
this.tokenExpiry = config.tokenExpiry || "1h";
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Generate service token
|
|
40
|
+
generateServiceToken(service: string, permissions: string[] = []): string {
|
|
41
|
+
const payload: Omit<ServiceClaims, "iat" | "exp"> = {
|
|
42
|
+
service,
|
|
43
|
+
permissions,
|
|
44
|
+
iss: "axova-platform",
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
return jwt.sign(payload, this.secret, {
|
|
48
|
+
expiresIn: this.tokenExpiry,
|
|
49
|
+
algorithm: "HS256",
|
|
50
|
+
} as jwt.SignOptions);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Verify service token
|
|
54
|
+
verifyServiceToken(token: string): ServiceClaims {
|
|
55
|
+
try {
|
|
56
|
+
const decoded = jwt.verify(token, this.secret, {
|
|
57
|
+
algorithms: ["HS256"],
|
|
58
|
+
issuer: "axova-platform",
|
|
59
|
+
}) as ServiceClaims;
|
|
60
|
+
|
|
61
|
+
// Validate with Zod schema
|
|
62
|
+
return ServiceClaimsSchema.parse(decoded);
|
|
63
|
+
} catch (error) {
|
|
64
|
+
throw new Error(
|
|
65
|
+
`Invalid service token: ${error instanceof Error ? error.message : "Unknown error"}`,
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Fastify middleware for service authentication
|
|
71
|
+
serviceAuthMiddleware(requiredPermissions: string[] = []) {
|
|
72
|
+
return async (request: AuthenticatedRequest, reply: FastifyReply) => {
|
|
73
|
+
try {
|
|
74
|
+
const authHeader = request.headers.authorization;
|
|
75
|
+
const serviceToken = request.headers["x-service-token"] as string;
|
|
76
|
+
|
|
77
|
+
let token: string | null = null;
|
|
78
|
+
|
|
79
|
+
// Check for Bearer token in Authorization header
|
|
80
|
+
if (authHeader?.startsWith("Bearer ")) {
|
|
81
|
+
token = authHeader.substring(7);
|
|
82
|
+
}
|
|
83
|
+
// Check for service token in custom header
|
|
84
|
+
else if (serviceToken) {
|
|
85
|
+
token = serviceToken;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (!token) {
|
|
89
|
+
return reply.code(401).send({
|
|
90
|
+
error: "Service authentication required",
|
|
91
|
+
code: "MISSING_SERVICE_TOKEN",
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// DEVELOPMENT MODE: Accept simple constant tokens
|
|
96
|
+
const isDevelopment = process.env.NODE_ENV !== "production";
|
|
97
|
+
const developmentTokens = [
|
|
98
|
+
"dev-compliance-token",
|
|
99
|
+
"development-mode",
|
|
100
|
+
"compliance-dev-access",
|
|
101
|
+
"simple-dev-token",
|
|
102
|
+
"inventory-dev-access",
|
|
103
|
+
"product-dev-access",
|
|
104
|
+
"oxa-dev-access",
|
|
105
|
+
];
|
|
106
|
+
|
|
107
|
+
if (isDevelopment && developmentTokens.includes(token)) {
|
|
108
|
+
// In development, validate against a proper development service registry
|
|
109
|
+
// instead of using mock claims
|
|
110
|
+
try {
|
|
111
|
+
// TODO: Implement proper development service authentication
|
|
112
|
+
// For now, only allow specific development services with limited permissions
|
|
113
|
+
let servicePermissions: string[] = [];
|
|
114
|
+
let serviceName = "unknown-service";
|
|
115
|
+
|
|
116
|
+
// Grant permissions based on the specific development token
|
|
117
|
+
switch (token) {
|
|
118
|
+
case "inventory-dev-access":
|
|
119
|
+
serviceName = "inventory-service-dev";
|
|
120
|
+
servicePermissions = ["store:read", "store:write"];
|
|
121
|
+
break;
|
|
122
|
+
case "product-dev-access":
|
|
123
|
+
serviceName = "product-service-dev";
|
|
124
|
+
servicePermissions = ["store:read", "store:write"];
|
|
125
|
+
break;
|
|
126
|
+
case "compliance-dev-access":
|
|
127
|
+
serviceName = "compliance-service-dev";
|
|
128
|
+
servicePermissions = ["compliance:read", "compliance:write"];
|
|
129
|
+
break;
|
|
130
|
+
case "oxa-dev-access":
|
|
131
|
+
serviceName = "oxa-service-dev";
|
|
132
|
+
servicePermissions = ["store:read", "ai:moderate"];
|
|
133
|
+
break;
|
|
134
|
+
default:
|
|
135
|
+
throw new Error("Unknown development token");
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const devClaims: ServiceClaims = {
|
|
139
|
+
service: serviceName,
|
|
140
|
+
permissions: servicePermissions,
|
|
141
|
+
iss: "axova-platform",
|
|
142
|
+
iat: Math.floor(Date.now() / 1000),
|
|
143
|
+
exp: Math.floor(Date.now() / 1000) + 60 * 60 * 24, // 24 hours
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
request.serviceClaims = devClaims;
|
|
147
|
+
request.isServiceAuthenticated = true;
|
|
148
|
+
console.log(
|
|
149
|
+
`🔧 Development mode: Service authenticated with token "${token}"`,
|
|
150
|
+
);
|
|
151
|
+
return; // Skip JWT verification in development
|
|
152
|
+
} catch (error) {
|
|
153
|
+
return reply.code(401).send({
|
|
154
|
+
error: "Invalid development token",
|
|
155
|
+
code: "INVALID_DEVELOPMENT_TOKEN",
|
|
156
|
+
message: error instanceof Error ? error.message : "Unknown error",
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Verify the token
|
|
162
|
+
const claims = this.verifyServiceToken(token);
|
|
163
|
+
|
|
164
|
+
// Check required permissions
|
|
165
|
+
if (requiredPermissions.length > 0) {
|
|
166
|
+
const hasPermissions = requiredPermissions.every((perm) =>
|
|
167
|
+
claims.permissions.includes(perm),
|
|
168
|
+
);
|
|
169
|
+
|
|
170
|
+
if (!hasPermissions) {
|
|
171
|
+
return reply.code(403).send({
|
|
172
|
+
error: "Insufficient permissions",
|
|
173
|
+
code: "INSUFFICIENT_PERMISSIONS",
|
|
174
|
+
required: requiredPermissions,
|
|
175
|
+
granted: claims.permissions,
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// Attach claims to request
|
|
181
|
+
request.serviceClaims = claims;
|
|
182
|
+
request.isServiceAuthenticated = true;
|
|
183
|
+
|
|
184
|
+
console.log(`Service authenticated: ${claims.service}`);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
return reply.code(401).send({
|
|
187
|
+
error: "Invalid service token",
|
|
188
|
+
code: "INVALID_SERVICE_TOKEN",
|
|
189
|
+
message: error instanceof Error ? error.message : "Unknown error",
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Alternative HMAC-based authentication
|
|
196
|
+
generateHMACSignature(payload: string, timestamp: string): string {
|
|
197
|
+
const crypto = require("node:crypto");
|
|
198
|
+
const message = `${timestamp}.${payload}`;
|
|
199
|
+
return crypto
|
|
200
|
+
.createHmac("sha256", this.secret)
|
|
201
|
+
.update(message)
|
|
202
|
+
.digest("hex");
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// HMAC middleware
|
|
206
|
+
hmacAuthMiddleware() {
|
|
207
|
+
return async (request: AuthenticatedRequest, reply: FastifyReply) => {
|
|
208
|
+
try {
|
|
209
|
+
const signature = request.headers["x-signature"] as string;
|
|
210
|
+
const timestamp = request.headers["x-timestamp"] as string;
|
|
211
|
+
const service = request.headers["x-service"] as string;
|
|
212
|
+
|
|
213
|
+
if (!signature || !timestamp || !service) {
|
|
214
|
+
return reply.code(401).send({
|
|
215
|
+
error: "HMAC authentication headers missing",
|
|
216
|
+
code: "MISSING_HMAC_HEADERS",
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Check timestamp (prevent replay attacks)
|
|
221
|
+
const now = Date.now();
|
|
222
|
+
const requestTime = Number.parseInt(timestamp);
|
|
223
|
+
const timeDiff = Math.abs(now - requestTime);
|
|
224
|
+
|
|
225
|
+
// Allow 5 minutes tolerance
|
|
226
|
+
if (timeDiff > 300000) {
|
|
227
|
+
return reply.code(401).send({
|
|
228
|
+
error: "Request timestamp too old",
|
|
229
|
+
code: "TIMESTAMP_EXPIRED",
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// Get request body as string
|
|
234
|
+
const body = JSON.stringify(request.body || {});
|
|
235
|
+
const expectedSignature = this.generateHMACSignature(body, timestamp);
|
|
236
|
+
|
|
237
|
+
if (signature !== expectedSignature) {
|
|
238
|
+
return reply.code(401).send({
|
|
239
|
+
error: "Invalid HMAC signature",
|
|
240
|
+
code: "INVALID_HMAC_SIGNATURE",
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// Set service info on request
|
|
245
|
+
request.serviceClaims = {
|
|
246
|
+
service,
|
|
247
|
+
permissions: [], // HMAC doesn't include permissions by default
|
|
248
|
+
iat: requestTime,
|
|
249
|
+
exp: requestTime + 300000, // 5 minutes
|
|
250
|
+
iss: "axova-platform",
|
|
251
|
+
};
|
|
252
|
+
request.isServiceAuthenticated = true;
|
|
253
|
+
|
|
254
|
+
console.log(`Service authenticated via HMAC: ${service}`);
|
|
255
|
+
} catch (error) {
|
|
256
|
+
return reply.code(401).send({
|
|
257
|
+
error: "HMAC authentication failed",
|
|
258
|
+
code: "HMAC_AUTH_FAILED",
|
|
259
|
+
message: error instanceof Error ? error.message : "Unknown error",
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// Singleton factory
|
|
267
|
+
let serviceAuthInstance: ServiceAuthenticator | null = null;
|
|
268
|
+
|
|
269
|
+
export function createServiceAuthenticator(
|
|
270
|
+
config: ServiceAuthConfig,
|
|
271
|
+
): ServiceAuthenticator {
|
|
272
|
+
if (!serviceAuthInstance) {
|
|
273
|
+
serviceAuthInstance = new ServiceAuthenticator(config);
|
|
274
|
+
}
|
|
275
|
+
return serviceAuthInstance;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export function getServiceAuthenticator(): ServiceAuthenticator {
|
|
279
|
+
if (!serviceAuthInstance) {
|
|
280
|
+
throw new Error(
|
|
281
|
+
"Service authenticator not created. Call createServiceAuthenticator() first.",
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
return serviceAuthInstance;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Utility to get auth config from environment
|
|
288
|
+
export function getServiceAuthConfigFromEnv(): ServiceAuthConfig {
|
|
289
|
+
const internalSecret = process.env.INTERNAL_SECRET;
|
|
290
|
+
|
|
291
|
+
if (!internalSecret) {
|
|
292
|
+
throw new Error("INTERNAL_SECRET environment variable is required");
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
return {
|
|
296
|
+
internalSecret,
|
|
297
|
+
tokenExpiry: process.env.SERVICE_TOKEN_EXPIRY || "1h",
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// Common service permissions
|
|
302
|
+
export const SERVICE_PERMISSIONS = {
|
|
303
|
+
// Store service permissions
|
|
304
|
+
STORE_READ: "store:read",
|
|
305
|
+
STORE_WRITE: "store:write",
|
|
306
|
+
STORE_DELETE: "store:delete",
|
|
307
|
+
|
|
308
|
+
// Compliance service permissions
|
|
309
|
+
COMPLIANCE_READ: "compliance:read",
|
|
310
|
+
COMPLIANCE_WRITE: "compliance:write",
|
|
311
|
+
COMPLIANCE_BAN: "compliance:ban",
|
|
312
|
+
COMPLIANCE_APPEAL: "compliance:appeal",
|
|
313
|
+
|
|
314
|
+
// Notification service permissions
|
|
315
|
+
NOTIFICATION_SEND: "notification:send",
|
|
316
|
+
NOTIFICATION_READ: "notification:read",
|
|
317
|
+
|
|
318
|
+
// Audit service permissions
|
|
319
|
+
AUDIT_READ: "audit:read",
|
|
320
|
+
AUDIT_WRITE: "audit:write",
|
|
321
|
+
|
|
322
|
+
// Admin service permissions
|
|
323
|
+
ADMIN_OVERRIDE: "admin:override",
|
|
324
|
+
ADMIN_REVIEW: "admin:review",
|
|
325
|
+
|
|
326
|
+
// AI moderation permissions
|
|
327
|
+
AI_MODERATE: "ai:moderate",
|
|
328
|
+
} as const;
|