@wopr-network/platform-core 1.68.0 → 1.70.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/dist/backup/types.d.ts +1 -1
- package/dist/db/schema/pool-config.d.ts +41 -0
- package/dist/db/schema/pool-config.js +5 -0
- package/dist/db/schema/pool-instances.d.ts +126 -0
- package/dist/db/schema/pool-instances.js +10 -0
- package/dist/server/__tests__/build-container.test.d.ts +1 -0
- package/dist/server/__tests__/build-container.test.js +339 -0
- package/dist/server/__tests__/container.test.d.ts +1 -0
- package/dist/server/__tests__/container.test.js +173 -0
- package/dist/server/__tests__/lifecycle.test.d.ts +1 -0
- package/dist/server/__tests__/lifecycle.test.js +90 -0
- package/dist/server/__tests__/mount-routes.test.d.ts +1 -0
- package/dist/server/__tests__/mount-routes.test.js +151 -0
- package/dist/server/boot-config.d.ts +51 -0
- package/dist/server/boot-config.js +7 -0
- package/dist/server/container.d.ts +97 -0
- package/dist/server/container.js +148 -0
- package/dist/server/index.d.ts +33 -0
- package/dist/server/index.js +66 -0
- package/dist/server/lifecycle.d.ts +25 -0
- package/dist/server/lifecycle.js +56 -0
- package/dist/server/middleware/__tests__/admin-auth.test.d.ts +1 -0
- package/dist/server/middleware/__tests__/admin-auth.test.js +59 -0
- package/dist/server/middleware/__tests__/tenant-proxy.test.d.ts +1 -0
- package/dist/server/middleware/__tests__/tenant-proxy.test.js +268 -0
- package/dist/server/middleware/admin-auth.d.ts +18 -0
- package/dist/server/middleware/admin-auth.js +38 -0
- package/dist/server/middleware/tenant-proxy.d.ts +56 -0
- package/dist/server/middleware/tenant-proxy.js +162 -0
- package/dist/server/mount-routes.d.ts +30 -0
- package/dist/server/mount-routes.js +74 -0
- package/dist/server/routes/__tests__/admin.test.d.ts +1 -0
- package/dist/server/routes/__tests__/admin.test.js +267 -0
- package/dist/server/routes/__tests__/crypto-webhook.test.d.ts +1 -0
- package/dist/server/routes/__tests__/crypto-webhook.test.js +137 -0
- package/dist/server/routes/__tests__/provision-webhook.test.d.ts +1 -0
- package/dist/server/routes/__tests__/provision-webhook.test.js +212 -0
- package/dist/server/routes/__tests__/stripe-webhook.test.d.ts +1 -0
- package/dist/server/routes/__tests__/stripe-webhook.test.js +65 -0
- package/dist/server/routes/admin.d.ts +129 -0
- package/dist/server/routes/admin.js +294 -0
- package/dist/server/routes/crypto-webhook.d.ts +23 -0
- package/dist/server/routes/crypto-webhook.js +82 -0
- package/dist/server/routes/provision-webhook.d.ts +38 -0
- package/dist/server/routes/provision-webhook.js +160 -0
- package/dist/server/routes/stripe-webhook.d.ts +10 -0
- package/dist/server/routes/stripe-webhook.js +29 -0
- package/dist/server/services/hot-pool-claim.d.ts +30 -0
- package/dist/server/services/hot-pool-claim.js +92 -0
- package/dist/server/services/hot-pool.d.ts +25 -0
- package/dist/server/services/hot-pool.js +129 -0
- package/dist/server/services/pool-repository.d.ts +44 -0
- package/dist/server/services/pool-repository.js +72 -0
- package/dist/server/test-container.d.ts +15 -0
- package/dist/server/test-container.js +103 -0
- package/dist/trpc/auth-helpers.d.ts +17 -0
- package/dist/trpc/auth-helpers.js +26 -0
- package/dist/trpc/container-factories.d.ts +300 -0
- package/dist/trpc/container-factories.js +80 -0
- package/dist/trpc/index.d.ts +2 -0
- package/dist/trpc/index.js +2 -0
- package/drizzle/migrations/0025_hot_pool_tables.sql +29 -0
- package/package.json +5 -1
- package/src/db/schema/pool-config.ts +6 -0
- package/src/db/schema/pool-instances.ts +11 -0
- package/src/server/__tests__/build-container.test.ts +402 -0
- package/src/server/__tests__/container.test.ts +207 -0
- package/src/server/__tests__/lifecycle.test.ts +106 -0
- package/src/server/__tests__/mount-routes.test.ts +169 -0
- package/src/server/boot-config.ts +84 -0
- package/src/server/container.ts +264 -0
- package/src/server/index.ts +92 -0
- package/src/server/lifecycle.ts +72 -0
- package/src/server/middleware/__tests__/admin-auth.test.ts +67 -0
- package/src/server/middleware/__tests__/tenant-proxy.test.ts +308 -0
- package/src/server/middleware/admin-auth.ts +51 -0
- package/src/server/middleware/tenant-proxy.ts +192 -0
- package/src/server/mount-routes.ts +113 -0
- package/src/server/routes/__tests__/admin.test.ts +320 -0
- package/src/server/routes/__tests__/crypto-webhook.test.ts +167 -0
- package/src/server/routes/__tests__/provision-webhook.test.ts +323 -0
- package/src/server/routes/__tests__/stripe-webhook.test.ts +73 -0
- package/src/server/routes/admin.ts +360 -0
- package/src/server/routes/crypto-webhook.ts +110 -0
- package/src/server/routes/provision-webhook.ts +212 -0
- package/src/server/routes/stripe-webhook.ts +36 -0
- package/src/server/services/hot-pool-claim.ts +130 -0
- package/src/server/services/hot-pool.ts +174 -0
- package/src/server/services/pool-repository.ts +107 -0
- package/src/server/test-container.ts +120 -0
- package/src/trpc/auth-helpers.ts +28 -0
- package/src/trpc/container-factories.ts +114 -0
- package/src/trpc/index.ts +9 -0
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PlatformContainer — the central DI container for platform-core.
|
|
3
|
+
*
|
|
4
|
+
* Products compose a container at boot time, enabling only the feature
|
|
5
|
+
* slices they need. Nullable sub-containers (fleet, crypto, stripe,
|
|
6
|
+
* gateway, hotPool) let each product opt in without pulling unused deps.
|
|
7
|
+
*/
|
|
8
|
+
// ---------------------------------------------------------------------------
|
|
9
|
+
// buildContainer — construct a PlatformContainer from a BootConfig
|
|
10
|
+
// ---------------------------------------------------------------------------
|
|
11
|
+
/**
|
|
12
|
+
* Build a fully-wired PlatformContainer from a declarative BootConfig.
|
|
13
|
+
*
|
|
14
|
+
* Construction order mirrors the proven boot sequence from product index.ts
|
|
15
|
+
* files: DB pool -> Drizzle -> migrations -> productConfig -> credit ledger
|
|
16
|
+
* -> org repos -> org service -> user role repo -> feature services.
|
|
17
|
+
*
|
|
18
|
+
* Feature sub-containers (fleet, crypto, stripe, gateway) are only
|
|
19
|
+
* constructed when their corresponding feature flag is enabled in
|
|
20
|
+
* `bootConfig.features`. Disabled features yield `null`.
|
|
21
|
+
*/
|
|
22
|
+
export async function buildContainer(bootConfig) {
|
|
23
|
+
if (!bootConfig.databaseUrl) {
|
|
24
|
+
throw new Error("buildContainer: databaseUrl is required");
|
|
25
|
+
}
|
|
26
|
+
// 1. Database pool
|
|
27
|
+
const { Pool: PgPool } = await import("pg");
|
|
28
|
+
const pool = new PgPool({ connectionString: bootConfig.databaseUrl });
|
|
29
|
+
// 2. Drizzle ORM instance
|
|
30
|
+
const { createDb } = await import("../db/index.js");
|
|
31
|
+
const db = createDb(pool);
|
|
32
|
+
// 3. Run Drizzle migrations
|
|
33
|
+
const { migrate } = await import("drizzle-orm/node-postgres/migrator");
|
|
34
|
+
const path = await import("node:path");
|
|
35
|
+
const migrationsFolder = path.resolve(path.dirname(new URL(import.meta.url).pathname), "../../drizzle");
|
|
36
|
+
await migrate(db, { migrationsFolder });
|
|
37
|
+
// 4. Bootstrap product config from DB (auto-seeds from presets if needed)
|
|
38
|
+
const { platformBoot } = await import("../product-config/boot.js");
|
|
39
|
+
const { config: productConfig } = await platformBoot({ slug: bootConfig.slug, db });
|
|
40
|
+
// 5. Credit ledger
|
|
41
|
+
const { DrizzleLedger } = await import("../credits/ledger.js");
|
|
42
|
+
const creditLedger = new DrizzleLedger(db);
|
|
43
|
+
await creditLedger.seedSystemAccounts();
|
|
44
|
+
// 6. Org repositories + OrgService
|
|
45
|
+
const { DrizzleOrgMemberRepository } = await import("../tenancy/org-member-repository.js");
|
|
46
|
+
const { DrizzleOrgRepository } = await import("../tenancy/drizzle-org-repository.js");
|
|
47
|
+
const { OrgService: OrgServiceClass } = await import("../tenancy/org-service.js");
|
|
48
|
+
const { BetterAuthUserRepository } = await import("../db/auth-user-repository.js");
|
|
49
|
+
const orgMemberRepo = new DrizzleOrgMemberRepository(db);
|
|
50
|
+
const orgRepo = new DrizzleOrgRepository(db);
|
|
51
|
+
const authUserRepo = new BetterAuthUserRepository(pool);
|
|
52
|
+
const orgService = new OrgServiceClass(orgRepo, orgMemberRepo, db, {
|
|
53
|
+
userRepo: authUserRepo,
|
|
54
|
+
});
|
|
55
|
+
// 7. User role repository
|
|
56
|
+
const { DrizzleUserRoleRepository } = await import("../auth/user-role-repository.js");
|
|
57
|
+
const userRoleRepo = new DrizzleUserRoleRepository(db);
|
|
58
|
+
// 8. Fleet services (when enabled)
|
|
59
|
+
let fleet = null;
|
|
60
|
+
if (bootConfig.features.fleet) {
|
|
61
|
+
const { FleetManager: FleetManagerClass } = await import("../fleet/fleet-manager.js");
|
|
62
|
+
const { ProfileStore } = await import("../fleet/profile-store.js");
|
|
63
|
+
const { ProxyManager } = await import("../proxy/manager.js");
|
|
64
|
+
const { DrizzleServiceKeyRepository } = await import("../gateway/service-key-repository.js");
|
|
65
|
+
const DockerModule = await import("dockerode");
|
|
66
|
+
const DockerClass = DockerModule.default ?? DockerModule;
|
|
67
|
+
const docker = new DockerClass();
|
|
68
|
+
const fleetDataDir = productConfig.fleet?.fleetDataDir ?? "/data/fleet";
|
|
69
|
+
const profileStore = new ProfileStore(fleetDataDir);
|
|
70
|
+
const proxy = new ProxyManager();
|
|
71
|
+
const serviceKeyRepo = new DrizzleServiceKeyRepository(db);
|
|
72
|
+
const manager = new FleetManagerClass(docker, profileStore, undefined, // platformDiscovery
|
|
73
|
+
undefined, // networkPolicy
|
|
74
|
+
proxy);
|
|
75
|
+
fleet = { manager, docker, proxy, profileStore, serviceKeyRepo };
|
|
76
|
+
}
|
|
77
|
+
// 9. Crypto services (when enabled)
|
|
78
|
+
let crypto = null;
|
|
79
|
+
if (bootConfig.features.crypto) {
|
|
80
|
+
const { DrizzleCryptoChargeRepository } = await import("../billing/crypto/charge-store.js");
|
|
81
|
+
const { DrizzleWebhookSeenRepository } = await import("../billing/drizzle-webhook-seen-repository.js");
|
|
82
|
+
const chargeRepo = new DrizzleCryptoChargeRepository(db);
|
|
83
|
+
const webhookSeenRepo = new DrizzleWebhookSeenRepository(db);
|
|
84
|
+
crypto = { chargeRepo, webhookSeenRepo };
|
|
85
|
+
}
|
|
86
|
+
// 10. Stripe services (when enabled)
|
|
87
|
+
let stripe = null;
|
|
88
|
+
if (bootConfig.features.stripe && bootConfig.stripeSecretKey) {
|
|
89
|
+
const StripeModule = await import("stripe");
|
|
90
|
+
const StripeClass = StripeModule.default;
|
|
91
|
+
const stripeClient = new StripeClass(bootConfig.stripeSecretKey);
|
|
92
|
+
const { DrizzleTenantCustomerRepository } = await import("../billing/stripe/tenant-store.js");
|
|
93
|
+
const { loadCreditPriceMap } = await import("../billing/stripe/credit-prices.js");
|
|
94
|
+
const { StripePaymentProcessor } = await import("../billing/stripe/stripe-payment-processor.js");
|
|
95
|
+
const customerRepo = new DrizzleTenantCustomerRepository(db);
|
|
96
|
+
const priceMap = loadCreditPriceMap();
|
|
97
|
+
const processor = new StripePaymentProcessor({
|
|
98
|
+
stripe: stripeClient,
|
|
99
|
+
tenantRepo: customerRepo,
|
|
100
|
+
webhookSecret: bootConfig.stripeWebhookSecret ?? "",
|
|
101
|
+
priceMap,
|
|
102
|
+
creditLedger,
|
|
103
|
+
});
|
|
104
|
+
stripe = {
|
|
105
|
+
stripe: stripeClient,
|
|
106
|
+
webhookSecret: bootConfig.stripeWebhookSecret ?? "",
|
|
107
|
+
customerRepo,
|
|
108
|
+
processor,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
// 11. Gateway services (when enabled)
|
|
112
|
+
let gateway = null;
|
|
113
|
+
if (bootConfig.features.gateway) {
|
|
114
|
+
const { DrizzleServiceKeyRepository } = await import("../gateway/service-key-repository.js");
|
|
115
|
+
const serviceKeyRepo = new DrizzleServiceKeyRepository(db);
|
|
116
|
+
gateway = { serviceKeyRepo };
|
|
117
|
+
}
|
|
118
|
+
// 12. Build the container (hotPool bound after construction)
|
|
119
|
+
const result = {
|
|
120
|
+
db,
|
|
121
|
+
pool,
|
|
122
|
+
productConfig,
|
|
123
|
+
creditLedger,
|
|
124
|
+
orgMemberRepo,
|
|
125
|
+
orgService,
|
|
126
|
+
userRoleRepo,
|
|
127
|
+
fleet,
|
|
128
|
+
crypto,
|
|
129
|
+
stripe,
|
|
130
|
+
gateway,
|
|
131
|
+
hotPool: null,
|
|
132
|
+
};
|
|
133
|
+
// Bind hot pool after container construction (closures need the full container)
|
|
134
|
+
if (bootConfig.features.hotPool && fleet) {
|
|
135
|
+
const { startHotPool, setPoolSize: setSize, getPoolSize: getSize } = await import("./services/hot-pool.js");
|
|
136
|
+
const { claimPoolInstance } = await import("./services/hot-pool-claim.js");
|
|
137
|
+
const { DrizzlePoolRepository } = await import("./services/pool-repository.js");
|
|
138
|
+
const poolRepo = new DrizzlePoolRepository(pool);
|
|
139
|
+
const hotPoolConfig = { provisionSecret: bootConfig.provisionSecret };
|
|
140
|
+
result.hotPool = {
|
|
141
|
+
start: () => startHotPool(result, poolRepo, hotPoolConfig),
|
|
142
|
+
claim: (name, tenantId, adminUser) => claimPoolInstance(result, poolRepo, name, tenantId, adminUser, hotPoolConfig),
|
|
143
|
+
getPoolSize: () => getSize(poolRepo),
|
|
144
|
+
setPoolSize: (size) => setSize(poolRepo, size),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
return result;
|
|
148
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* platform-core server entry point.
|
|
3
|
+
*
|
|
4
|
+
* Re-exports types, the test helper, and provides bootPlatformServer() —
|
|
5
|
+
* the single-call boot function products use to go from a declarative
|
|
6
|
+
* BootConfig to a running Hono server with DI container.
|
|
7
|
+
*/
|
|
8
|
+
import type { BootConfig, BootResult } from "./boot-config.js";
|
|
9
|
+
export type { BootConfig, BootResult, FeatureFlags, RoutePlugin } from "./boot-config.js";
|
|
10
|
+
export type { CryptoServices, FleetServices, GatewayServices, HotPoolServices, PlatformContainer, StripeServices, } from "./container.js";
|
|
11
|
+
export { buildContainer } from "./container.js";
|
|
12
|
+
export { type BackgroundHandles, gracefulShutdown, startBackgroundServices } from "./lifecycle.js";
|
|
13
|
+
export { type MountConfig, mountRoutes } from "./mount-routes.js";
|
|
14
|
+
export { createTestContainer } from "./test-container.js";
|
|
15
|
+
/**
|
|
16
|
+
* Boot a fully-wired platform server from a declarative config.
|
|
17
|
+
*
|
|
18
|
+
* 1. Builds the DI container (DB, migrations, product config, feature slices)
|
|
19
|
+
* 2. Creates a Hono app and mounts shared routes
|
|
20
|
+
* 3. Returns start/stop lifecycle hooks
|
|
21
|
+
*
|
|
22
|
+
* Products call this from their index.ts:
|
|
23
|
+
* ```ts
|
|
24
|
+
* const { app, container, start, stop } = await bootPlatformServer({
|
|
25
|
+
* slug: "paperclip",
|
|
26
|
+
* databaseUrl: process.env.DATABASE_URL!,
|
|
27
|
+
* provisionSecret: process.env.PROVISION_SECRET!,
|
|
28
|
+
* features: { fleet: true, crypto: true, stripe: true, gateway: true, hotPool: false },
|
|
29
|
+
* });
|
|
30
|
+
* await start();
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export declare function bootPlatformServer(config: BootConfig): Promise<BootResult>;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* platform-core server entry point.
|
|
3
|
+
*
|
|
4
|
+
* Re-exports types, the test helper, and provides bootPlatformServer() —
|
|
5
|
+
* the single-call boot function products use to go from a declarative
|
|
6
|
+
* BootConfig to a running Hono server with DI container.
|
|
7
|
+
*/
|
|
8
|
+
import { Hono } from "hono";
|
|
9
|
+
import { buildContainer } from "./container.js";
|
|
10
|
+
import { gracefulShutdown, startBackgroundServices } from "./lifecycle.js";
|
|
11
|
+
import { mountRoutes } from "./mount-routes.js";
|
|
12
|
+
export { buildContainer } from "./container.js";
|
|
13
|
+
export { gracefulShutdown, startBackgroundServices } from "./lifecycle.js";
|
|
14
|
+
export { mountRoutes } from "./mount-routes.js";
|
|
15
|
+
export { createTestContainer } from "./test-container.js";
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
// bootPlatformServer
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
/**
|
|
20
|
+
* Boot a fully-wired platform server from a declarative config.
|
|
21
|
+
*
|
|
22
|
+
* 1. Builds the DI container (DB, migrations, product config, feature slices)
|
|
23
|
+
* 2. Creates a Hono app and mounts shared routes
|
|
24
|
+
* 3. Returns start/stop lifecycle hooks
|
|
25
|
+
*
|
|
26
|
+
* Products call this from their index.ts:
|
|
27
|
+
* ```ts
|
|
28
|
+
* const { app, container, start, stop } = await bootPlatformServer({
|
|
29
|
+
* slug: "paperclip",
|
|
30
|
+
* databaseUrl: process.env.DATABASE_URL!,
|
|
31
|
+
* provisionSecret: process.env.PROVISION_SECRET!,
|
|
32
|
+
* features: { fleet: true, crypto: true, stripe: true, gateway: true, hotPool: false },
|
|
33
|
+
* });
|
|
34
|
+
* await start();
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export async function bootPlatformServer(config) {
|
|
38
|
+
const container = await buildContainer(config);
|
|
39
|
+
const app = new Hono();
|
|
40
|
+
mountRoutes(app, container, {
|
|
41
|
+
provisionSecret: config.provisionSecret,
|
|
42
|
+
cryptoServiceKey: config.cryptoServiceKey,
|
|
43
|
+
platformDomain: container.productConfig.product?.domain ?? "localhost",
|
|
44
|
+
}, config.routes);
|
|
45
|
+
let handles = null;
|
|
46
|
+
let server = null;
|
|
47
|
+
return {
|
|
48
|
+
app,
|
|
49
|
+
container,
|
|
50
|
+
start: async (port) => {
|
|
51
|
+
const { serve } = await import("@hono/node-server");
|
|
52
|
+
const listenPort = port ?? config.port ?? 3001;
|
|
53
|
+
const hostname = config.host ?? "0.0.0.0";
|
|
54
|
+
server = serve({ fetch: app.fetch, hostname, port: listenPort }, async () => {
|
|
55
|
+
handles = await startBackgroundServices(container);
|
|
56
|
+
});
|
|
57
|
+
},
|
|
58
|
+
stop: async () => {
|
|
59
|
+
if (server)
|
|
60
|
+
server.close();
|
|
61
|
+
if (handles) {
|
|
62
|
+
await gracefulShutdown(container, handles);
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lifecycle management — background services and graceful shutdown.
|
|
3
|
+
*
|
|
4
|
+
* Products currently handle background tasks in their serve() callbacks.
|
|
5
|
+
* This module provides a standard interface for starting and stopping
|
|
6
|
+
* those tasks so bootPlatformServer can manage them uniformly.
|
|
7
|
+
*/
|
|
8
|
+
import type { PlatformContainer } from "./container.js";
|
|
9
|
+
export interface BackgroundHandles {
|
|
10
|
+
intervals: ReturnType<typeof setInterval>[];
|
|
11
|
+
unsubscribes: (() => void)[];
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Start background services that run after the server is listening.
|
|
15
|
+
*
|
|
16
|
+
* Currently a thin scaffold — the hooks exist so products can migrate their
|
|
17
|
+
* background tasks (fleet updater, notification worker, caddy hydration,
|
|
18
|
+
* health monitor) incrementally without changing the boot contract.
|
|
19
|
+
*/
|
|
20
|
+
export declare function startBackgroundServices(container: PlatformContainer): Promise<BackgroundHandles>;
|
|
21
|
+
/**
|
|
22
|
+
* Graceful shutdown: clear intervals, call unsubscribe hooks, close the
|
|
23
|
+
* database connection pool.
|
|
24
|
+
*/
|
|
25
|
+
export declare function gracefulShutdown(container: PlatformContainer, handles: BackgroundHandles): Promise<void>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lifecycle management — background services and graceful shutdown.
|
|
3
|
+
*
|
|
4
|
+
* Products currently handle background tasks in their serve() callbacks.
|
|
5
|
+
* This module provides a standard interface for starting and stopping
|
|
6
|
+
* those tasks so bootPlatformServer can manage them uniformly.
|
|
7
|
+
*/
|
|
8
|
+
// ---------------------------------------------------------------------------
|
|
9
|
+
// startBackgroundServices
|
|
10
|
+
// ---------------------------------------------------------------------------
|
|
11
|
+
/**
|
|
12
|
+
* Start background services that run after the server is listening.
|
|
13
|
+
*
|
|
14
|
+
* Currently a thin scaffold — the hooks exist so products can migrate their
|
|
15
|
+
* background tasks (fleet updater, notification worker, caddy hydration,
|
|
16
|
+
* health monitor) incrementally without changing the boot contract.
|
|
17
|
+
*/
|
|
18
|
+
export async function startBackgroundServices(container) {
|
|
19
|
+
const handles = { intervals: [], unsubscribes: [] };
|
|
20
|
+
// Caddy proxy hydration (if fleet + proxy are enabled)
|
|
21
|
+
if (container.fleet?.proxy) {
|
|
22
|
+
try {
|
|
23
|
+
await container.fleet.proxy.start?.();
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
// Non-fatal — proxy sync will retry on next health tick
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
// Hot pool manager (if enabled)
|
|
30
|
+
if (container.hotPool) {
|
|
31
|
+
try {
|
|
32
|
+
const poolHandles = await container.hotPool.start();
|
|
33
|
+
handles.unsubscribes.push(poolHandles.stop);
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
// Non-fatal — pool will be empty but claiming falls back to cold create
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return handles;
|
|
40
|
+
}
|
|
41
|
+
// ---------------------------------------------------------------------------
|
|
42
|
+
// gracefulShutdown
|
|
43
|
+
// ---------------------------------------------------------------------------
|
|
44
|
+
/**
|
|
45
|
+
* Graceful shutdown: clear intervals, call unsubscribe hooks, close the
|
|
46
|
+
* database connection pool.
|
|
47
|
+
*/
|
|
48
|
+
export async function gracefulShutdown(container, handles) {
|
|
49
|
+
for (const interval of handles.intervals) {
|
|
50
|
+
clearInterval(interval);
|
|
51
|
+
}
|
|
52
|
+
for (const unsub of handles.unsubscribes) {
|
|
53
|
+
unsub();
|
|
54
|
+
}
|
|
55
|
+
await container.pool.end();
|
|
56
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { describe, expect, it } from "vitest";
|
|
3
|
+
import { createAdminAuthMiddleware } from "../admin-auth.js";
|
|
4
|
+
function createApp(adminApiKey) {
|
|
5
|
+
const app = new Hono();
|
|
6
|
+
app.use("/admin/*", createAdminAuthMiddleware({ adminApiKey }));
|
|
7
|
+
app.get("/admin/status", (c) => c.json({ ok: true }));
|
|
8
|
+
return app;
|
|
9
|
+
}
|
|
10
|
+
describe("createAdminAuthMiddleware", () => {
|
|
11
|
+
const API_KEY = "test-admin-key-abc123";
|
|
12
|
+
it("returns 401 without Authorization header", async () => {
|
|
13
|
+
const app = createApp(API_KEY);
|
|
14
|
+
const res = await app.request("/admin/status");
|
|
15
|
+
expect(res.status).toBe(401);
|
|
16
|
+
const body = await res.json();
|
|
17
|
+
expect(body.error).toContain("Unauthorized");
|
|
18
|
+
});
|
|
19
|
+
it("returns 401 with wrong API key", async () => {
|
|
20
|
+
const app = createApp(API_KEY);
|
|
21
|
+
const res = await app.request("/admin/status", {
|
|
22
|
+
headers: { authorization: "Bearer wrong-key" },
|
|
23
|
+
});
|
|
24
|
+
expect(res.status).toBe(401);
|
|
25
|
+
const body = await res.json();
|
|
26
|
+
expect(body.error).toContain("invalid admin credentials");
|
|
27
|
+
});
|
|
28
|
+
it("passes through with correct API key (timing-safe)", async () => {
|
|
29
|
+
const app = createApp(API_KEY);
|
|
30
|
+
const res = await app.request("/admin/status", {
|
|
31
|
+
headers: { authorization: `Bearer ${API_KEY}` },
|
|
32
|
+
});
|
|
33
|
+
expect(res.status).toBe(200);
|
|
34
|
+
const body = await res.json();
|
|
35
|
+
expect(body.ok).toBe(true);
|
|
36
|
+
});
|
|
37
|
+
it("rejects keys of different length (timing-safe length check)", async () => {
|
|
38
|
+
const app = createApp(API_KEY);
|
|
39
|
+
// Key with same prefix but different length
|
|
40
|
+
const res = await app.request("/admin/status", {
|
|
41
|
+
headers: { authorization: `Bearer ${API_KEY}extra` },
|
|
42
|
+
});
|
|
43
|
+
expect(res.status).toBe(401);
|
|
44
|
+
});
|
|
45
|
+
it("returns 503 when admin key is not configured (fail-closed)", async () => {
|
|
46
|
+
const app = createApp("");
|
|
47
|
+
const res = await app.request("/admin/status", {
|
|
48
|
+
headers: { authorization: "Bearer anything" },
|
|
49
|
+
});
|
|
50
|
+
expect(res.status).toBe(503);
|
|
51
|
+
});
|
|
52
|
+
it("rejects non-Bearer auth schemes", async () => {
|
|
53
|
+
const app = createApp(API_KEY);
|
|
54
|
+
const res = await app.request("/admin/status", {
|
|
55
|
+
headers: { authorization: `Basic ${API_KEY}` },
|
|
56
|
+
});
|
|
57
|
+
expect(res.status).toBe(401);
|
|
58
|
+
});
|
|
59
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
3
|
+
import { createTestContainer } from "../../test-container.js";
|
|
4
|
+
import { buildUpstreamHeaders, createTenantProxyMiddleware, extractTenantSubdomain, } from "../tenant-proxy.js";
|
|
5
|
+
// ---------------------------------------------------------------------------
|
|
6
|
+
// extractTenantSubdomain unit tests
|
|
7
|
+
// ---------------------------------------------------------------------------
|
|
8
|
+
describe("extractTenantSubdomain", () => {
|
|
9
|
+
const domain = "example.com";
|
|
10
|
+
it("extracts a valid subdomain", () => {
|
|
11
|
+
expect(extractTenantSubdomain("alice.example.com", domain)).toBe("alice");
|
|
12
|
+
});
|
|
13
|
+
it("returns null for the root domain", () => {
|
|
14
|
+
expect(extractTenantSubdomain("example.com", domain)).toBeNull();
|
|
15
|
+
});
|
|
16
|
+
it("returns null for reserved subdomains", () => {
|
|
17
|
+
expect(extractTenantSubdomain("app.example.com", domain)).toBeNull();
|
|
18
|
+
expect(extractTenantSubdomain("api.example.com", domain)).toBeNull();
|
|
19
|
+
expect(extractTenantSubdomain("admin.example.com", domain)).toBeNull();
|
|
20
|
+
});
|
|
21
|
+
it("returns null for nested subdomains", () => {
|
|
22
|
+
expect(extractTenantSubdomain("deep.alice.example.com", domain)).toBeNull();
|
|
23
|
+
});
|
|
24
|
+
it("strips port before matching", () => {
|
|
25
|
+
expect(extractTenantSubdomain("alice.example.com:3000", domain)).toBe("alice");
|
|
26
|
+
});
|
|
27
|
+
it("returns null for non-matching domain", () => {
|
|
28
|
+
expect(extractTenantSubdomain("alice.other.com", domain)).toBeNull();
|
|
29
|
+
});
|
|
30
|
+
it("returns null for invalid subdomain characters", () => {
|
|
31
|
+
expect(extractTenantSubdomain("al!ce.example.com", domain)).toBeNull();
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
// ---------------------------------------------------------------------------
|
|
35
|
+
// buildUpstreamHeaders unit tests
|
|
36
|
+
// ---------------------------------------------------------------------------
|
|
37
|
+
describe("buildUpstreamHeaders", () => {
|
|
38
|
+
it("copies only allowlisted headers and injects platform headers", () => {
|
|
39
|
+
const incoming = new Headers({
|
|
40
|
+
"content-type": "application/json",
|
|
41
|
+
"x-evil-header": "should-not-pass",
|
|
42
|
+
host: "alice.example.com",
|
|
43
|
+
});
|
|
44
|
+
const user = { id: "u1", email: "a@b.com", name: "Alice" };
|
|
45
|
+
const result = buildUpstreamHeaders(incoming, user, "alice");
|
|
46
|
+
expect(result.get("content-type")).toBe("application/json");
|
|
47
|
+
expect(result.get("x-evil-header")).toBeNull();
|
|
48
|
+
expect(result.get("x-platform-user-id")).toBe("u1");
|
|
49
|
+
expect(result.get("x-platform-tenant")).toBe("alice");
|
|
50
|
+
expect(result.get("x-platform-user-email")).toBe("a@b.com");
|
|
51
|
+
expect(result.get("x-platform-user-name")).toBe("Alice");
|
|
52
|
+
expect(result.get("host")).toBe("alice.example.com");
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
// ---------------------------------------------------------------------------
|
|
56
|
+
// createTenantProxyMiddleware integration tests
|
|
57
|
+
// ---------------------------------------------------------------------------
|
|
58
|
+
describe("createTenantProxyMiddleware", () => {
|
|
59
|
+
const DOMAIN = "example.com";
|
|
60
|
+
let resolveUser;
|
|
61
|
+
let config;
|
|
62
|
+
beforeEach(() => {
|
|
63
|
+
resolveUser = vi.fn();
|
|
64
|
+
config = { platformDomain: DOMAIN, resolveUser };
|
|
65
|
+
});
|
|
66
|
+
function createApp(container) {
|
|
67
|
+
const app = new Hono();
|
|
68
|
+
app.use("/*", createTenantProxyMiddleware(container, config));
|
|
69
|
+
app.get("/fallthrough", (c) => c.json({ fallthrough: true }));
|
|
70
|
+
return app;
|
|
71
|
+
}
|
|
72
|
+
it("passes through non-tenant requests (no subdomain)", async () => {
|
|
73
|
+
const container = createTestContainer();
|
|
74
|
+
const app = createApp(container);
|
|
75
|
+
const res = await app.request("http://example.com/fallthrough");
|
|
76
|
+
expect(res.status).toBe(200);
|
|
77
|
+
const body = await res.json();
|
|
78
|
+
expect(body.fallthrough).toBe(true);
|
|
79
|
+
// resolveUser should not be called for non-tenant requests
|
|
80
|
+
expect(resolveUser).not.toHaveBeenCalled();
|
|
81
|
+
});
|
|
82
|
+
it("returns 401 for unauthenticated tenant requests", async () => {
|
|
83
|
+
const container = createTestContainer({
|
|
84
|
+
fleet: {
|
|
85
|
+
profileStore: { list: vi.fn().mockResolvedValue([]) },
|
|
86
|
+
proxy: { getRoutes: vi.fn().mockReturnValue([]) },
|
|
87
|
+
manager: {},
|
|
88
|
+
docker: {},
|
|
89
|
+
serviceKeyRepo: {},
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
resolveUser.mockResolvedValue(undefined);
|
|
93
|
+
const app = createApp(container);
|
|
94
|
+
const res = await app.request("http://alice.example.com/dashboard", {
|
|
95
|
+
headers: { host: "alice.example.com" },
|
|
96
|
+
});
|
|
97
|
+
expect(res.status).toBe(401);
|
|
98
|
+
const body = await res.json();
|
|
99
|
+
expect(body.error).toContain("Authentication required");
|
|
100
|
+
});
|
|
101
|
+
it("returns 503 when fleet services are not available", async () => {
|
|
102
|
+
const container = createTestContainer({ fleet: null });
|
|
103
|
+
const app = createApp(container);
|
|
104
|
+
const res = await app.request("http://alice.example.com/dashboard", {
|
|
105
|
+
headers: { host: "alice.example.com" },
|
|
106
|
+
});
|
|
107
|
+
expect(res.status).toBe(503);
|
|
108
|
+
const body = await res.json();
|
|
109
|
+
expect(body.error).toContain("Fleet services unavailable");
|
|
110
|
+
});
|
|
111
|
+
it("returns 403 when user is not a member of the tenant", async () => {
|
|
112
|
+
const mockProfile = { name: "alice", tenantId: "tenant-1" };
|
|
113
|
+
const container = createTestContainer({
|
|
114
|
+
fleet: {
|
|
115
|
+
profileStore: { list: vi.fn().mockResolvedValue([mockProfile]) },
|
|
116
|
+
proxy: {
|
|
117
|
+
getRoutes: vi
|
|
118
|
+
.fn()
|
|
119
|
+
.mockReturnValue([{ subdomain: "alice", upstreamHost: "127.0.0.1", upstreamPort: 4000, healthy: true }]),
|
|
120
|
+
},
|
|
121
|
+
manager: {},
|
|
122
|
+
docker: {},
|
|
123
|
+
serviceKeyRepo: {},
|
|
124
|
+
},
|
|
125
|
+
orgMemberRepo: {
|
|
126
|
+
findMember: vi.fn().mockResolvedValue(null),
|
|
127
|
+
listMembers: vi.fn(),
|
|
128
|
+
addMember: vi.fn(),
|
|
129
|
+
updateMemberRole: vi.fn(),
|
|
130
|
+
removeMember: vi.fn(),
|
|
131
|
+
countAdminsAndOwners: vi.fn(),
|
|
132
|
+
listInvites: vi.fn(),
|
|
133
|
+
createInvite: vi.fn(),
|
|
134
|
+
findInviteById: vi.fn(),
|
|
135
|
+
findInviteByToken: vi.fn(),
|
|
136
|
+
deleteInvite: vi.fn(),
|
|
137
|
+
deleteAllMembers: vi.fn(),
|
|
138
|
+
deleteAllInvites: vi.fn(),
|
|
139
|
+
listOrgsByUser: vi.fn(),
|
|
140
|
+
markInviteAccepted: vi.fn(),
|
|
141
|
+
},
|
|
142
|
+
});
|
|
143
|
+
resolveUser.mockResolvedValue({ id: "user-99", email: "user@test.com" });
|
|
144
|
+
const app = createApp(container);
|
|
145
|
+
const res = await app.request("http://alice.example.com/dashboard", {
|
|
146
|
+
headers: { host: "alice.example.com" },
|
|
147
|
+
});
|
|
148
|
+
expect(res.status).toBe(403);
|
|
149
|
+
const body = await res.json();
|
|
150
|
+
expect(body.error).toContain("not a member");
|
|
151
|
+
});
|
|
152
|
+
it("proxies correctly when authorized", async () => {
|
|
153
|
+
const mockProfile = { name: "alice", tenantId: "tenant-1" };
|
|
154
|
+
const upstreamRoute = {
|
|
155
|
+
instanceId: "inst-1",
|
|
156
|
+
subdomain: "alice",
|
|
157
|
+
upstreamHost: "127.0.0.1",
|
|
158
|
+
upstreamPort: 4000,
|
|
159
|
+
healthy: true,
|
|
160
|
+
};
|
|
161
|
+
const container = createTestContainer({
|
|
162
|
+
fleet: {
|
|
163
|
+
profileStore: { list: vi.fn().mockResolvedValue([mockProfile]) },
|
|
164
|
+
proxy: { getRoutes: vi.fn().mockReturnValue([upstreamRoute]) },
|
|
165
|
+
manager: {},
|
|
166
|
+
docker: {},
|
|
167
|
+
serviceKeyRepo: {},
|
|
168
|
+
},
|
|
169
|
+
orgMemberRepo: {
|
|
170
|
+
findMember: vi.fn().mockResolvedValue({ orgId: "tenant-1", userId: "user-1", role: "member" }),
|
|
171
|
+
listMembers: vi.fn(),
|
|
172
|
+
addMember: vi.fn(),
|
|
173
|
+
updateMemberRole: vi.fn(),
|
|
174
|
+
removeMember: vi.fn(),
|
|
175
|
+
countAdminsAndOwners: vi.fn(),
|
|
176
|
+
listInvites: vi.fn(),
|
|
177
|
+
createInvite: vi.fn(),
|
|
178
|
+
findInviteById: vi.fn(),
|
|
179
|
+
findInviteByToken: vi.fn(),
|
|
180
|
+
deleteInvite: vi.fn(),
|
|
181
|
+
deleteAllMembers: vi.fn(),
|
|
182
|
+
deleteAllInvites: vi.fn(),
|
|
183
|
+
listOrgsByUser: vi.fn(),
|
|
184
|
+
markInviteAccepted: vi.fn(),
|
|
185
|
+
},
|
|
186
|
+
});
|
|
187
|
+
resolveUser.mockResolvedValue({ id: "user-1", email: "user@test.com" });
|
|
188
|
+
// Mock global fetch to simulate upstream response
|
|
189
|
+
const originalFetch = globalThis.fetch;
|
|
190
|
+
globalThis.fetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({ upstream: true }), {
|
|
191
|
+
status: 200,
|
|
192
|
+
headers: { "content-type": "application/json" },
|
|
193
|
+
}));
|
|
194
|
+
try {
|
|
195
|
+
const app = createApp(container);
|
|
196
|
+
const res = await app.request("http://alice.example.com/api/data?q=1", {
|
|
197
|
+
headers: { host: "alice.example.com" },
|
|
198
|
+
});
|
|
199
|
+
expect(res.status).toBe(200);
|
|
200
|
+
const body = await res.json();
|
|
201
|
+
expect(body.upstream).toBe(true);
|
|
202
|
+
// Verify fetch was called with the correct upstream URL
|
|
203
|
+
const fetchCall = globalThis.fetch.mock.calls[0];
|
|
204
|
+
expect(fetchCall[0]).toBe("http://127.0.0.1:4000/api/data?q=1");
|
|
205
|
+
// Verify platform headers were injected
|
|
206
|
+
const headers = fetchCall[1].headers;
|
|
207
|
+
expect(headers.get("x-platform-user-id")).toBe("user-1");
|
|
208
|
+
expect(headers.get("x-platform-tenant")).toBe("alice");
|
|
209
|
+
}
|
|
210
|
+
finally {
|
|
211
|
+
globalThis.fetch = originalFetch;
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
it("returns 502 when upstream fetch fails", async () => {
|
|
215
|
+
const mockProfile = { name: "bob", tenantId: "user-1" };
|
|
216
|
+
const upstreamRoute = {
|
|
217
|
+
instanceId: "inst-2",
|
|
218
|
+
subdomain: "bob",
|
|
219
|
+
upstreamHost: "127.0.0.1",
|
|
220
|
+
upstreamPort: 4001,
|
|
221
|
+
healthy: true,
|
|
222
|
+
};
|
|
223
|
+
const container = createTestContainer({
|
|
224
|
+
fleet: {
|
|
225
|
+
profileStore: { list: vi.fn().mockResolvedValue([mockProfile]) },
|
|
226
|
+
proxy: { getRoutes: vi.fn().mockReturnValue([upstreamRoute]) },
|
|
227
|
+
manager: {},
|
|
228
|
+
docker: {},
|
|
229
|
+
serviceKeyRepo: {},
|
|
230
|
+
},
|
|
231
|
+
});
|
|
232
|
+
// tenantId === userId means personal tenant, so validateTenantAccess returns true
|
|
233
|
+
resolveUser.mockResolvedValue({ id: "user-1" });
|
|
234
|
+
const originalFetch = globalThis.fetch;
|
|
235
|
+
globalThis.fetch = vi.fn().mockRejectedValue(new Error("ECONNREFUSED"));
|
|
236
|
+
try {
|
|
237
|
+
const app = createApp(container);
|
|
238
|
+
const res = await app.request("http://bob.example.com/test", {
|
|
239
|
+
headers: { host: "bob.example.com" },
|
|
240
|
+
});
|
|
241
|
+
expect(res.status).toBe(502);
|
|
242
|
+
const body = await res.json();
|
|
243
|
+
expect(body.error).toContain("Bad Gateway");
|
|
244
|
+
}
|
|
245
|
+
finally {
|
|
246
|
+
globalThis.fetch = originalFetch;
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
it("returns 404 when subdomain has no upstream route", async () => {
|
|
250
|
+
const container = createTestContainer({
|
|
251
|
+
fleet: {
|
|
252
|
+
profileStore: { list: vi.fn().mockResolvedValue([]) },
|
|
253
|
+
proxy: { getRoutes: vi.fn().mockReturnValue([]) },
|
|
254
|
+
manager: {},
|
|
255
|
+
docker: {},
|
|
256
|
+
serviceKeyRepo: {},
|
|
257
|
+
},
|
|
258
|
+
});
|
|
259
|
+
resolveUser.mockResolvedValue({ id: "user-1" });
|
|
260
|
+
const app = createApp(container);
|
|
261
|
+
const res = await app.request("http://ghost.example.com/test", {
|
|
262
|
+
headers: { host: "ghost.example.com" },
|
|
263
|
+
});
|
|
264
|
+
expect(res.status).toBe(404);
|
|
265
|
+
const body = await res.json();
|
|
266
|
+
expect(body.error).toContain("Tenant not found");
|
|
267
|
+
});
|
|
268
|
+
});
|