@hasna/microservices 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/bin/index.js +63 -0
  2. package/bin/mcp.js +63 -0
  3. package/dist/index.js +63 -0
  4. package/microservices/microservice-ads/package.json +27 -0
  5. package/microservices/microservice-ads/src/cli/index.ts +605 -0
  6. package/microservices/microservice-ads/src/db/campaigns.ts +797 -0
  7. package/microservices/microservice-ads/src/db/database.ts +93 -0
  8. package/microservices/microservice-ads/src/db/migrations.ts +60 -0
  9. package/microservices/microservice-ads/src/index.ts +39 -0
  10. package/microservices/microservice-ads/src/mcp/index.ts +480 -0
  11. package/microservices/microservice-contracts/package.json +27 -0
  12. package/microservices/microservice-contracts/src/cli/index.ts +770 -0
  13. package/microservices/microservice-contracts/src/db/contracts.ts +925 -0
  14. package/microservices/microservice-contracts/src/db/database.ts +93 -0
  15. package/microservices/microservice-contracts/src/db/migrations.ts +141 -0
  16. package/microservices/microservice-contracts/src/index.ts +43 -0
  17. package/microservices/microservice-contracts/src/mcp/index.ts +617 -0
  18. package/microservices/microservice-domains/package.json +27 -0
  19. package/microservices/microservice-domains/src/cli/index.ts +691 -0
  20. package/microservices/microservice-domains/src/db/database.ts +93 -0
  21. package/microservices/microservice-domains/src/db/domains.ts +1164 -0
  22. package/microservices/microservice-domains/src/db/migrations.ts +60 -0
  23. package/microservices/microservice-domains/src/index.ts +65 -0
  24. package/microservices/microservice-domains/src/mcp/index.ts +536 -0
  25. package/microservices/microservice-hiring/package.json +27 -0
  26. package/microservices/microservice-hiring/src/cli/index.ts +741 -0
  27. package/microservices/microservice-hiring/src/db/database.ts +93 -0
  28. package/microservices/microservice-hiring/src/db/hiring.ts +1085 -0
  29. package/microservices/microservice-hiring/src/db/migrations.ts +89 -0
  30. package/microservices/microservice-hiring/src/index.ts +80 -0
  31. package/microservices/microservice-hiring/src/lib/scoring.ts +206 -0
  32. package/microservices/microservice-hiring/src/mcp/index.ts +709 -0
  33. package/microservices/microservice-payments/package.json +27 -0
  34. package/microservices/microservice-payments/src/cli/index.ts +609 -0
  35. package/microservices/microservice-payments/src/db/database.ts +93 -0
  36. package/microservices/microservice-payments/src/db/migrations.ts +81 -0
  37. package/microservices/microservice-payments/src/db/payments.ts +1204 -0
  38. package/microservices/microservice-payments/src/index.ts +51 -0
  39. package/microservices/microservice-payments/src/mcp/index.ts +683 -0
  40. package/microservices/microservice-payroll/package.json +27 -0
  41. package/microservices/microservice-payroll/src/cli/index.ts +643 -0
  42. package/microservices/microservice-payroll/src/db/database.ts +93 -0
  43. package/microservices/microservice-payroll/src/db/migrations.ts +95 -0
  44. package/microservices/microservice-payroll/src/db/payroll.ts +1377 -0
  45. package/microservices/microservice-payroll/src/index.ts +48 -0
  46. package/microservices/microservice-payroll/src/mcp/index.ts +666 -0
  47. package/microservices/microservice-shipping/package.json +27 -0
  48. package/microservices/microservice-shipping/src/cli/index.ts +606 -0
  49. package/microservices/microservice-shipping/src/db/database.ts +93 -0
  50. package/microservices/microservice-shipping/src/db/migrations.ts +69 -0
  51. package/microservices/microservice-shipping/src/db/shipping.ts +1093 -0
  52. package/microservices/microservice-shipping/src/index.ts +53 -0
  53. package/microservices/microservice-shipping/src/mcp/index.ts +533 -0
  54. package/microservices/microservice-social/package.json +27 -0
  55. package/microservices/microservice-social/src/cli/index.ts +689 -0
  56. package/microservices/microservice-social/src/db/database.ts +93 -0
  57. package/microservices/microservice-social/src/db/migrations.ts +88 -0
  58. package/microservices/microservice-social/src/db/social.ts +1046 -0
  59. package/microservices/microservice-social/src/index.ts +46 -0
  60. package/microservices/microservice-social/src/mcp/index.ts +655 -0
  61. package/microservices/microservice-subscriptions/package.json +27 -0
  62. package/microservices/microservice-subscriptions/src/cli/index.ts +715 -0
  63. package/microservices/microservice-subscriptions/src/db/database.ts +93 -0
  64. package/microservices/microservice-subscriptions/src/db/migrations.ts +125 -0
  65. package/microservices/microservice-subscriptions/src/db/subscriptions.ts +1256 -0
  66. package/microservices/microservice-subscriptions/src/index.ts +41 -0
  67. package/microservices/microservice-subscriptions/src/mcp/index.ts +631 -0
  68. package/package.json +1 -1
@@ -0,0 +1,1164 @@
1
+ /**
2
+ * Domain, DNS record, and alert CRUD operations
3
+ */
4
+
5
+ import { getDatabase } from "./database.js";
6
+ import { execSync } from "node:child_process";
7
+
8
+ // --- Domain types ---
9
+
10
+ export interface Domain {
11
+ id: string;
12
+ name: string;
13
+ registrar: string | null;
14
+ status: "active" | "expired" | "transferring" | "redemption";
15
+ registered_at: string | null;
16
+ expires_at: string | null;
17
+ auto_renew: boolean;
18
+ nameservers: string[];
19
+ whois: Record<string, unknown>;
20
+ ssl_expires_at: string | null;
21
+ ssl_issuer: string | null;
22
+ notes: string | null;
23
+ metadata: Record<string, unknown>;
24
+ created_at: string;
25
+ updated_at: string;
26
+ }
27
+
28
+ interface DomainRow {
29
+ id: string;
30
+ name: string;
31
+ registrar: string | null;
32
+ status: string;
33
+ registered_at: string | null;
34
+ expires_at: string | null;
35
+ auto_renew: number;
36
+ nameservers: string;
37
+ whois: string;
38
+ ssl_expires_at: string | null;
39
+ ssl_issuer: string | null;
40
+ notes: string | null;
41
+ metadata: string;
42
+ created_at: string;
43
+ updated_at: string;
44
+ }
45
+
46
+ function rowToDomain(row: DomainRow): Domain {
47
+ return {
48
+ ...row,
49
+ status: row.status as Domain["status"],
50
+ auto_renew: row.auto_renew === 1,
51
+ nameservers: JSON.parse(row.nameservers || "[]"),
52
+ whois: JSON.parse(row.whois || "{}"),
53
+ metadata: JSON.parse(row.metadata || "{}"),
54
+ };
55
+ }
56
+
57
+ // --- DNS Record types ---
58
+
59
+ export interface DnsRecord {
60
+ id: string;
61
+ domain_id: string;
62
+ type: "A" | "AAAA" | "CNAME" | "MX" | "TXT" | "NS" | "SRV";
63
+ name: string;
64
+ value: string;
65
+ ttl: number;
66
+ priority: number | null;
67
+ created_at: string;
68
+ }
69
+
70
+ interface DnsRecordRow {
71
+ id: string;
72
+ domain_id: string;
73
+ type: string;
74
+ name: string;
75
+ value: string;
76
+ ttl: number;
77
+ priority: number | null;
78
+ created_at: string;
79
+ }
80
+
81
+ function rowToDnsRecord(row: DnsRecordRow): DnsRecord {
82
+ return {
83
+ ...row,
84
+ type: row.type as DnsRecord["type"],
85
+ };
86
+ }
87
+
88
+ // --- Alert types ---
89
+
90
+ export interface Alert {
91
+ id: string;
92
+ domain_id: string;
93
+ type: "expiry" | "ssl_expiry" | "dns_change";
94
+ trigger_days_before: number | null;
95
+ sent_at: string | null;
96
+ created_at: string;
97
+ }
98
+
99
+ interface AlertRow {
100
+ id: string;
101
+ domain_id: string;
102
+ type: string;
103
+ trigger_days_before: number | null;
104
+ sent_at: string | null;
105
+ created_at: string;
106
+ }
107
+
108
+ function rowToAlert(row: AlertRow): Alert {
109
+ return {
110
+ ...row,
111
+ type: row.type as Alert["type"],
112
+ };
113
+ }
114
+
115
+ // ============================================================
116
+ // Domain CRUD
117
+ // ============================================================
118
+
119
+ export interface CreateDomainInput {
120
+ name: string;
121
+ registrar?: string;
122
+ status?: Domain["status"];
123
+ registered_at?: string;
124
+ expires_at?: string;
125
+ auto_renew?: boolean;
126
+ nameservers?: string[];
127
+ whois?: Record<string, unknown>;
128
+ ssl_expires_at?: string;
129
+ ssl_issuer?: string;
130
+ notes?: string;
131
+ metadata?: Record<string, unknown>;
132
+ }
133
+
134
+ export function createDomain(input: CreateDomainInput): Domain {
135
+ const db = getDatabase();
136
+ const id = crypto.randomUUID();
137
+ const nameservers = JSON.stringify(input.nameservers || []);
138
+ const whois = JSON.stringify(input.whois || {});
139
+ const metadata = JSON.stringify(input.metadata || {});
140
+
141
+ db.prepare(
142
+ `INSERT INTO domains (id, name, registrar, status, registered_at, expires_at, auto_renew, nameservers, whois, ssl_expires_at, ssl_issuer, notes, metadata)
143
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
144
+ ).run(
145
+ id,
146
+ input.name,
147
+ input.registrar || null,
148
+ input.status || "active",
149
+ input.registered_at || null,
150
+ input.expires_at || null,
151
+ input.auto_renew !== undefined ? (input.auto_renew ? 1 : 0) : 1,
152
+ nameservers,
153
+ whois,
154
+ input.ssl_expires_at || null,
155
+ input.ssl_issuer || null,
156
+ input.notes || null,
157
+ metadata
158
+ );
159
+
160
+ return getDomain(id)!;
161
+ }
162
+
163
+ export function getDomain(id: string): Domain | null {
164
+ const db = getDatabase();
165
+ const row = db.prepare("SELECT * FROM domains WHERE id = ?").get(id) as DomainRow | null;
166
+ return row ? rowToDomain(row) : null;
167
+ }
168
+
169
+ export interface ListDomainsOptions {
170
+ search?: string;
171
+ status?: Domain["status"];
172
+ registrar?: string;
173
+ limit?: number;
174
+ offset?: number;
175
+ }
176
+
177
+ export function listDomains(options: ListDomainsOptions = {}): Domain[] {
178
+ const db = getDatabase();
179
+ const conditions: string[] = [];
180
+ const params: unknown[] = [];
181
+
182
+ if (options.search) {
183
+ conditions.push("(name LIKE ? OR registrar LIKE ? OR notes LIKE ?)");
184
+ const q = `%${options.search}%`;
185
+ params.push(q, q, q);
186
+ }
187
+
188
+ if (options.status) {
189
+ conditions.push("status = ?");
190
+ params.push(options.status);
191
+ }
192
+
193
+ if (options.registrar) {
194
+ conditions.push("registrar = ?");
195
+ params.push(options.registrar);
196
+ }
197
+
198
+ let sql = "SELECT * FROM domains";
199
+ if (conditions.length > 0) {
200
+ sql += " WHERE " + conditions.join(" AND ");
201
+ }
202
+ sql += " ORDER BY name";
203
+
204
+ if (options.limit) {
205
+ sql += " LIMIT ?";
206
+ params.push(options.limit);
207
+ }
208
+ if (options.offset) {
209
+ sql += " OFFSET ?";
210
+ params.push(options.offset);
211
+ }
212
+
213
+ const rows = db.prepare(sql).all(...params) as DomainRow[];
214
+ return rows.map(rowToDomain);
215
+ }
216
+
217
+ export interface UpdateDomainInput {
218
+ name?: string;
219
+ registrar?: string;
220
+ status?: Domain["status"];
221
+ registered_at?: string;
222
+ expires_at?: string;
223
+ auto_renew?: boolean;
224
+ nameservers?: string[];
225
+ whois?: Record<string, unknown>;
226
+ ssl_expires_at?: string;
227
+ ssl_issuer?: string;
228
+ notes?: string;
229
+ metadata?: Record<string, unknown>;
230
+ }
231
+
232
+ export function updateDomain(id: string, input: UpdateDomainInput): Domain | null {
233
+ const db = getDatabase();
234
+ const existing = getDomain(id);
235
+ if (!existing) return null;
236
+
237
+ const sets: string[] = [];
238
+ const params: unknown[] = [];
239
+
240
+ if (input.name !== undefined) {
241
+ sets.push("name = ?");
242
+ params.push(input.name);
243
+ }
244
+ if (input.registrar !== undefined) {
245
+ sets.push("registrar = ?");
246
+ params.push(input.registrar);
247
+ }
248
+ if (input.status !== undefined) {
249
+ sets.push("status = ?");
250
+ params.push(input.status);
251
+ }
252
+ if (input.registered_at !== undefined) {
253
+ sets.push("registered_at = ?");
254
+ params.push(input.registered_at);
255
+ }
256
+ if (input.expires_at !== undefined) {
257
+ sets.push("expires_at = ?");
258
+ params.push(input.expires_at);
259
+ }
260
+ if (input.auto_renew !== undefined) {
261
+ sets.push("auto_renew = ?");
262
+ params.push(input.auto_renew ? 1 : 0);
263
+ }
264
+ if (input.nameservers !== undefined) {
265
+ sets.push("nameservers = ?");
266
+ params.push(JSON.stringify(input.nameservers));
267
+ }
268
+ if (input.whois !== undefined) {
269
+ sets.push("whois = ?");
270
+ params.push(JSON.stringify(input.whois));
271
+ }
272
+ if (input.ssl_expires_at !== undefined) {
273
+ sets.push("ssl_expires_at = ?");
274
+ params.push(input.ssl_expires_at);
275
+ }
276
+ if (input.ssl_issuer !== undefined) {
277
+ sets.push("ssl_issuer = ?");
278
+ params.push(input.ssl_issuer);
279
+ }
280
+ if (input.notes !== undefined) {
281
+ sets.push("notes = ?");
282
+ params.push(input.notes);
283
+ }
284
+ if (input.metadata !== undefined) {
285
+ sets.push("metadata = ?");
286
+ params.push(JSON.stringify(input.metadata));
287
+ }
288
+
289
+ if (sets.length === 0) return existing;
290
+
291
+ sets.push("updated_at = datetime('now')");
292
+ params.push(id);
293
+
294
+ db.prepare(
295
+ `UPDATE domains SET ${sets.join(", ")} WHERE id = ?`
296
+ ).run(...params);
297
+
298
+ return getDomain(id);
299
+ }
300
+
301
+ export function deleteDomain(id: string): boolean {
302
+ const db = getDatabase();
303
+ const result = db.prepare("DELETE FROM domains WHERE id = ?").run(id);
304
+ return result.changes > 0;
305
+ }
306
+
307
+ export function countDomains(): number {
308
+ const db = getDatabase();
309
+ const row = db.prepare("SELECT COUNT(*) as count FROM domains").get() as { count: number };
310
+ return row.count;
311
+ }
312
+
313
+ export function searchDomains(query: string): Domain[] {
314
+ return listDomains({ search: query });
315
+ }
316
+
317
+ export function getByRegistrar(registrar: string): Domain[] {
318
+ return listDomains({ registrar });
319
+ }
320
+
321
+ export function listExpiring(days: number): Domain[] {
322
+ const db = getDatabase();
323
+ const rows = db
324
+ .prepare(
325
+ `SELECT * FROM domains
326
+ WHERE expires_at IS NOT NULL
327
+ AND expires_at <= datetime('now', '+' || ? || ' days')
328
+ AND expires_at >= datetime('now')
329
+ AND status = 'active'
330
+ ORDER BY expires_at`
331
+ )
332
+ .all(days) as DomainRow[];
333
+ return rows.map(rowToDomain);
334
+ }
335
+
336
+ export function listSslExpiring(days: number): Domain[] {
337
+ const db = getDatabase();
338
+ const rows = db
339
+ .prepare(
340
+ `SELECT * FROM domains
341
+ WHERE ssl_expires_at IS NOT NULL
342
+ AND ssl_expires_at <= datetime('now', '+' || ? || ' days')
343
+ AND ssl_expires_at >= datetime('now')
344
+ ORDER BY ssl_expires_at`
345
+ )
346
+ .all(days) as DomainRow[];
347
+ return rows.map(rowToDomain);
348
+ }
349
+
350
+ export interface DomainStats {
351
+ total: number;
352
+ active: number;
353
+ expired: number;
354
+ transferring: number;
355
+ redemption: number;
356
+ auto_renew_enabled: number;
357
+ expiring_30_days: number;
358
+ ssl_expiring_30_days: number;
359
+ }
360
+
361
+ export function getDomainStats(): DomainStats {
362
+ const db = getDatabase();
363
+
364
+ const total = (
365
+ db.prepare("SELECT COUNT(*) as count FROM domains").get() as { count: number }
366
+ ).count;
367
+
368
+ const active = (
369
+ db.prepare("SELECT COUNT(*) as count FROM domains WHERE status = 'active'").get() as { count: number }
370
+ ).count;
371
+
372
+ const expired = (
373
+ db.prepare("SELECT COUNT(*) as count FROM domains WHERE status = 'expired'").get() as { count: number }
374
+ ).count;
375
+
376
+ const transferring = (
377
+ db.prepare("SELECT COUNT(*) as count FROM domains WHERE status = 'transferring'").get() as { count: number }
378
+ ).count;
379
+
380
+ const redemption = (
381
+ db.prepare("SELECT COUNT(*) as count FROM domains WHERE status = 'redemption'").get() as { count: number }
382
+ ).count;
383
+
384
+ const auto_renew_enabled = (
385
+ db.prepare("SELECT COUNT(*) as count FROM domains WHERE auto_renew = 1").get() as { count: number }
386
+ ).count;
387
+
388
+ const expiring_30_days = listExpiring(30).length;
389
+ const ssl_expiring_30_days = listSslExpiring(30).length;
390
+
391
+ return {
392
+ total,
393
+ active,
394
+ expired,
395
+ transferring,
396
+ redemption,
397
+ auto_renew_enabled,
398
+ expiring_30_days,
399
+ ssl_expiring_30_days,
400
+ };
401
+ }
402
+
403
+ // ============================================================
404
+ // DNS Record CRUD
405
+ // ============================================================
406
+
407
+ export interface CreateDnsRecordInput {
408
+ domain_id: string;
409
+ type: DnsRecord["type"];
410
+ name: string;
411
+ value: string;
412
+ ttl?: number;
413
+ priority?: number;
414
+ }
415
+
416
+ export function createDnsRecord(input: CreateDnsRecordInput): DnsRecord {
417
+ const db = getDatabase();
418
+ const id = crypto.randomUUID();
419
+
420
+ db.prepare(
421
+ `INSERT INTO dns_records (id, domain_id, type, name, value, ttl, priority)
422
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
423
+ ).run(
424
+ id,
425
+ input.domain_id,
426
+ input.type,
427
+ input.name,
428
+ input.value,
429
+ input.ttl ?? 3600,
430
+ input.priority ?? null
431
+ );
432
+
433
+ return getDnsRecord(id)!;
434
+ }
435
+
436
+ export function getDnsRecord(id: string): DnsRecord | null {
437
+ const db = getDatabase();
438
+ const row = db.prepare("SELECT * FROM dns_records WHERE id = ?").get(id) as DnsRecordRow | null;
439
+ return row ? rowToDnsRecord(row) : null;
440
+ }
441
+
442
+ export function listDnsRecords(domainId: string, type?: DnsRecord["type"]): DnsRecord[] {
443
+ const db = getDatabase();
444
+ let sql = "SELECT * FROM dns_records WHERE domain_id = ?";
445
+ const params: unknown[] = [domainId];
446
+
447
+ if (type) {
448
+ sql += " AND type = ?";
449
+ params.push(type);
450
+ }
451
+
452
+ sql += " ORDER BY type, name";
453
+
454
+ const rows = db.prepare(sql).all(...params) as DnsRecordRow[];
455
+ return rows.map(rowToDnsRecord);
456
+ }
457
+
458
+ export interface UpdateDnsRecordInput {
459
+ type?: DnsRecord["type"];
460
+ name?: string;
461
+ value?: string;
462
+ ttl?: number;
463
+ priority?: number;
464
+ }
465
+
466
+ export function updateDnsRecord(id: string, input: UpdateDnsRecordInput): DnsRecord | null {
467
+ const db = getDatabase();
468
+ const existing = getDnsRecord(id);
469
+ if (!existing) return null;
470
+
471
+ const sets: string[] = [];
472
+ const params: unknown[] = [];
473
+
474
+ if (input.type !== undefined) {
475
+ sets.push("type = ?");
476
+ params.push(input.type);
477
+ }
478
+ if (input.name !== undefined) {
479
+ sets.push("name = ?");
480
+ params.push(input.name);
481
+ }
482
+ if (input.value !== undefined) {
483
+ sets.push("value = ?");
484
+ params.push(input.value);
485
+ }
486
+ if (input.ttl !== undefined) {
487
+ sets.push("ttl = ?");
488
+ params.push(input.ttl);
489
+ }
490
+ if (input.priority !== undefined) {
491
+ sets.push("priority = ?");
492
+ params.push(input.priority);
493
+ }
494
+
495
+ if (sets.length === 0) return existing;
496
+
497
+ params.push(id);
498
+
499
+ db.prepare(
500
+ `UPDATE dns_records SET ${sets.join(", ")} WHERE id = ?`
501
+ ).run(...params);
502
+
503
+ return getDnsRecord(id);
504
+ }
505
+
506
+ export function deleteDnsRecord(id: string): boolean {
507
+ const db = getDatabase();
508
+ const result = db.prepare("DELETE FROM dns_records WHERE id = ?").run(id);
509
+ return result.changes > 0;
510
+ }
511
+
512
+ // ============================================================
513
+ // Alert CRUD
514
+ // ============================================================
515
+
516
+ export interface CreateAlertInput {
517
+ domain_id: string;
518
+ type: Alert["type"];
519
+ trigger_days_before?: number;
520
+ }
521
+
522
+ export function createAlert(input: CreateAlertInput): Alert {
523
+ const db = getDatabase();
524
+ const id = crypto.randomUUID();
525
+
526
+ db.prepare(
527
+ `INSERT INTO alerts (id, domain_id, type, trigger_days_before)
528
+ VALUES (?, ?, ?, ?)`
529
+ ).run(id, input.domain_id, input.type, input.trigger_days_before ?? null);
530
+
531
+ return getAlert(id)!;
532
+ }
533
+
534
+ export function getAlert(id: string): Alert | null {
535
+ const db = getDatabase();
536
+ const row = db.prepare("SELECT * FROM alerts WHERE id = ?").get(id) as AlertRow | null;
537
+ return row ? rowToAlert(row) : null;
538
+ }
539
+
540
+ export function listAlerts(domainId: string): Alert[] {
541
+ const db = getDatabase();
542
+ const rows = db
543
+ .prepare("SELECT * FROM alerts WHERE domain_id = ? ORDER BY type, trigger_days_before")
544
+ .all(domainId) as AlertRow[];
545
+ return rows.map(rowToAlert);
546
+ }
547
+
548
+ export function deleteAlert(id: string): boolean {
549
+ const db = getDatabase();
550
+ const result = db.prepare("DELETE FROM alerts WHERE id = ?").run(id);
551
+ return result.changes > 0;
552
+ }
553
+
554
+ // ============================================================
555
+ // WHOIS Lookup
556
+ // ============================================================
557
+
558
+ export interface WhoisResult {
559
+ domain: string;
560
+ registrar: string | null;
561
+ expires_at: string | null;
562
+ nameservers: string[];
563
+ raw: string;
564
+ }
565
+
566
+ export function whoisLookup(domainName: string): WhoisResult {
567
+ let raw: string;
568
+ try {
569
+ raw = execSync(`whois ${domainName}`, { timeout: 15000, encoding: "utf-8" });
570
+ } catch (error: unknown) {
571
+ const err = error as { stdout?: string; stderr?: string };
572
+ raw = err.stdout || err.stderr || "";
573
+ if (!raw) throw new Error(`whois command failed for ${domainName}`);
574
+ }
575
+
576
+ const registrarMatch = raw.match(/Registrar:\s*(.+)/i) || raw.match(/registrar:\s*(.+)/i);
577
+ const registrar = registrarMatch ? registrarMatch[1].trim() : null;
578
+
579
+ const expiresMatch =
580
+ raw.match(/Registry Expiry Date:\s*(.+)/i) ||
581
+ raw.match(/Expir(?:y|ation) Date:\s*(.+)/i) ||
582
+ raw.match(/paid-till:\s*(.+)/i);
583
+ let expires_at: string | null = null;
584
+ if (expiresMatch) {
585
+ try {
586
+ expires_at = new Date(expiresMatch[1].trim()).toISOString();
587
+ } catch {
588
+ expires_at = expiresMatch[1].trim();
589
+ }
590
+ }
591
+
592
+ const nsMatches = raw.matchAll(/Name Server:\s*(.+)/gi);
593
+ const nameservers: string[] = [];
594
+ for (const m of nsMatches) {
595
+ const ns = m[1].trim().toLowerCase();
596
+ if (ns && !nameservers.includes(ns)) nameservers.push(ns);
597
+ }
598
+
599
+ // Update the DB record if a domain with this name exists
600
+ const db = getDatabase();
601
+ const row = db.prepare("SELECT id FROM domains WHERE name = ?").get(domainName) as { id: string } | null;
602
+ if (row) {
603
+ const updates: UpdateDomainInput = { whois: { raw } };
604
+ if (registrar) updates.registrar = registrar;
605
+ if (expires_at) updates.expires_at = expires_at;
606
+ if (nameservers.length > 0) updates.nameservers = nameservers;
607
+ updateDomain(row.id, updates);
608
+ }
609
+
610
+ return { domain: domainName, registrar, expires_at, nameservers, raw };
611
+ }
612
+
613
+ // ============================================================
614
+ // DNS Propagation Check
615
+ // ============================================================
616
+
617
+ const DNS_SERVERS = ["8.8.8.8", "1.1.1.1", "9.9.9.9", "208.67.222.222"];
618
+ const DNS_SERVER_NAMES: Record<string, string> = {
619
+ "8.8.8.8": "Google",
620
+ "1.1.1.1": "Cloudflare",
621
+ "9.9.9.9": "Quad9",
622
+ "208.67.222.222": "OpenDNS",
623
+ };
624
+
625
+ export interface DnsPropagationResult {
626
+ domain: string;
627
+ record_type: string;
628
+ servers: {
629
+ server: string;
630
+ name: string;
631
+ values: string[];
632
+ status: "ok" | "error";
633
+ error?: string;
634
+ }[];
635
+ consistent: boolean;
636
+ }
637
+
638
+ export function checkDnsPropagation(
639
+ domain: string,
640
+ recordType: string = "A"
641
+ ): DnsPropagationResult {
642
+ const servers: DnsPropagationResult["servers"] = [];
643
+
644
+ for (const server of DNS_SERVERS) {
645
+ try {
646
+ const output = execSync(
647
+ `dig @${server} ${domain} ${recordType} +short +time=5 +tries=1`,
648
+ { timeout: 10000, encoding: "utf-8" }
649
+ );
650
+ const values = output
651
+ .trim()
652
+ .split("\n")
653
+ .filter((l) => l.length > 0);
654
+ servers.push({
655
+ server,
656
+ name: DNS_SERVER_NAMES[server] || server,
657
+ values,
658
+ status: "ok",
659
+ });
660
+ } catch (error: unknown) {
661
+ servers.push({
662
+ server,
663
+ name: DNS_SERVER_NAMES[server] || server,
664
+ values: [],
665
+ status: "error",
666
+ error: error instanceof Error ? error.message : String(error),
667
+ });
668
+ }
669
+ }
670
+
671
+ // Check consistency: all servers with "ok" should have the same sorted values
672
+ const okServers = servers.filter((s) => s.status === "ok");
673
+ const consistent =
674
+ okServers.length > 0 &&
675
+ okServers.every(
676
+ (s) => JSON.stringify(s.values.sort()) === JSON.stringify(okServers[0].values.sort())
677
+ );
678
+
679
+ return { domain, record_type: recordType, servers, consistent };
680
+ }
681
+
682
+ // ============================================================
683
+ // SSL Certificate Check
684
+ // ============================================================
685
+
686
+ export interface SslCheckResult {
687
+ domain: string;
688
+ issuer: string | null;
689
+ expires_at: string | null;
690
+ subject: string | null;
691
+ error?: string;
692
+ }
693
+
694
+ export function checkSsl(domainName: string): SslCheckResult {
695
+ try {
696
+ const output = execSync(
697
+ `echo | openssl s_client -servername ${domainName} -connect ${domainName}:443 2>/dev/null | openssl x509 -noout -issuer -dates -subject 2>/dev/null`,
698
+ { timeout: 15000, encoding: "utf-8" }
699
+ );
700
+
701
+ const issuerMatch = output.match(/issuer\s*=\s*(.+)/i);
702
+ const notAfterMatch = output.match(/notAfter\s*=\s*(.+)/i);
703
+ const subjectMatch = output.match(/subject\s*=\s*(.+)/i);
704
+
705
+ const issuer = issuerMatch ? issuerMatch[1].trim() : null;
706
+ const subject = subjectMatch ? subjectMatch[1].trim() : null;
707
+ let expires_at: string | null = null;
708
+
709
+ if (notAfterMatch) {
710
+ try {
711
+ expires_at = new Date(notAfterMatch[1].trim()).toISOString();
712
+ } catch {
713
+ expires_at = notAfterMatch[1].trim();
714
+ }
715
+ }
716
+
717
+ // Update the DB record if exists
718
+ const db = getDatabase();
719
+ const row = db.prepare("SELECT id FROM domains WHERE name = ?").get(domainName) as { id: string } | null;
720
+ if (row) {
721
+ const updates: UpdateDomainInput = {};
722
+ if (expires_at) updates.ssl_expires_at = expires_at;
723
+ if (issuer) updates.ssl_issuer = issuer;
724
+ updateDomain(row.id, updates);
725
+ }
726
+
727
+ return { domain: domainName, issuer, expires_at, subject };
728
+ } catch (error: unknown) {
729
+ return {
730
+ domain: domainName,
731
+ issuer: null,
732
+ expires_at: null,
733
+ subject: null,
734
+ error: error instanceof Error ? error.message : String(error),
735
+ };
736
+ }
737
+ }
738
+
739
+ // ============================================================
740
+ // Zone File Export / Import
741
+ // ============================================================
742
+
743
+ export function exportZoneFile(domainId: string): string | null {
744
+ const domain = getDomain(domainId);
745
+ if (!domain) return null;
746
+
747
+ const records = listDnsRecords(domainId);
748
+ const lines: string[] = [];
749
+
750
+ lines.push(`; Zone file for ${domain.name}`);
751
+ lines.push(`; Exported at ${new Date().toISOString()}`);
752
+ lines.push(`$ORIGIN ${domain.name}.`);
753
+ lines.push(`$TTL 3600`);
754
+ lines.push("");
755
+
756
+ for (const r of records) {
757
+ const name = r.name === "@" ? domain.name + "." : r.name;
758
+ if (r.type === "MX" || r.type === "SRV") {
759
+ const priority = r.priority ?? 10;
760
+ lines.push(`${name}\t${r.ttl}\tIN\t${r.type}\t${priority}\t${r.value}`);
761
+ } else {
762
+ lines.push(`${name}\t${r.ttl}\tIN\t${r.type}\t${r.value}`);
763
+ }
764
+ }
765
+
766
+ return lines.join("\n") + "\n";
767
+ }
768
+
769
+ export interface ZoneImportResult {
770
+ imported: number;
771
+ skipped: number;
772
+ errors: string[];
773
+ records: DnsRecord[];
774
+ }
775
+
776
+ export function importZoneFile(domainId: string, content: string): ZoneImportResult | null {
777
+ const domain = getDomain(domainId);
778
+ if (!domain) return null;
779
+
780
+ const result: ZoneImportResult = { imported: 0, skipped: 0, errors: [], records: [] };
781
+ const lines = content.split("\n");
782
+ const validTypes = new Set(["A", "AAAA", "CNAME", "MX", "TXT", "NS", "SRV"]);
783
+
784
+ for (const rawLine of lines) {
785
+ const line = rawLine.trim();
786
+ if (!line || line.startsWith(";") || line.startsWith("$")) {
787
+ continue;
788
+ }
789
+
790
+ // Parse zone file line: name ttl class type [priority] value
791
+ const parts = line.split(/\s+/);
792
+ if (parts.length < 4) {
793
+ result.errors.push(`Could not parse line: ${line}`);
794
+ result.skipped++;
795
+ continue;
796
+ }
797
+
798
+ let name = parts[0];
799
+ let idx = 1;
800
+
801
+ // Skip optional TTL (numeric)
802
+ let ttl = 3600;
803
+ if (/^\d+$/.test(parts[idx])) {
804
+ ttl = parseInt(parts[idx]);
805
+ idx++;
806
+ }
807
+
808
+ // Skip class (IN)
809
+ if (parts[idx] && parts[idx].toUpperCase() === "IN") {
810
+ idx++;
811
+ }
812
+
813
+ const type = parts[idx]?.toUpperCase();
814
+ idx++;
815
+
816
+ if (!type || !validTypes.has(type)) {
817
+ result.errors.push(`Unknown record type '${type}' in: ${line}`);
818
+ result.skipped++;
819
+ continue;
820
+ }
821
+
822
+ let priority: number | undefined;
823
+ if (type === "MX" || type === "SRV") {
824
+ if (parts[idx] && /^\d+$/.test(parts[idx])) {
825
+ priority = parseInt(parts[idx]);
826
+ idx++;
827
+ }
828
+ }
829
+
830
+ const value = parts.slice(idx).join(" ");
831
+ if (!value) {
832
+ result.errors.push(`Missing value in: ${line}`);
833
+ result.skipped++;
834
+ continue;
835
+ }
836
+
837
+ // Normalize name: remove trailing dot, replace domain name with @
838
+ if (name.endsWith(".")) name = name.slice(0, -1);
839
+ if (name === domain.name || name === "") name = "@";
840
+
841
+ try {
842
+ const record = createDnsRecord({
843
+ domain_id: domainId,
844
+ type: type as DnsRecord["type"],
845
+ name,
846
+ value,
847
+ ttl,
848
+ priority,
849
+ });
850
+ result.records.push(record);
851
+ result.imported++;
852
+ } catch (error: unknown) {
853
+ result.errors.push(
854
+ `Failed to create record: ${error instanceof Error ? error.message : String(error)}`
855
+ );
856
+ result.skipped++;
857
+ }
858
+ }
859
+
860
+ return result;
861
+ }
862
+
863
+ // ============================================================
864
+ // Subdomain Discovery (crt.sh)
865
+ // ============================================================
866
+
867
+ export interface SubdomainResult {
868
+ domain: string;
869
+ subdomains: string[];
870
+ source: string;
871
+ error?: string;
872
+ }
873
+
874
+ export async function discoverSubdomains(domain: string): Promise<SubdomainResult> {
875
+ try {
876
+ const url = `https://crt.sh/?q=%25.${encodeURIComponent(domain)}&output=json`;
877
+ const response = await fetch(url, {
878
+ signal: AbortSignal.timeout(15000),
879
+ headers: { "User-Agent": "microservice-domains/0.0.1" },
880
+ });
881
+
882
+ if (!response.ok) {
883
+ return {
884
+ domain,
885
+ subdomains: [],
886
+ source: "crt.sh",
887
+ error: `crt.sh returned ${response.status}`,
888
+ };
889
+ }
890
+
891
+ const data = (await response.json()) as { common_name?: string; name_value?: string }[];
892
+ const subdomainSet = new Set<string>();
893
+
894
+ for (const entry of data) {
895
+ for (const field of [entry.common_name, entry.name_value]) {
896
+ if (!field) continue;
897
+ for (const name of field.split("\n")) {
898
+ const cleaned = name.trim().toLowerCase().replace(/^\*\./, "");
899
+ if (cleaned.endsWith(domain.toLowerCase()) && cleaned !== domain.toLowerCase()) {
900
+ subdomainSet.add(cleaned);
901
+ }
902
+ }
903
+ }
904
+ }
905
+
906
+ const subdomains = [...subdomainSet].sort();
907
+ return { domain, subdomains, source: "crt.sh" };
908
+ } catch (error: unknown) {
909
+ return {
910
+ domain,
911
+ subdomains: [],
912
+ source: "crt.sh",
913
+ error: error instanceof Error ? error.message : String(error),
914
+ };
915
+ }
916
+ }
917
+
918
+ // ============================================================
919
+ // DNS Validation
920
+ // ============================================================
921
+
922
+ export interface DnsValidationIssue {
923
+ type: "error" | "warning";
924
+ record_id?: string;
925
+ message: string;
926
+ }
927
+
928
+ export interface DnsValidationResult {
929
+ domain_id: string;
930
+ domain_name: string;
931
+ issues: DnsValidationIssue[];
932
+ valid: boolean;
933
+ }
934
+
935
+ export function validateDns(domainId: string): DnsValidationResult | null {
936
+ const domain = getDomain(domainId);
937
+ if (!domain) return null;
938
+
939
+ const records = listDnsRecords(domainId);
940
+ const issues: DnsValidationIssue[] = [];
941
+
942
+ // Group records by name
943
+ const byName = new Map<string, DnsRecord[]>();
944
+ for (const r of records) {
945
+ const key = r.name.toLowerCase();
946
+ if (!byName.has(key)) byName.set(key, []);
947
+ byName.get(key)!.push(r);
948
+ }
949
+
950
+ // Check: CNAME should not coexist with A or MX at the same name
951
+ for (const [name, recs] of byName) {
952
+ const hasCname = recs.some((r) => r.type === "CNAME");
953
+ const hasA = recs.some((r) => r.type === "A" || r.type === "AAAA");
954
+ const hasMx = recs.some((r) => r.type === "MX");
955
+ const hasNs = recs.some((r) => r.type === "NS");
956
+
957
+ if (hasCname && hasA) {
958
+ issues.push({
959
+ type: "error",
960
+ message: `CNAME record at '${name}' conflicts with A/AAAA record — CNAME cannot coexist with other record types`,
961
+ });
962
+ }
963
+ if (hasCname && hasMx) {
964
+ issues.push({
965
+ type: "error",
966
+ message: `CNAME record at '${name}' conflicts with MX record — CNAME cannot coexist with other record types`,
967
+ });
968
+ }
969
+ if (hasCname && hasNs) {
970
+ issues.push({
971
+ type: "error",
972
+ message: `CNAME record at '${name}' conflicts with NS record — CNAME cannot coexist with other record types`,
973
+ });
974
+ }
975
+ if (hasCname && recs.filter((r) => r.type === "CNAME").length > 1) {
976
+ issues.push({
977
+ type: "error",
978
+ message: `Multiple CNAME records at '${name}' — only one CNAME is allowed per name`,
979
+ });
980
+ }
981
+ }
982
+
983
+ // Check: Missing MX records for root domain (warning)
984
+ const rootRecords = byName.get("@") || [];
985
+ const hasMxAtRoot = rootRecords.some((r) => r.type === "MX");
986
+ if (!hasMxAtRoot && records.length > 0) {
987
+ issues.push({
988
+ type: "warning",
989
+ message: `No MX record found at root (@) — email delivery may not work for ${domain.name}`,
990
+ });
991
+ }
992
+
993
+ // Check: Orphan records — records pointing to names with no A/AAAA resolution
994
+ for (const r of records) {
995
+ if (r.type === "CNAME") {
996
+ const target = r.value.toLowerCase().replace(/\.$/, "");
997
+ // Check if target is within this domain and has no records
998
+ if (target.endsWith(domain.name.toLowerCase())) {
999
+ const targetName = target === domain.name.toLowerCase() ? "@" : target.replace(`.${domain.name.toLowerCase()}`, "");
1000
+ const targetRecords = byName.get(targetName.toLowerCase());
1001
+ if (!targetRecords || targetRecords.length === 0) {
1002
+ issues.push({
1003
+ type: "warning",
1004
+ record_id: r.id,
1005
+ message: `CNAME '${r.name}' points to '${r.value}' which has no records in this zone`,
1006
+ });
1007
+ }
1008
+ }
1009
+ }
1010
+ }
1011
+
1012
+ // Check: MX records should have priority
1013
+ for (const r of records) {
1014
+ if (r.type === "MX" && r.priority === null) {
1015
+ issues.push({
1016
+ type: "warning",
1017
+ record_id: r.id,
1018
+ message: `MX record '${r.name}' -> '${r.value}' has no priority set`,
1019
+ });
1020
+ }
1021
+ }
1022
+
1023
+ return {
1024
+ domain_id: domainId,
1025
+ domain_name: domain.name,
1026
+ issues,
1027
+ valid: issues.filter((i) => i.type === "error").length === 0,
1028
+ };
1029
+ }
1030
+
1031
+ // ============================================================
1032
+ // Portfolio Export
1033
+ // ============================================================
1034
+
1035
+ export function exportPortfolio(format: "csv" | "json" = "json"): string {
1036
+ const domains = listDomains();
1037
+
1038
+ if (format === "json") {
1039
+ return JSON.stringify(
1040
+ domains.map((d) => ({
1041
+ name: d.name,
1042
+ registrar: d.registrar,
1043
+ status: d.status,
1044
+ registered_at: d.registered_at,
1045
+ expires_at: d.expires_at,
1046
+ auto_renew: d.auto_renew,
1047
+ nameservers: d.nameservers,
1048
+ ssl_expires_at: d.ssl_expires_at,
1049
+ ssl_issuer: d.ssl_issuer,
1050
+ notes: d.notes,
1051
+ })),
1052
+ null,
1053
+ 2
1054
+ );
1055
+ }
1056
+
1057
+ // CSV format
1058
+ const headers = [
1059
+ "name",
1060
+ "registrar",
1061
+ "status",
1062
+ "registered_at",
1063
+ "expires_at",
1064
+ "auto_renew",
1065
+ "nameservers",
1066
+ "ssl_expires_at",
1067
+ "ssl_issuer",
1068
+ "notes",
1069
+ ];
1070
+ const rows = domains.map((d) =>
1071
+ [
1072
+ csvEscape(d.name),
1073
+ csvEscape(d.registrar || ""),
1074
+ csvEscape(d.status),
1075
+ csvEscape(d.registered_at || ""),
1076
+ csvEscape(d.expires_at || ""),
1077
+ d.auto_renew ? "true" : "false",
1078
+ csvEscape(d.nameservers.join("; ")),
1079
+ csvEscape(d.ssl_expires_at || ""),
1080
+ csvEscape(d.ssl_issuer || ""),
1081
+ csvEscape(d.notes || ""),
1082
+ ].join(",")
1083
+ );
1084
+
1085
+ return [headers.join(","), ...rows].join("\n") + "\n";
1086
+ }
1087
+
1088
+ function csvEscape(value: string): string {
1089
+ if (value.includes(",") || value.includes('"') || value.includes("\n")) {
1090
+ return `"${value.replace(/"/g, '""')}"`;
1091
+ }
1092
+ return value;
1093
+ }
1094
+
1095
+ // ============================================================
1096
+ // Bulk Domain Check
1097
+ // ============================================================
1098
+
1099
+ export interface BulkCheckResult {
1100
+ domain: string;
1101
+ domain_id: string;
1102
+ whois?: { registrar: string | null; expires_at: string | null; error?: string };
1103
+ ssl?: { issuer: string | null; expires_at: string | null; error?: string };
1104
+ dns_validation?: { valid: boolean; issue_count: number; errors: string[] };
1105
+ }
1106
+
1107
+ export function checkAllDomains(): BulkCheckResult[] {
1108
+ const domains = listDomains();
1109
+ const results: BulkCheckResult[] = [];
1110
+
1111
+ for (const domain of domains) {
1112
+ const result: BulkCheckResult = {
1113
+ domain: domain.name,
1114
+ domain_id: domain.id,
1115
+ };
1116
+
1117
+ // WHOIS check
1118
+ try {
1119
+ const whois = whoisLookup(domain.name);
1120
+ result.whois = {
1121
+ registrar: whois.registrar,
1122
+ expires_at: whois.expires_at,
1123
+ };
1124
+ } catch (error: unknown) {
1125
+ result.whois = {
1126
+ registrar: null,
1127
+ expires_at: null,
1128
+ error: error instanceof Error ? error.message : String(error),
1129
+ };
1130
+ }
1131
+
1132
+ // SSL check
1133
+ const ssl = checkSsl(domain.name);
1134
+ result.ssl = {
1135
+ issuer: ssl.issuer,
1136
+ expires_at: ssl.expires_at,
1137
+ error: ssl.error,
1138
+ };
1139
+
1140
+ // DNS validation
1141
+ const validation = validateDns(domain.id);
1142
+ if (validation) {
1143
+ result.dns_validation = {
1144
+ valid: validation.valid,
1145
+ issue_count: validation.issues.length,
1146
+ errors: validation.issues.map((i) => `[${i.type}] ${i.message}`),
1147
+ };
1148
+ }
1149
+
1150
+ results.push(result);
1151
+ }
1152
+
1153
+ return results;
1154
+ }
1155
+
1156
+ // ============================================================
1157
+ // Helper: find domain by name (used by CLI to resolve names to IDs)
1158
+ // ============================================================
1159
+
1160
+ export function getDomainByName(name: string): Domain | null {
1161
+ const db = getDatabase();
1162
+ const row = db.prepare("SELECT * FROM domains WHERE name = ?").get(name) as DomainRow | null;
1163
+ return row ? rowToDomain(row) : null;
1164
+ }