@wopr-network/platform-core 1.68.0 → 1.69.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/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 +170 -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 +81 -0
- package/dist/server/container.js +134 -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 +46 -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 +111 -0
- package/dist/server/routes/admin.js +273 -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/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/package.json +5 -1
- package/src/server/__tests__/build-container.test.ts +402 -0
- package/src/server/__tests__/container.test.ts +204 -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 +237 -0
- package/src/server/index.ts +92 -0
- package/src/server/lifecycle.ts +62 -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 +334 -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/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,237 @@
|
|
|
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
|
+
import type Docker from "dockerode";
|
|
10
|
+
import type { Pool } from "pg";
|
|
11
|
+
import type Stripe from "stripe";
|
|
12
|
+
import type { IUserRoleRepository } from "../auth/user-role-repository.js";
|
|
13
|
+
import type { ICryptoChargeRepository } from "../billing/crypto/charge-store.js";
|
|
14
|
+
import type { IWebhookSeenRepository } from "../billing/webhook-seen-repository.js";
|
|
15
|
+
import type { ILedger } from "../credits/ledger.js";
|
|
16
|
+
import type { ITenantCustomerRepository } from "../credits/tenant-customer-repository.js";
|
|
17
|
+
import type { DrizzleDb } from "../db/index.js";
|
|
18
|
+
import type { FleetManager } from "../fleet/fleet-manager.js";
|
|
19
|
+
import type { IProfileStore } from "../fleet/profile-store.js";
|
|
20
|
+
import type { IServiceKeyRepository } from "../gateway/service-key-repository.js";
|
|
21
|
+
import type { ProductConfig } from "../product-config/repository-types.js";
|
|
22
|
+
import type { ProxyManagerInterface } from "../proxy/types.js";
|
|
23
|
+
import type { IOrgMemberRepository } from "../tenancy/org-member-repository.js";
|
|
24
|
+
import type { OrgService } from "../tenancy/org-service.js";
|
|
25
|
+
import type { BootConfig } from "./boot-config.js";
|
|
26
|
+
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
// Feature sub-containers
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
export interface FleetServices {
|
|
32
|
+
manager: FleetManager;
|
|
33
|
+
docker: Docker;
|
|
34
|
+
proxy: ProxyManagerInterface;
|
|
35
|
+
profileStore: IProfileStore;
|
|
36
|
+
serviceKeyRepo: IServiceKeyRepository;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface CryptoServices {
|
|
40
|
+
chargeRepo: ICryptoChargeRepository;
|
|
41
|
+
webhookSeenRepo: IWebhookSeenRepository;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface StripeServices {
|
|
45
|
+
stripe: Stripe;
|
|
46
|
+
webhookSecret: string;
|
|
47
|
+
customerRepo: ITenantCustomerRepository;
|
|
48
|
+
processor: { handleWebhook(payload: Buffer, signature: string): Promise<unknown> };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface GatewayServices {
|
|
52
|
+
serviceKeyRepo: IServiceKeyRepository;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface HotPoolServices {
|
|
56
|
+
/** Will be typed properly when extracted from nemoclaw. */
|
|
57
|
+
poolManager: unknown;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// ---------------------------------------------------------------------------
|
|
61
|
+
// Main container
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
|
|
64
|
+
export interface PlatformContainer {
|
|
65
|
+
db: DrizzleDb;
|
|
66
|
+
pool: Pool;
|
|
67
|
+
productConfig: ProductConfig;
|
|
68
|
+
creditLedger: ILedger;
|
|
69
|
+
orgMemberRepo: IOrgMemberRepository;
|
|
70
|
+
orgService: OrgService;
|
|
71
|
+
userRoleRepo: IUserRoleRepository;
|
|
72
|
+
|
|
73
|
+
/** Null when the product does not use fleet management. */
|
|
74
|
+
fleet: FleetServices | null;
|
|
75
|
+
/** Null when the product does not accept crypto payments. */
|
|
76
|
+
crypto: CryptoServices | null;
|
|
77
|
+
/** Null when the product does not use Stripe billing. */
|
|
78
|
+
stripe: StripeServices | null;
|
|
79
|
+
/** Null when the product does not expose a metered inference gateway. */
|
|
80
|
+
gateway: GatewayServices | null;
|
|
81
|
+
/** Null when the product does not use a hot-pool of pre-provisioned instances. */
|
|
82
|
+
hotPool: HotPoolServices | null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// ---------------------------------------------------------------------------
|
|
86
|
+
// buildContainer — construct a PlatformContainer from a BootConfig
|
|
87
|
+
// ---------------------------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Build a fully-wired PlatformContainer from a declarative BootConfig.
|
|
91
|
+
*
|
|
92
|
+
* Construction order mirrors the proven boot sequence from product index.ts
|
|
93
|
+
* files: DB pool -> Drizzle -> migrations -> productConfig -> credit ledger
|
|
94
|
+
* -> org repos -> org service -> user role repo -> feature services.
|
|
95
|
+
*
|
|
96
|
+
* Feature sub-containers (fleet, crypto, stripe, gateway) are only
|
|
97
|
+
* constructed when their corresponding feature flag is enabled in
|
|
98
|
+
* `bootConfig.features`. Disabled features yield `null`.
|
|
99
|
+
*/
|
|
100
|
+
export async function buildContainer(bootConfig: BootConfig): Promise<PlatformContainer> {
|
|
101
|
+
if (!bootConfig.databaseUrl) {
|
|
102
|
+
throw new Error("buildContainer: databaseUrl is required");
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// 1. Database pool
|
|
106
|
+
const { Pool: PgPool } = await import("pg");
|
|
107
|
+
const pool: Pool = new PgPool({ connectionString: bootConfig.databaseUrl });
|
|
108
|
+
|
|
109
|
+
// 2. Drizzle ORM instance
|
|
110
|
+
const { createDb } = await import("../db/index.js");
|
|
111
|
+
const db = createDb(pool);
|
|
112
|
+
|
|
113
|
+
// 3. Run Drizzle migrations
|
|
114
|
+
const { migrate } = await import("drizzle-orm/node-postgres/migrator");
|
|
115
|
+
const path = await import("node:path");
|
|
116
|
+
const migrationsFolder = path.resolve(path.dirname(new URL(import.meta.url).pathname), "../../drizzle");
|
|
117
|
+
await migrate(db as never, { migrationsFolder });
|
|
118
|
+
|
|
119
|
+
// 4. Bootstrap product config from DB (auto-seeds from presets if needed)
|
|
120
|
+
const { platformBoot } = await import("../product-config/boot.js");
|
|
121
|
+
const { config: productConfig } = await platformBoot({ slug: bootConfig.slug, db });
|
|
122
|
+
|
|
123
|
+
// 5. Credit ledger
|
|
124
|
+
const { DrizzleLedger } = await import("../credits/ledger.js");
|
|
125
|
+
const creditLedger: ILedger = new DrizzleLedger(db as never);
|
|
126
|
+
await creditLedger.seedSystemAccounts();
|
|
127
|
+
|
|
128
|
+
// 6. Org repositories + OrgService
|
|
129
|
+
const { DrizzleOrgMemberRepository } = await import("../tenancy/org-member-repository.js");
|
|
130
|
+
const { DrizzleOrgRepository } = await import("../tenancy/drizzle-org-repository.js");
|
|
131
|
+
const { OrgService: OrgServiceClass } = await import("../tenancy/org-service.js");
|
|
132
|
+
const { BetterAuthUserRepository } = await import("../db/auth-user-repository.js");
|
|
133
|
+
|
|
134
|
+
const orgMemberRepo: IOrgMemberRepository = new DrizzleOrgMemberRepository(db as never);
|
|
135
|
+
const orgRepo = new DrizzleOrgRepository(db as never);
|
|
136
|
+
const authUserRepo = new BetterAuthUserRepository(pool);
|
|
137
|
+
const orgService = new OrgServiceClass(orgRepo, orgMemberRepo, db as never, {
|
|
138
|
+
userRepo: authUserRepo,
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
// 7. User role repository
|
|
142
|
+
const { DrizzleUserRoleRepository } = await import("../auth/user-role-repository.js");
|
|
143
|
+
const userRoleRepo: IUserRoleRepository = new DrizzleUserRoleRepository(db as never);
|
|
144
|
+
|
|
145
|
+
// 8. Fleet services (when enabled)
|
|
146
|
+
let fleet: FleetServices | null = null;
|
|
147
|
+
if (bootConfig.features.fleet) {
|
|
148
|
+
const { FleetManager: FleetManagerClass } = await import("../fleet/fleet-manager.js");
|
|
149
|
+
const { ProfileStore } = await import("../fleet/profile-store.js");
|
|
150
|
+
const { ProxyManager } = await import("../proxy/manager.js");
|
|
151
|
+
const { DrizzleServiceKeyRepository } = await import("../gateway/service-key-repository.js");
|
|
152
|
+
const DockerModule = await import("dockerode");
|
|
153
|
+
const DockerClass = DockerModule.default ?? DockerModule;
|
|
154
|
+
|
|
155
|
+
const docker: Docker = new (DockerClass as new () => Docker)();
|
|
156
|
+
const fleetDataDir = productConfig.fleet?.fleetDataDir ?? "/data/fleet";
|
|
157
|
+
const profileStore: IProfileStore = new ProfileStore(fleetDataDir);
|
|
158
|
+
const proxy: ProxyManagerInterface = new ProxyManager();
|
|
159
|
+
const serviceKeyRepo: IServiceKeyRepository = new DrizzleServiceKeyRepository(db as never);
|
|
160
|
+
const manager: FleetManager = new FleetManagerClass(
|
|
161
|
+
docker,
|
|
162
|
+
profileStore,
|
|
163
|
+
undefined, // platformDiscovery
|
|
164
|
+
undefined, // networkPolicy
|
|
165
|
+
proxy,
|
|
166
|
+
);
|
|
167
|
+
|
|
168
|
+
fleet = { manager, docker, proxy, profileStore, serviceKeyRepo };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// 9. Crypto services (when enabled)
|
|
172
|
+
let crypto: CryptoServices | null = null;
|
|
173
|
+
if (bootConfig.features.crypto) {
|
|
174
|
+
const { DrizzleCryptoChargeRepository } = await import("../billing/crypto/charge-store.js");
|
|
175
|
+
const { DrizzleWebhookSeenRepository } = await import("../billing/drizzle-webhook-seen-repository.js");
|
|
176
|
+
|
|
177
|
+
const chargeRepo: ICryptoChargeRepository = new DrizzleCryptoChargeRepository(db as never);
|
|
178
|
+
const webhookSeenRepo: IWebhookSeenRepository = new DrizzleWebhookSeenRepository(db as never);
|
|
179
|
+
|
|
180
|
+
crypto = { chargeRepo, webhookSeenRepo };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// 10. Stripe services (when enabled)
|
|
184
|
+
let stripe: StripeServices | null = null;
|
|
185
|
+
if (bootConfig.features.stripe && bootConfig.stripeSecretKey) {
|
|
186
|
+
const StripeModule = await import("stripe");
|
|
187
|
+
const StripeClass = StripeModule.default;
|
|
188
|
+
const stripeClient: Stripe = new StripeClass(bootConfig.stripeSecretKey);
|
|
189
|
+
|
|
190
|
+
const { DrizzleTenantCustomerRepository } = await import("../billing/stripe/tenant-store.js");
|
|
191
|
+
const { loadCreditPriceMap } = await import("../billing/stripe/credit-prices.js");
|
|
192
|
+
const { StripePaymentProcessor } = await import("../billing/stripe/stripe-payment-processor.js");
|
|
193
|
+
|
|
194
|
+
const customerRepo = new DrizzleTenantCustomerRepository(db as never);
|
|
195
|
+
const priceMap = loadCreditPriceMap();
|
|
196
|
+
const processor = new StripePaymentProcessor({
|
|
197
|
+
stripe: stripeClient,
|
|
198
|
+
tenantRepo: customerRepo,
|
|
199
|
+
webhookSecret: bootConfig.stripeWebhookSecret ?? "",
|
|
200
|
+
priceMap,
|
|
201
|
+
creditLedger,
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
stripe = {
|
|
205
|
+
stripe: stripeClient,
|
|
206
|
+
webhookSecret: bootConfig.stripeWebhookSecret ?? "",
|
|
207
|
+
customerRepo,
|
|
208
|
+
processor,
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// 11. Gateway services (when enabled)
|
|
213
|
+
let gateway: GatewayServices | null = null;
|
|
214
|
+
if (bootConfig.features.gateway) {
|
|
215
|
+
const { DrizzleServiceKeyRepository } = await import("../gateway/service-key-repository.js");
|
|
216
|
+
const serviceKeyRepo: IServiceKeyRepository = new DrizzleServiceKeyRepository(db as never);
|
|
217
|
+
gateway = { serviceKeyRepo };
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// hotPool: not yet implemented — needs nemoclaw extraction
|
|
221
|
+
const hotPool: HotPoolServices | null = null;
|
|
222
|
+
|
|
223
|
+
return {
|
|
224
|
+
db,
|
|
225
|
+
pool,
|
|
226
|
+
productConfig,
|
|
227
|
+
creditLedger,
|
|
228
|
+
orgMemberRepo,
|
|
229
|
+
orgService,
|
|
230
|
+
userRoleRepo,
|
|
231
|
+
fleet,
|
|
232
|
+
crypto,
|
|
233
|
+
stripe,
|
|
234
|
+
gateway,
|
|
235
|
+
hotPool,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
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
|
+
|
|
9
|
+
import { Hono } from "hono";
|
|
10
|
+
import type { BootConfig, BootResult } from "./boot-config.js";
|
|
11
|
+
import { buildContainer } from "./container.js";
|
|
12
|
+
import { type BackgroundHandles, gracefulShutdown, startBackgroundServices } from "./lifecycle.js";
|
|
13
|
+
import { mountRoutes } from "./mount-routes.js";
|
|
14
|
+
|
|
15
|
+
// ---------------------------------------------------------------------------
|
|
16
|
+
// Re-exports
|
|
17
|
+
// ---------------------------------------------------------------------------
|
|
18
|
+
|
|
19
|
+
export type { BootConfig, BootResult, FeatureFlags, RoutePlugin } from "./boot-config.js";
|
|
20
|
+
export type {
|
|
21
|
+
CryptoServices,
|
|
22
|
+
FleetServices,
|
|
23
|
+
GatewayServices,
|
|
24
|
+
HotPoolServices,
|
|
25
|
+
PlatformContainer,
|
|
26
|
+
StripeServices,
|
|
27
|
+
} from "./container.js";
|
|
28
|
+
export { buildContainer } from "./container.js";
|
|
29
|
+
export { type BackgroundHandles, gracefulShutdown, startBackgroundServices } from "./lifecycle.js";
|
|
30
|
+
export { type MountConfig, mountRoutes } from "./mount-routes.js";
|
|
31
|
+
export { createTestContainer } from "./test-container.js";
|
|
32
|
+
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
// bootPlatformServer
|
|
35
|
+
// ---------------------------------------------------------------------------
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Boot a fully-wired platform server from a declarative config.
|
|
39
|
+
*
|
|
40
|
+
* 1. Builds the DI container (DB, migrations, product config, feature slices)
|
|
41
|
+
* 2. Creates a Hono app and mounts shared routes
|
|
42
|
+
* 3. Returns start/stop lifecycle hooks
|
|
43
|
+
*
|
|
44
|
+
* Products call this from their index.ts:
|
|
45
|
+
* ```ts
|
|
46
|
+
* const { app, container, start, stop } = await bootPlatformServer({
|
|
47
|
+
* slug: "paperclip",
|
|
48
|
+
* databaseUrl: process.env.DATABASE_URL!,
|
|
49
|
+
* provisionSecret: process.env.PROVISION_SECRET!,
|
|
50
|
+
* features: { fleet: true, crypto: true, stripe: true, gateway: true, hotPool: false },
|
|
51
|
+
* });
|
|
52
|
+
* await start();
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
export async function bootPlatformServer(config: BootConfig): Promise<BootResult> {
|
|
56
|
+
const container = await buildContainer(config);
|
|
57
|
+
const app = new Hono();
|
|
58
|
+
|
|
59
|
+
mountRoutes(
|
|
60
|
+
app,
|
|
61
|
+
container,
|
|
62
|
+
{
|
|
63
|
+
provisionSecret: config.provisionSecret,
|
|
64
|
+
cryptoServiceKey: config.cryptoServiceKey,
|
|
65
|
+
platformDomain: container.productConfig.product?.domain ?? "localhost",
|
|
66
|
+
},
|
|
67
|
+
config.routes,
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
let handles: BackgroundHandles | null = null;
|
|
71
|
+
let server: { close: () => void } | null = null;
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
app,
|
|
75
|
+
container,
|
|
76
|
+
start: async (port?: number) => {
|
|
77
|
+
const { serve } = await import("@hono/node-server");
|
|
78
|
+
const listenPort = port ?? config.port ?? 3001;
|
|
79
|
+
const hostname = config.host ?? "0.0.0.0";
|
|
80
|
+
|
|
81
|
+
server = serve({ fetch: app.fetch, hostname, port: listenPort }, async () => {
|
|
82
|
+
handles = await startBackgroundServices(container);
|
|
83
|
+
});
|
|
84
|
+
},
|
|
85
|
+
stop: async () => {
|
|
86
|
+
if (server) server.close();
|
|
87
|
+
if (handles) {
|
|
88
|
+
await gracefulShutdown(container, handles);
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
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
|
+
import type { PlatformContainer } from "./container.js";
|
|
10
|
+
|
|
11
|
+
// ---------------------------------------------------------------------------
|
|
12
|
+
// Types
|
|
13
|
+
// ---------------------------------------------------------------------------
|
|
14
|
+
|
|
15
|
+
export interface BackgroundHandles {
|
|
16
|
+
intervals: ReturnType<typeof setInterval>[];
|
|
17
|
+
unsubscribes: (() => void)[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// ---------------------------------------------------------------------------
|
|
21
|
+
// startBackgroundServices
|
|
22
|
+
// ---------------------------------------------------------------------------
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Start background services that run after the server is listening.
|
|
26
|
+
*
|
|
27
|
+
* Currently a thin scaffold — the hooks exist so products can migrate their
|
|
28
|
+
* background tasks (fleet updater, notification worker, caddy hydration,
|
|
29
|
+
* health monitor) incrementally without changing the boot contract.
|
|
30
|
+
*/
|
|
31
|
+
export async function startBackgroundServices(container: PlatformContainer): Promise<BackgroundHandles> {
|
|
32
|
+
const handles: BackgroundHandles = { intervals: [], unsubscribes: [] };
|
|
33
|
+
|
|
34
|
+
// Caddy proxy hydration (if fleet + proxy are enabled)
|
|
35
|
+
if (container.fleet?.proxy) {
|
|
36
|
+
try {
|
|
37
|
+
await container.fleet.proxy.start?.();
|
|
38
|
+
} catch {
|
|
39
|
+
// Non-fatal — proxy sync will retry on next health tick
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return handles;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// ---------------------------------------------------------------------------
|
|
47
|
+
// gracefulShutdown
|
|
48
|
+
// ---------------------------------------------------------------------------
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Graceful shutdown: clear intervals, call unsubscribe hooks, close the
|
|
52
|
+
* database connection pool.
|
|
53
|
+
*/
|
|
54
|
+
export async function gracefulShutdown(container: PlatformContainer, handles: BackgroundHandles): Promise<void> {
|
|
55
|
+
for (const interval of handles.intervals) {
|
|
56
|
+
clearInterval(interval);
|
|
57
|
+
}
|
|
58
|
+
for (const unsub of handles.unsubscribes) {
|
|
59
|
+
unsub();
|
|
60
|
+
}
|
|
61
|
+
await container.pool.end();
|
|
62
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { describe, expect, it } from "vitest";
|
|
3
|
+
import { createAdminAuthMiddleware } from "../admin-auth.js";
|
|
4
|
+
|
|
5
|
+
function createApp(adminApiKey: string) {
|
|
6
|
+
const app = new Hono();
|
|
7
|
+
app.use("/admin/*", createAdminAuthMiddleware({ adminApiKey }));
|
|
8
|
+
app.get("/admin/status", (c) => c.json({ ok: true }));
|
|
9
|
+
return app;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
describe("createAdminAuthMiddleware", () => {
|
|
13
|
+
const API_KEY = "test-admin-key-abc123";
|
|
14
|
+
|
|
15
|
+
it("returns 401 without Authorization header", async () => {
|
|
16
|
+
const app = createApp(API_KEY);
|
|
17
|
+
const res = await app.request("/admin/status");
|
|
18
|
+
expect(res.status).toBe(401);
|
|
19
|
+
const body = await res.json();
|
|
20
|
+
expect(body.error).toContain("Unauthorized");
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it("returns 401 with wrong API key", async () => {
|
|
24
|
+
const app = createApp(API_KEY);
|
|
25
|
+
const res = await app.request("/admin/status", {
|
|
26
|
+
headers: { authorization: "Bearer wrong-key" },
|
|
27
|
+
});
|
|
28
|
+
expect(res.status).toBe(401);
|
|
29
|
+
const body = await res.json();
|
|
30
|
+
expect(body.error).toContain("invalid admin credentials");
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it("passes through with correct API key (timing-safe)", async () => {
|
|
34
|
+
const app = createApp(API_KEY);
|
|
35
|
+
const res = await app.request("/admin/status", {
|
|
36
|
+
headers: { authorization: `Bearer ${API_KEY}` },
|
|
37
|
+
});
|
|
38
|
+
expect(res.status).toBe(200);
|
|
39
|
+
const body = await res.json();
|
|
40
|
+
expect(body.ok).toBe(true);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it("rejects keys of different length (timing-safe length check)", async () => {
|
|
44
|
+
const app = createApp(API_KEY);
|
|
45
|
+
// Key with same prefix but different length
|
|
46
|
+
const res = await app.request("/admin/status", {
|
|
47
|
+
headers: { authorization: `Bearer ${API_KEY}extra` },
|
|
48
|
+
});
|
|
49
|
+
expect(res.status).toBe(401);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it("returns 503 when admin key is not configured (fail-closed)", async () => {
|
|
53
|
+
const app = createApp("");
|
|
54
|
+
const res = await app.request("/admin/status", {
|
|
55
|
+
headers: { authorization: "Bearer anything" },
|
|
56
|
+
});
|
|
57
|
+
expect(res.status).toBe(503);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it("rejects non-Bearer auth schemes", async () => {
|
|
61
|
+
const app = createApp(API_KEY);
|
|
62
|
+
const res = await app.request("/admin/status", {
|
|
63
|
+
headers: { authorization: `Basic ${API_KEY}` },
|
|
64
|
+
});
|
|
65
|
+
expect(res.status).toBe(401);
|
|
66
|
+
});
|
|
67
|
+
});
|