@descix/platform-api 1.0.1

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/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # @descix/platform-api
2
+
3
+ **Shared platform infrastructure: Firestore models, auth and session, permissions, entitlements,
4
+ email, service manifests and MCP tool definitions.** This is the DeSciX domain layer — it sits
5
+ between `@descix/cloud-core` (which owns GCP) and the services that consume it.
6
+
7
+ Consumed by the Cloud microservice, the Powch microservice, and the CLI.
8
+
9
+ ## Where it sits
10
+
11
+ ```
12
+ @descix/cloud-core GCP infrastructure: config, Firestore, Pub/Sub, manifests
13
+ ↑
14
+ @descix/platform-api DeSciX domain: models, auth, permissions, entitlements ← you are here
15
+ ↑
16
+ your microservice
17
+ ```
18
+
19
+ ## Entry points
20
+
21
+ The root export carries the common surface; sub-paths let a consumer take one area without pulling
22
+ the rest.
23
+
24
+ | Import path | Area |
25
+ |---|---|
26
+ | `@descix/platform-api` | everything below, re-exported |
27
+ | `@descix/platform-api/models` | Firestore models |
28
+ | `@descix/platform-api/auth` | session creation, email verification, user migration |
29
+ | `@descix/platform-api/permissions` | command permission checks |
30
+ | `@descix/platform-api/entitlements` | ownership and access queries |
31
+ | `@descix/platform-api/email` | transactional email |
32
+ | `@descix/platform-api/manifest` | service manifest shapes |
33
+ | `@descix/platform-api/service-bootstrap` | a microservice serves its manifest and registers it at boot — the one owner |
34
+ | `@descix/platform-api/mcp-tools` | MCP tool definitions and param validation |
35
+ | `@descix/platform-api/naming` | id and name normalisation |
36
+
37
+ ## Models
38
+
39
+ `Role`, `App`, `User`, `Community`, `UserCommunityStats`, `GuildSettings`, `Promotion`, `NFT`,
40
+ `AdCampaign`, `SharedAsset`, plus helpers including `clean_name_for_id`, `count_tokens`,
41
+ `sanitizeCredentialId`, `get_default_community` and `getUserEntitlements`.
42
+
43
+ **User-domain data has an owner.** User fields, entitlements and per-user flags belong to their
44
+ model or service module, and every consumer goes through it. Reaching into a user-domain Firestore
45
+ collection from outside its owner is a review-blocking anti-pattern, not a shortcut — the owner is
46
+ where a new field gets added and normalised.
47
+
48
+ ## MCP tool definitions
49
+
50
+ `./mcp-tools` holds the tool schemas the platform advertises. A parameter that is not declared in
51
+ a tool's `inputSchema` is **rejected at the gateway boundary**, with the accepted set returned in
52
+ the error — it is never silently dropped. That makes the schema, not the prose description, the
53
+ contract: if the two disagree, the schema is what callers experience.
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@descix/platform-api",
3
+ "version": "1.0.1",
4
+ "description": "Shared platform infrastructure: Firestore models, auth/session, permissions, entitlements, email",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "exports": {
8
+ ".": "./src/index.js",
9
+ "./models": "./src/models/index.js",
10
+ "./auth": "./src/auth/index.js",
11
+ "./email": "./src/email/index.js",
12
+ "./permissions": "./src/permissions/index.js",
13
+ "./entitlements": "./src/entitlements/index.js",
14
+ "./fabric": "./src/fabric/index.js",
15
+ "./manifest": "./src/manifest/index.js",
16
+ "./mcp-tools": "./src/mcp-tools/index.js",
17
+ "./naming": "./src/naming/index.js",
18
+ "./service-bootstrap": "./src/service-bootstrap/index.js"
19
+ },
20
+ "files": [
21
+ "src"
22
+ ],
23
+ "keywords": [
24
+ "descix",
25
+ "platform",
26
+ "models",
27
+ "auth",
28
+ "permissions"
29
+ ],
30
+ "license": "SEE LICENSE IN LICENSE.md",
31
+ "engines": {
32
+ "node": ">=24.0.0"
33
+ },
34
+ "dependencies": {
35
+ "@descix/cloud-core": "^1.1.0",
36
+ "google-auth-library": "^10.5.0",
37
+ "googleapis": "^169.0.0"
38
+ }
39
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * @descix/platform-api - Email Verification Auth
3
+ *
4
+ * Email-based verification code flow shared between Cloud and Powch microservices.
5
+ * Generates codes, stores hashed values in Firestore, sends via Gmail.
6
+ *
7
+ * Config values loaded at call time via getCloudConfig() from @descix/cloud-core.
8
+ */
9
+
10
+ import crypto from 'crypto';
11
+ import {
12
+ CacheFirestore,
13
+ FirestoreCollections,
14
+ Timestamp,
15
+ networkResponse,
16
+ NetworkStatus,
17
+ LoginStatus,
18
+ getCloudConfig,
19
+ } from '@descix/cloud-core';
20
+ import { sendVerificationEmail, normalizeEmail } from '../email/index.js';
21
+
22
+ const EMAIL_CODE_EXPIRY_MINUTES = 15;
23
+ const EMAIL_CODE_MAX_ATTEMPTS = 5;
24
+
25
+ /**
26
+ * Send an email verification code to the given address.
27
+ * Generates a 6-digit code, hashes and stores it in Firestore, then emails it.
28
+ *
29
+ * @param {Object} params
30
+ * @param {string} params.email - Email address to verify
31
+ * @returns {Promise<Object>} networkResponse result
32
+ */
33
+ export async function sendEmailVerification(params) {
34
+ const utils = getCloudConfig();
35
+ const { email } = params;
36
+ const normalized = normalizeEmail(email);
37
+ if (!normalized || !normalized.includes('@')) {
38
+ return networkResponse(NetworkStatus.ERROR, LoginStatus.AUTH_FAILED, 'Valid email address is required.');
39
+ }
40
+ if (!utils.DESCIX_ROUTER_COMMUNITY_MANAGER) {
41
+ return networkResponse(
42
+ NetworkStatus.ERROR,
43
+ LoginStatus.AUTH_FAILED,
44
+ 'Email sending is not configured on the server (missing DESCIX_ROUTER_COMMUNITY_MANAGER).'
45
+ );
46
+ }
47
+
48
+ const code = crypto.randomInt(100000, 999999).toString();
49
+ const codeHash = crypto.createHash('sha256').update(code).digest('hex');
50
+ const expiresAt = Timestamp.fromDate(new Date(Date.now() + EMAIL_CODE_EXPIRY_MINUTES * 60 * 1000));
51
+
52
+ const db = new CacheFirestore();
53
+ await db.put_doc(FirestoreCollections.EMAIL_VERIFICATIONS(), normalized, {
54
+ email: normalized,
55
+ code_hash: codeHash,
56
+ expires_at: expiresAt,
57
+ created_at: Timestamp.now(),
58
+ attempts: 0,
59
+ verified: false
60
+ });
61
+
62
+ await sendVerificationEmail(normalized, code, EMAIL_CODE_EXPIRY_MINUTES);
63
+
64
+ return networkResponse(NetworkStatus.OK, LoginStatus.CONNECTED, {
65
+ sent: true,
66
+ expires_in_minutes: EMAIL_CODE_EXPIRY_MINUTES
67
+ });
68
+ }
69
+
70
+ /**
71
+ * Verify an email code previously sent by sendEmailVerification.
72
+ *
73
+ * @param {Object} params
74
+ * @param {string} params.email - Email address that was verified
75
+ * @param {string} params.code - The 6-digit code to check
76
+ * @returns {Promise<Object>} networkResponse result
77
+ */
78
+ export async function verifyEmailCode(params) {
79
+ const { email, code } = params;
80
+ const normalized = normalizeEmail(email);
81
+ if (!normalized || !code) {
82
+ return networkResponse(NetworkStatus.ERROR, LoginStatus.AUTH_FAILED, 'Email and code are required.');
83
+ }
84
+ const db = new CacheFirestore();
85
+ const record = await db.get_doc(FirestoreCollections.EMAIL_VERIFICATIONS(), normalized);
86
+ if (!record) {
87
+ return networkResponse(NetworkStatus.ERROR, LoginStatus.AUTH_FAILED, 'No verification code found. Please request a new code.');
88
+ }
89
+ const now = new Date();
90
+ const expiresAt = record.expires_at?.toDate ? record.expires_at.toDate() : null;
91
+ if (expiresAt && expiresAt < now) {
92
+ return networkResponse(NetworkStatus.ERROR, LoginStatus.AUTH_FAILED, 'Verification code expired. Please request a new code.');
93
+ }
94
+ if (record.attempts >= EMAIL_CODE_MAX_ATTEMPTS) {
95
+ return networkResponse(NetworkStatus.ERROR, LoginStatus.AUTH_FAILED, 'Too many attempts. Please request a new code.');
96
+ }
97
+ const codeHash = crypto.createHash('sha256').update(code).digest('hex');
98
+ const matches = record.code_hash === codeHash;
99
+ await db.put_doc(FirestoreCollections.EMAIL_VERIFICATIONS(), normalized, {
100
+ attempts: (record.attempts || 0) + 1,
101
+ verified: matches,
102
+ verified_at: matches ? Timestamp.now() : record.verified_at || null
103
+ });
104
+ if (!matches) {
105
+ return networkResponse(NetworkStatus.ERROR, LoginStatus.AUTH_FAILED, 'Invalid verification code.');
106
+ }
107
+ return networkResponse(NetworkStatus.OK, LoginStatus.CONNECTED, { verified: true });
108
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @descix/platform-api - Auth module
3
+ *
4
+ * Session management, email verification, and user migration utilities.
5
+ */
6
+
7
+ export { createUserSession } from './session.js';
8
+ export { sendEmailVerification, verifyEmailCode } from './emailVerification.js';
9
+ export { migrateUserIfNeeded } from './migration.js';
@@ -0,0 +1,96 @@
1
+ /**
2
+ * @descix/platform-api - User Migration
3
+ *
4
+ * Lazy migration for users from legacy provider IDs to descix_ primary auth IDs.
5
+ * Used by Cloud's authHandlers.js during login flows.
6
+ */
7
+
8
+ import crypto from 'crypto';
9
+ import { CacheFirestore, FirestoreCollections, AuthProvider } from '@descix/cloud-core';
10
+
11
+ /**
12
+ * Migrate legacy user to DeSciX primary auth system (lazy migration on login).
13
+ *
14
+ * @param {string} legacyId - Legacy user ID (Discord snowflake, google_*, or descix_email_hash)
15
+ * @param {string} providerType - Provider type (AuthProvider.DISCORD, AuthProvider.GOOGLE, AuthProvider.DESCIX)
16
+ * @returns {Promise<Object|null>} Migrated user doc data or null if not found
17
+ *
18
+ * NOTE: Returns raw Firestore doc data, not a User model instance,
19
+ * to avoid a circular dependency with the models module.
20
+ * Callers should wrap in User.from_firestore() if needed.
21
+ */
22
+ export async function migrateUserIfNeeded(legacyId, providerType) {
23
+ if (!legacyId || !providerType) return null;
24
+
25
+ const db = new CacheFirestore();
26
+
27
+ // Check if already migrated (has descix_ prefix)
28
+ if (legacyId.startsWith('descix_')) {
29
+ return await db.get_doc(FirestoreCollections.USERS(), legacyId);
30
+ }
31
+
32
+ // Check if already indexed in ProviderIndex
33
+ const sanitizedId = sanitizeProviderId(legacyId);
34
+ const indexKey = `${providerType}_${sanitizedId}`;
35
+ const index = await db.get_doc(FirestoreCollections.PROVIDER_INDEX(), indexKey);
36
+ if (index?.descix_user_id) {
37
+ return await db.get_doc(FirestoreCollections.USERS(), index.descix_user_id);
38
+ }
39
+
40
+ // Try to load legacy user
41
+ const existingUser = await db.get_doc(FirestoreCollections.USERS(), legacyId);
42
+ if (!existingUser) {
43
+ return null;
44
+ }
45
+
46
+ // Generate new DeSciX ID
47
+ const newId = `descix_${crypto.randomUUID()}`;
48
+
49
+ // Create new user document with DeSciX ID
50
+ const userData = { ...existingUser, id: newId };
51
+
52
+ // Ensure provider_links is populated
53
+ if (!userData.provider_links || Object.keys(userData.provider_links).length === 0) {
54
+ userData.provider_links = {};
55
+ if (providerType === AuthProvider.DISCORD) {
56
+ userData.provider_links[AuthProvider.DISCORD] = {
57
+ provider_id: legacyId,
58
+ linked_at: new Date().toISOString()
59
+ };
60
+ } else if (providerType === AuthProvider.GOOGLE) {
61
+ const googleSub = legacyId.startsWith('google_') ? legacyId.substring(7) : legacyId;
62
+ userData.provider_links[AuthProvider.GOOGLE] = {
63
+ provider_id: googleSub,
64
+ linked_at: new Date().toISOString()
65
+ };
66
+ }
67
+ }
68
+
69
+ // Save new document
70
+ await db.put_doc(FirestoreCollections.USERS(), newId, userData);
71
+
72
+ // Add ProviderIndex entry for the new ID
73
+ await db.put_doc(FirestoreCollections.PROVIDER_INDEX(), indexKey, {
74
+ descix_user_id: newId,
75
+ provider_type: providerType,
76
+ provider_id: legacyId,
77
+ linked_at: new Date().toISOString()
78
+ });
79
+
80
+ console.log(`[migration] Migrated user ${legacyId} -> ${newId}`);
81
+ return userData;
82
+ }
83
+
84
+ /**
85
+ * Sanitize provider ID for use in Firestore document paths.
86
+ * @param {string} providerId - Original provider ID
87
+ * @returns {string} Sanitized ID safe for Firestore paths
88
+ */
89
+ function sanitizeProviderId(providerId) {
90
+ if (!providerId) return '';
91
+ if (providerId.includes('@') || providerId.includes('+') || providerId.includes('/')) {
92
+ // Hash emails and IDs with special characters
93
+ return crypto.createHash('sha256').update(providerId.toLowerCase()).digest('hex').substring(0, 32);
94
+ }
95
+ return providerId.replace(/[/.+@#[\]]/g, '_');
96
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @descix/platform-api - Session Management
3
+ *
4
+ * Creates and manages user sessions in Firestore.
5
+ * Shared between Cloud and Powch microservices.
6
+ */
7
+
8
+ import crypto from 'crypto';
9
+ import { UserSession, AuthProvider, CacheFirestore } from '@descix/cloud-core';
10
+
11
+ /**
12
+ * Create a unified user session for any authentication provider.
13
+ *
14
+ * @param {string} userId - DeSciX user ID (descix_*)
15
+ * @param {string} provider - Provider type (AuthProvider.DISCORD, AuthProvider.GOOGLE, AuthProvider.DESCIX, etc.)
16
+ * @param {number} expiresInSeconds - Session expiration in seconds (default: 86400 = 24 hours)
17
+ * @returns {Promise<string>} Session token
18
+ */
19
+ export async function createUserSession(userId, provider, expiresInSeconds = 86400) {
20
+ const sessionToken = crypto.randomUUID();
21
+ const session = new UserSession(
22
+ provider,
23
+ sessionToken,
24
+ null, // refresh_token
25
+ expiresInSeconds,
26
+ provider, // scope
27
+ 'Bearer',
28
+ null, // id_token
29
+ userId
30
+ );
31
+ await UserSession.to_firestore(session);
32
+ return sessionToken;
33
+ }
@@ -0,0 +1,259 @@
1
+ /**
2
+ * @descix/platform-api - Email Infrastructure
3
+ *
4
+ * Gmail API email sending using service account with domain-wide delegation.
5
+ * Used by both DeSciX_Cloud and DeSciX_Powch microservices.
6
+ *
7
+ * Config values are loaded at call time via getCloudConfig() from @descix/cloud-core.
8
+ * All config must be bootstrapped before calling any function here.
9
+ */
10
+
11
+ import { google } from 'googleapis';
12
+ import { getCloudConfig } from '@descix/cloud-core';
13
+
14
+ /**
15
+ * Base64 URL encode helper for Gmail API message encoding
16
+ * @param {string} input - Input string to encode
17
+ * @returns {string} Base64 URL-encoded string
18
+ */
19
+ export function base64UrlEncode(input) {
20
+ return Buffer.from(input)
21
+ .toString('base64')
22
+ .replace(/\+/g, '-')
23
+ .replace(/\//g, '_')
24
+ .replace(/=+$/, '');
25
+ }
26
+
27
+ /**
28
+ * Normalize email address (trim and lowercase)
29
+ * @param {string} email - Email address to normalize
30
+ * @returns {string|null} Normalized email or null if invalid
31
+ */
32
+ export function normalizeEmail(email) {
33
+ return email ? email.trim().toLowerCase() : null;
34
+ }
35
+
36
+ /**
37
+ * Core Gmail email sending function using service account with domain-wide delegation.
38
+ *
39
+ * Uses DESCIX_ROUTER_COMMUNITY_MANAGER as the impersonated user (sender).
40
+ * Uses GMAIL_SENDER_EMAIL as the Reply-To address.
41
+ *
42
+ * @param {string} toEmail - Recipient email address
43
+ * @param {string} subject - Email subject
44
+ * @param {string} body - Email body (plain text)
45
+ * @param {string} [fromEmail] - Optional sender email (defaults to DESCIX_ROUTER_COMMUNITY_MANAGER)
46
+ * @returns {Promise<void>}
47
+ */
48
+ export async function sendEmail(toEmail, subject, body, fromEmail = null) {
49
+ const utils = getCloudConfig();
50
+
51
+ // The sender/impersonated user - must be a real user in the domain with Gmail access
52
+ const impersonatedUser = fromEmail || utils.DESCIX_ROUTER_COMMUNITY_MANAGER;
53
+ // Reply-To address for user responses
54
+ const replyToEmail = utils.GMAIL_SENDER_EMAIL || impersonatedUser;
55
+
56
+ if (!impersonatedUser) {
57
+ throw new Error('Email sender is not configured. Please set DESCIX_ROUTER_COMMUNITY_MANAGER in config.');
58
+ }
59
+
60
+ // Get service account credentials from utils (loaded from Secret Manager)
61
+ const credentials = utils.GOOGLE_APPLICATION_CREDENTIALS;
62
+ if (!credentials) {
63
+ throw new Error('Service account credentials not available. Ensure elevated_credentials_descix secret is loaded.');
64
+ }
65
+
66
+ // Create JWT client with domain-wide delegation (impersonating the user)
67
+ const auth = new google.auth.JWT({
68
+ email: credentials.client_email,
69
+ key: credentials.private_key,
70
+ scopes: ['https://www.googleapis.com/auth/gmail.send'],
71
+ subject: impersonatedUser // Impersonate this user to send email
72
+ });
73
+
74
+ const gmail = google.gmail({ version: 'v1', auth });
75
+
76
+ // Build the email message with Reply-To header
77
+ const message = [
78
+ `From: DeSciX <${impersonatedUser}>`,
79
+ `To: ${toEmail}`,
80
+ `Reply-To: ${replyToEmail}`,
81
+ `Subject: ${subject}`,
82
+ 'Content-Type: text/plain; charset="UTF-8"',
83
+ '',
84
+ body
85
+ ].join('\n');
86
+
87
+ const raw = base64UrlEncode(message);
88
+
89
+ // Use impersonated user's email as userId
90
+ try {
91
+ await gmail.users.messages.send({
92
+ userId: impersonatedUser,
93
+ requestBody: { raw }
94
+ });
95
+ console.log(`Email sent successfully to ${toEmail} from ${impersonatedUser} (reply-to: ${replyToEmail})`);
96
+ } catch (error) {
97
+ console.error(`Failed to send email to ${toEmail}:`, error.message);
98
+ if (error.code === 403 || error.message?.includes('insufficient')) {
99
+ console.error(
100
+ `\n⚠️ Gmail API Permission Error. Ensure:\n` +
101
+ ` 1. Domain-wide delegation is enabled for service account: ${credentials.client_email}\n` +
102
+ ` 2. Scope 'https://www.googleapis.com/auth/gmail.send' is authorized in Google Workspace Admin\n` +
103
+ ` 3. User ${impersonatedUser} exists in the domain and has Gmail access\n`
104
+ );
105
+ }
106
+ throw error;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * High-level verification email sender.
112
+ * Sends a verification code email with standard formatting.
113
+ *
114
+ * @param {string} toEmail - Recipient email address
115
+ * @param {string} code - Verification code to send
116
+ * @param {number} [expiryMinutes=15] - Expiry time in minutes for the code
117
+ * @returns {Promise<void>}
118
+ */
119
+ export async function sendVerificationEmail(toEmail, code, expiryMinutes = 15) {
120
+ const subject = 'Your DeSciX verification code';
121
+ const body = `Your DeSciX verification code is: ${code}\n\nThis code expires in ${expiryMinutes} minutes.\nIf you did not request this, please ignore this email.`;
122
+ await sendEmail(toEmail, subject, body);
123
+ }
124
+
125
+ /**
126
+ * Send payment pending notification with deposit instructions.
127
+ *
128
+ * @param {Object} quote - The payment quote object
129
+ * @param {string} quote.quote_id - Unique quote identifier
130
+ * @param {string} quote.deposit_address - Deposit address
131
+ * @param {string} quote.amount_formatted - Formatted amount (e.g., "0.5 ETH")
132
+ * @param {string} quote.usd_amount_formatted - Formatted USD amount (e.g., "$10.00")
133
+ * @param {string} quote.chain_name - Chain name (e.g., "Polygon")
134
+ * @param {string} quote.expires_at - ISO timestamp when quote expires
135
+ * @param {string} recipientEmail - Recipient email address
136
+ * @returns {Promise<void>}
137
+ */
138
+ export async function sendPaymentPending(quote, recipientEmail) {
139
+ const utils = getCloudConfig();
140
+ const subject = `Payment Instructions - ${quote.usd_amount_formatted || `$${quote.usd_amount}`} via ${quote.chain_name || quote.chain}`;
141
+
142
+ const expiryDate = new Date(quote.expires_at);
143
+ const expiryStr = expiryDate.toLocaleString();
144
+
145
+ const body = `Hello,
146
+
147
+ You've initiated a crypto payment on DeSciX. Please complete your payment using the instructions below:
148
+
149
+ ═══════════════════════════════════════════════
150
+ PAYMENT DETAILS
151
+ ═══════════════════════════════════════════════
152
+
153
+ Quote ID: ${quote.quote_id}
154
+ Amount: ${quote.amount_formatted}
155
+ USD Value: ${quote.usd_amount_formatted || `$${quote.usd_amount}`}
156
+ Chain: ${quote.chain_name || quote.chain?.toUpperCase()}
157
+
158
+ DEPOSIT ADDRESS:
159
+ ${quote.deposit_address}
160
+
161
+ ⚠️ IMPORTANT: Send exactly ${quote.amount_formatted} to the address above.
162
+ Sending the wrong amount may result in processing issues.
163
+
164
+ Expires: ${expiryStr}
165
+
166
+ ═══════════════════════════════════════════════
167
+
168
+ Once your payment is confirmed on the blockchain, we'll send you a confirmation email.
169
+
170
+ If you did not initiate this payment, please ignore this email.
171
+
172
+ — The DeSciX Team
173
+ `;
174
+
175
+ // Send to user
176
+ await sendEmail(recipientEmail, subject, body);
177
+
178
+ // CC admin group if configured
179
+ const adminGroup = utils.DESCIX_ADMIN_GROUP;
180
+ if (adminGroup) {
181
+ try {
182
+ await sendEmail(adminGroup, `[ADMIN CC] ${subject}`, `Payment pending for: ${recipientEmail}\n\n${body}`);
183
+ } catch (error) {
184
+ console.warn(`Failed to send admin CC email: ${error.message}`);
185
+ }
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Send payment confirmation notification.
191
+ *
192
+ * @param {Object} quote - The fulfilled quote object
193
+ * @param {string} quote.quote_id - Unique quote identifier
194
+ * @param {string} quote.usd_amount - USD amount
195
+ * @param {string} quote.chain - Chain identifier
196
+ * @param {string} quote.payment_tx_hash - Transaction hash
197
+ * @param {Object} fulfillment - Fulfillment details
198
+ * @param {string} fulfillment.type - Fulfillment type (usdcx_credit or token_mint)
199
+ * @param {number} [fulfillment.usdcx_credited] - USDCX amount credited
200
+ * @param {number} [fulfillment.tokens_minted] - Tokens minted
201
+ * @param {string} [fulfillment.token_symbol] - Token symbol
202
+ * @param {string} recipientEmail - Recipient email address
203
+ * @returns {Promise<void>}
204
+ */
205
+ export async function sendPaymentConfirmation(quote, fulfillment, recipientEmail) {
206
+ const utils = getCloudConfig();
207
+ const usdAmountFormatted = quote.usd_amount_formatted || `$${quote.usd_amount}`;
208
+ const chainName = quote.chain_name || quote.chain?.toUpperCase();
209
+
210
+ let subject, creditsText;
211
+
212
+ if (fulfillment.type === 'usdcx_credit') {
213
+ subject = `Payment Confirmed - ${usdAmountFormatted} USDCX Credited`;
214
+ creditsText = `USDCX Credited: ${fulfillment.usdcx_credited?.toFixed(2) || quote.usd_amount}`;
215
+ } else if (fulfillment.type === 'token_mint') {
216
+ subject = `Payment Confirmed - ${fulfillment.tokens_minted} ${fulfillment.token_symbol} Tokens`;
217
+ creditsText = `Tokens Received: ${fulfillment.tokens_minted} ${fulfillment.token_symbol}`;
218
+ } else {
219
+ subject = `Payment Confirmed - ${usdAmountFormatted}`;
220
+ creditsText = `Amount: ${usdAmountFormatted}`;
221
+ }
222
+
223
+ const body = `Hello,
224
+
225
+ Your crypto payment has been confirmed!
226
+
227
+ ═══════════════════════════════════════════════
228
+ PAYMENT CONFIRMATION
229
+ ═══════════════════════════════════════════════
230
+
231
+ Quote ID: ${quote.quote_id}
232
+ Status: CONFIRMED
233
+ Chain: ${chainName}
234
+ ${creditsText}
235
+
236
+ ${quote.payment_tx_hash ? `Transaction: ${quote.payment_tx_hash}` : ''}
237
+
238
+ ═══════════════════════════════════════════════
239
+
240
+ Your account has been updated with the purchased credits/tokens.
241
+
242
+ Thank you for using DeSciX!
243
+
244
+ — The DeSciX Team
245
+ `;
246
+
247
+ // Send to user
248
+ await sendEmail(recipientEmail, subject, body);
249
+
250
+ // CC admin group if configured
251
+ const adminGroup = utils.DESCIX_ADMIN_GROUP;
252
+ if (adminGroup) {
253
+ try {
254
+ await sendEmail(adminGroup, `[ADMIN CC] ${subject}`, `Payment confirmed for: ${recipientEmail}\n\n${body}`);
255
+ } catch (error) {
256
+ console.warn(`Failed to send admin CC email: ${error.message}`);
257
+ }
258
+ }
259
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * @descix/platform-api - Entitlements
3
+ *
4
+ * Purchase verification, community membership checks, and product registry utilities.
5
+ * Shared between Cloud and Powch microservices.
6
+ */
7
+
8
+ import { CacheFirestore } from '@descix/cloud-core';
9
+
10
+ /**
11
+ * Error thrown when an app_id cannot be resolved to a registered Products entry.
12
+ *
13
+ * Carries an HTTP-mappable statusCode (404) and a stable machine-readable code so
14
+ * the apiFront catch-all can surface a clean client error instead of an opaque 500.
15
+ * The message names only the app_id and the deployment env — no internals — so it is
16
+ * safe to return to clients even in production.
17
+ *
18
+ * Common cause: a chat/RAG/KB query targeting a DEV-only app against a prod backend
19
+ * (or any wrong-env mistake). A clean 404 makes that misconfiguration self-evident.
20
+ */
21
+ export class AppNotFoundError extends Error {
22
+ constructor(appId, env) {
23
+ const envLabel = env || 'unknown';
24
+ super(`app "${appId}" is not registered in env ${envLabel}`);
25
+ this.name = 'AppNotFoundError';
26
+ this.code = 'APP_NOT_FOUND';
27
+ this.statusCode = 404;
28
+ this.app_id = appId;
29
+ this.env = envLabel;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Hydrate community_id from the Products registry when missing.
35
+ *
36
+ * The Products/{app_id} document is the canonical O(1) registry entry.
37
+ * app_id is globally unique; community_id is stored metadata in the doc.
38
+ * This function mutates params.community_id in-place.
39
+ *
40
+ * Invariant: Never trust a client-provided community_id.
41
+ * Security boundaries (Pinecone namespace, entitlement checks) must always
42
+ * call this to re-derive community_id from the Products registry.
43
+ *
44
+ * Resolution is authoritative and explicit (no silent default — anti-pattern #7):
45
+ * - If app_id has no Products/{app_id} doc (or no resolvable community_id in it),
46
+ * throw AppNotFoundError (HTTP 404). This covers the wrong-env / nonexistent-app
47
+ * case for every chat/RAG/KB query path, all of which funnel through here.
48
+ * - Genuine infrastructure errors (Firestore unreachable, etc.) are re-thrown as-is
49
+ * so they surface as 500s — not masked as "app not found".
50
+ *
51
+ * @param {Object} params - Mutable params object with app_id; sets community_id if missing
52
+ * @returns {Promise<void>}
53
+ * @throws {AppNotFoundError} when app_id is not registered in the current env
54
+ */
55
+ export async function hydrateCommunityIdFromProducts(params) {
56
+ if (!params.app_id || params.community_id) return;
57
+
58
+ let productDoc;
59
+ try {
60
+ const db = new CacheFirestore();
61
+ productDoc = await db.db.collection('Products').doc(params.app_id).get();
62
+ } catch (err) {
63
+ // Infrastructure failure (e.g. Firestore unreachable) — NOT a missing app.
64
+ // Re-throw so it surfaces as a 500 rather than a misleading 404.
65
+ console.error(`[hydrateCommunityIdFromProducts] Firestore error resolving '${params.app_id}': ${err.message}`);
66
+ throw err;
67
+ }
68
+
69
+ if (productDoc.exists) {
70
+ const productData = productDoc.data();
71
+ if (productData.community_id) {
72
+ params.community_id = productData.community_id;
73
+ return;
74
+ }
75
+ const match = productData.productPath?.match(/Community\/([^/]+)/);
76
+ if (match) {
77
+ params.community_id = match[1];
78
+ return;
79
+ }
80
+ }
81
+
82
+ // App is not registered in this environment (or its Products doc is malformed).
83
+ // Surface a clean, structured 404 instead of letting an undefined community_id
84
+ // bubble into an opaque downstream 500.
85
+ throw new AppNotFoundError(params.app_id, process.env.DEPLOY_ENV);
86
+ }