@codelitdev/platform-cli 0.1.0-alpha.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/LICENSE +21 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +43 -0
- package/dist/codemod-readme-title.d.ts +5 -0
- package/dist/codemod-readme-title.js +21 -0
- package/dist/create.d.ts +6 -0
- package/dist/create.js +124 -0
- package/dist/doctor.d.ts +12 -0
- package/dist/doctor.js +111 -0
- package/dist/fs.d.ts +5 -0
- package/dist/fs.js +42 -0
- package/dist/git.d.ts +1 -0
- package/dist/git.js +19 -0
- package/dist/hash.d.ts +2 -0
- package/dist/hash.js +8 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/manifest.d.ts +12 -0
- package/dist/manifest.js +31 -0
- package/dist/template.d.ts +2 -0
- package/dist/template.js +23 -0
- package/dist/upgrade.d.ts +13 -0
- package/dist/upgrade.js +97 -0
- package/package.json +41 -0
- package/template/.github/workflows/platform-conformance.yml +28 -0
- package/template/README.md +5 -0
- package/template/apps/api/.env.example +18 -0
- package/template/apps/api/README.md +3 -0
- package/template/apps/api/billing.config.ts +25 -0
- package/template/apps/api/drizzle.config.ts +7 -0
- package/template/apps/api/package.json +53 -0
- package/template/apps/api/scripts/generate-auth-schema.mjs +173 -0
- package/template/apps/api/scripts/migrate.mjs +15 -0
- package/template/apps/api/src/app.test.ts +479 -0
- package/template/apps/api/src/auth/api-keys.ts +131 -0
- package/template/apps/api/src/auth/authenticate.ts +166 -0
- package/template/apps/api/src/auth/better-auth.ts +38 -0
- package/template/apps/api/src/auth/oauth.ts +9 -0
- package/template/apps/api/src/auth/options.ts +69 -0
- package/template/apps/api/src/billing.ts +58 -0
- package/template/apps/api/src/conformance-adapter.ts +335 -0
- package/template/apps/api/src/db/migrate.ts +26 -0
- package/template/apps/api/src/db/migrations/0000_application.sql +72 -0
- package/template/apps/api/src/db/migrations/0000_auth.sql +178 -0
- package/template/apps/api/src/db/migrations/0001_billing.sql +234 -0
- package/template/apps/api/src/db/schema/auth.generated.ts +185 -0
- package/template/apps/api/src/db/schema/billing.generated.ts +447 -0
- package/template/apps/api/src/db/schema/index.ts +3 -0
- package/template/apps/api/src/db/schema/notes.ts +31 -0
- package/template/apps/api/src/db/schema/tenants.ts +83 -0
- package/template/apps/api/src/deps.ts +12 -0
- package/template/apps/api/src/dispatch.ts +476 -0
- package/template/apps/api/src/express-app.ts +161 -0
- package/template/apps/api/src/invitations.ts +217 -0
- package/template/apps/api/src/logger.ts +26 -0
- package/template/apps/api/src/main.ts +98 -0
- package/template/apps/api/src/mcp.ts +127 -0
- package/template/apps/api/src/notes.ts +251 -0
- package/template/apps/api/src/openapi.ts +12 -0
- package/template/apps/api/src/permissions.ts +35 -0
- package/template/apps/api/src/runtime.ts +167 -0
- package/template/apps/api/src/seed.ts +340 -0
- package/template/apps/api/src/tenancy.ts +116 -0
- package/template/apps/api/src/types.ts +20 -0
- package/template/apps/api/src/worker.ts +57 -0
- package/template/apps/api/tsconfig.json +14 -0
- package/template/apps/web/.env.example +7 -0
- package/template/apps/web/app/api/[...path]/route.ts +51 -0
- package/template/apps/web/app/globals.css +156 -0
- package/template/apps/web/app/layout.tsx +34 -0
- package/template/apps/web/app/login/page.tsx +127 -0
- package/template/apps/web/app/notes/page.tsx +93 -0
- package/template/apps/web/app/page.tsx +80 -0
- package/template/apps/web/components/auth-gate.tsx +34 -0
- package/template/apps/web/components/browser-observability.tsx +53 -0
- package/template/apps/web/components/tenant-switcher.tsx +51 -0
- package/template/apps/web/lib/observability-config.ts +15 -0
- package/template/apps/web/next-env.d.ts +2 -0
- package/template/apps/web/next.config.ts +7 -0
- package/template/apps/web/package.json +26 -0
- package/template/apps/web/tsconfig.json +21 -0
- package/template/biome.template.json +50 -0
- package/template/docker-compose.yml +14 -0
- package/template/package.json +40 -0
- package/template/packages/api-contract/package.json +23 -0
- package/template/packages/api-contract/src/index.ts +256 -0
- package/template/packages/api-contract/src/mcp-parity.ts +158 -0
- package/template/packages/api-contract/tsconfig.json +11 -0
- package/template/patches/@anatine__zod-openapi@1.14.2.patch +14 -0
- package/template/tooling/platform/config.ts +2 -0
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { verifyOAuthAccessToken } from "@codelitdev/oauth-server-kit";
|
|
2
|
+
import { resolveBetterAuthSession } from "@codelitdev/oauth-server-kit/better-auth";
|
|
3
|
+
import {
|
|
4
|
+
type AuthenticationResult,
|
|
5
|
+
type Clock,
|
|
6
|
+
createPlatformError,
|
|
7
|
+
type HeaderMap,
|
|
8
|
+
mapTransportAuthentication,
|
|
9
|
+
selectHttpCredential,
|
|
10
|
+
selectMcpCredential,
|
|
11
|
+
} from "@codelitdev/platform";
|
|
12
|
+
import { fromNodeHeaders } from "better-auth/node";
|
|
13
|
+
import { and, eq, isNull } from "drizzle-orm";
|
|
14
|
+
import * as schema from "../db/schema/index.js";
|
|
15
|
+
import type { AppDb } from "../types.js";
|
|
16
|
+
import { apiKeyDigestMatches, parseApiKey } from "./api-keys.js";
|
|
17
|
+
import type { ReferenceAuth } from "./better-auth.js";
|
|
18
|
+
|
|
19
|
+
export type AuthRuntime = {
|
|
20
|
+
db: AppDb;
|
|
21
|
+
apiKeyPepper: string;
|
|
22
|
+
auth: ReferenceAuth;
|
|
23
|
+
clock: Clock;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
function toNodeHeaderMap(
|
|
27
|
+
headers: HeaderMap,
|
|
28
|
+
): Record<string, string | string[] | undefined> {
|
|
29
|
+
return headers;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function authenticateHttpRequest(
|
|
33
|
+
headers: HeaderMap,
|
|
34
|
+
deps: AuthRuntime,
|
|
35
|
+
): Promise<AuthenticationResult<string>> {
|
|
36
|
+
const selected = selectHttpCredential(headers);
|
|
37
|
+
if (selected.kind === "absent") {
|
|
38
|
+
return mapTransportAuthentication({ kind: "absent" }, { transport: "http" });
|
|
39
|
+
}
|
|
40
|
+
if (selected.kind === "ambiguous") {
|
|
41
|
+
return { kind: "rejected", error: selected.error };
|
|
42
|
+
}
|
|
43
|
+
const presented = selected.credential;
|
|
44
|
+
if (presented.kind === "session") {
|
|
45
|
+
const resolved = await resolveBetterAuthSession(
|
|
46
|
+
{ auth: deps.auth.auth, issuer: deps.auth.issuer },
|
|
47
|
+
fromNodeHeaders(toNodeHeaderMap(headers)),
|
|
48
|
+
);
|
|
49
|
+
if (resolved.status === "unavailable") {
|
|
50
|
+
return {
|
|
51
|
+
kind: "rejected",
|
|
52
|
+
error: createPlatformError("internal_error"),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
if (resolved.status !== "authenticated" || resolved.identity.method !== "session") {
|
|
56
|
+
return {
|
|
57
|
+
kind: "rejected",
|
|
58
|
+
error: createPlatformError("unauthenticated"),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
kind: "authenticated",
|
|
63
|
+
principalId: resolved.identity.subject,
|
|
64
|
+
credential: { kind: "session", credentialId: resolved.identity.subject },
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
if (presented.kind === "oauth") {
|
|
68
|
+
const resolved = await verifyOAuthAccessToken(
|
|
69
|
+
{
|
|
70
|
+
oauthResourceClient: deps.auth.oauthResourceClient,
|
|
71
|
+
issuer: deps.auth.issuer,
|
|
72
|
+
audiences: [deps.auth.mcpResource, deps.auth.restResource],
|
|
73
|
+
},
|
|
74
|
+
presented.secret,
|
|
75
|
+
);
|
|
76
|
+
if (resolved.status === "unavailable") {
|
|
77
|
+
return {
|
|
78
|
+
kind: "rejected",
|
|
79
|
+
error: createPlatformError("internal_error"),
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
if (resolved.status !== "authenticated" || resolved.identity.method !== "oauth") {
|
|
83
|
+
return {
|
|
84
|
+
kind: "rejected",
|
|
85
|
+
error: createPlatformError("unauthenticated"),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
kind: "authenticated",
|
|
90
|
+
principalId: resolved.identity.subject,
|
|
91
|
+
credential: {
|
|
92
|
+
kind: "oauth",
|
|
93
|
+
credentialId: resolved.identity.clientId,
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
const parsed = parseApiKey(presented.secret);
|
|
98
|
+
if (!parsed) {
|
|
99
|
+
return {
|
|
100
|
+
kind: "rejected",
|
|
101
|
+
error: createPlatformError("unauthenticated"),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
const keys = await deps.db
|
|
105
|
+
.select()
|
|
106
|
+
.from(schema.apiKeys)
|
|
107
|
+
.where(
|
|
108
|
+
and(
|
|
109
|
+
eq(schema.apiKeys.publicId, parsed.publicId),
|
|
110
|
+
isNull(schema.apiKeys.revokedAt),
|
|
111
|
+
),
|
|
112
|
+
)
|
|
113
|
+
.limit(1);
|
|
114
|
+
const key = keys[0];
|
|
115
|
+
if (
|
|
116
|
+
!key ||
|
|
117
|
+
(key.expiresAt && key.expiresAt.getTime() <= deps.clock.now().getTime()) ||
|
|
118
|
+
!apiKeyDigestMatches(deps.apiKeyPepper, parsed.secret, key.digest)
|
|
119
|
+
) {
|
|
120
|
+
return {
|
|
121
|
+
kind: "rejected",
|
|
122
|
+
error: createPlatformError("unauthenticated"),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
void deps.db
|
|
126
|
+
.update(schema.apiKeys)
|
|
127
|
+
.set({ lastUsedAt: deps.clock.now() })
|
|
128
|
+
.where(eq(schema.apiKeys.id, key.id))
|
|
129
|
+
.then(() => undefined)
|
|
130
|
+
.catch(() => undefined);
|
|
131
|
+
return {
|
|
132
|
+
kind: "authenticated",
|
|
133
|
+
principalId: key.userId,
|
|
134
|
+
credential: { kind: "api_key", credentialId: key.id },
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export async function authenticateMcpRequest(
|
|
139
|
+
headers: HeaderMap,
|
|
140
|
+
deps: AuthRuntime,
|
|
141
|
+
): Promise<AuthenticationResult<string>> {
|
|
142
|
+
const selected = selectMcpCredential(headers);
|
|
143
|
+
if (selected.kind === "absent") {
|
|
144
|
+
return mapTransportAuthentication({ kind: "absent" }, { transport: "mcp" });
|
|
145
|
+
}
|
|
146
|
+
if (selected.kind === "ambiguous") {
|
|
147
|
+
return { kind: "rejected", error: selected.error };
|
|
148
|
+
}
|
|
149
|
+
if (selected.credential.kind === "session") {
|
|
150
|
+
return {
|
|
151
|
+
kind: "rejected",
|
|
152
|
+
error: createPlatformError("unauthenticated"),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
return authenticateHttpRequest(
|
|
156
|
+
{
|
|
157
|
+
authorization:
|
|
158
|
+
selected.credential.kind === "oauth"
|
|
159
|
+
? `Bearer ${selected.credential.secret}`
|
|
160
|
+
: undefined,
|
|
161
|
+
"x-api-key":
|
|
162
|
+
selected.credential.kind === "api_key" ? selected.credential.secret : undefined,
|
|
163
|
+
},
|
|
164
|
+
deps,
|
|
165
|
+
).then((result) => mapTransportAuthentication(result, { transport: "mcp" }));
|
|
166
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { oauthProviderResourceClient } from "@better-auth/oauth-provider/resource-client";
|
|
2
|
+
import { betterAuth } from "better-auth";
|
|
3
|
+
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
|
4
|
+
import * as authSchema from "../db/schema/auth.generated.js";
|
|
5
|
+
import type { AppDb } from "../types.js";
|
|
6
|
+
import { AUTH_BASE_PATH, authUrls, referenceAuthOptions } from "./options.js";
|
|
7
|
+
|
|
8
|
+
export function createReferenceAuth(input: {
|
|
9
|
+
db: AppDb;
|
|
10
|
+
publicApiUrl: string;
|
|
11
|
+
secret: string;
|
|
12
|
+
webOrigin?: string;
|
|
13
|
+
}) {
|
|
14
|
+
if (input.secret.length < 32) {
|
|
15
|
+
throw new Error("better_auth_secret_too_short");
|
|
16
|
+
}
|
|
17
|
+
const urls = authUrls(input.publicApiUrl, input.webOrigin);
|
|
18
|
+
const auth = betterAuth(
|
|
19
|
+
referenceAuthOptions({
|
|
20
|
+
publicApiUrl: input.publicApiUrl,
|
|
21
|
+
secret: input.secret,
|
|
22
|
+
webOrigin: input.webOrigin,
|
|
23
|
+
database: drizzleAdapter(input.db, {
|
|
24
|
+
provider: "pg",
|
|
25
|
+
schema: authSchema,
|
|
26
|
+
}),
|
|
27
|
+
}),
|
|
28
|
+
);
|
|
29
|
+
const oauthResourceClient = oauthProviderResourceClient(auth);
|
|
30
|
+
return {
|
|
31
|
+
auth,
|
|
32
|
+
oauthResourceClient,
|
|
33
|
+
...urls,
|
|
34
|
+
authBasePath: AUTH_BASE_PATH,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type ReferenceAuth = ReturnType<typeof createReferenceAuth>;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { oauthProvider } from "@better-auth/oauth-provider";
|
|
2
|
+
import { createOAuthProviderOptions } from "@codelitdev/oauth-server-kit/better-auth";
|
|
3
|
+
import { emailOTP } from "better-auth/plugins/email-otp";
|
|
4
|
+
import { jwt } from "better-auth/plugins/jwt";
|
|
5
|
+
|
|
6
|
+
export const AUTH_BASE_PATH = "/api/auth";
|
|
7
|
+
export const AUTH_SECRET_MIN_LENGTH = 32;
|
|
8
|
+
|
|
9
|
+
export type ReferenceAuthUrls = {
|
|
10
|
+
publicApiUrl: string;
|
|
11
|
+
webOrigin: string;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export function authUrls(
|
|
15
|
+
publicApiUrl: string,
|
|
16
|
+
webOrigin?: string,
|
|
17
|
+
): ReferenceAuthUrls & {
|
|
18
|
+
issuer: string;
|
|
19
|
+
restResource: string;
|
|
20
|
+
mcpResource: string;
|
|
21
|
+
} {
|
|
22
|
+
const normalized = publicApiUrl.replace(/\/$/, "");
|
|
23
|
+
return {
|
|
24
|
+
publicApiUrl: normalized,
|
|
25
|
+
webOrigin: (webOrigin ?? normalized).replace(/\/$/, ""),
|
|
26
|
+
issuer: `${normalized}${AUTH_BASE_PATH}`,
|
|
27
|
+
restResource: `${normalized}/api`,
|
|
28
|
+
mcpResource: `${normalized}/mcp`,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function oauthProviderInput(urls: ReturnType<typeof authUrls>) {
|
|
33
|
+
return createOAuthProviderOptions({
|
|
34
|
+
loginPage: `${urls.publicApiUrl}/oauth/login`,
|
|
35
|
+
consentPage: `${urls.publicApiUrl}/oauth/consent`,
|
|
36
|
+
scopes: ["openid", "profile", "email", "offline_access", "data:read"],
|
|
37
|
+
validAudiences: [urls.restResource, urls.mcpResource],
|
|
38
|
+
clientRegistrationDefaultScopes: ["openid", "profile", "email"],
|
|
39
|
+
clientRegistrationAllowedScopes: ["offline_access", "data:read"],
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Shared Better Auth options used by the live factory and the schema generator. */
|
|
44
|
+
export function referenceAuthOptions(input: {
|
|
45
|
+
publicApiUrl: string;
|
|
46
|
+
secret: string;
|
|
47
|
+
webOrigin?: string;
|
|
48
|
+
database?: unknown;
|
|
49
|
+
}) {
|
|
50
|
+
const urls = authUrls(input.publicApiUrl, input.webOrigin);
|
|
51
|
+
return {
|
|
52
|
+
appName: "__PRODUCT_NAME__",
|
|
53
|
+
baseURL: urls.publicApiUrl,
|
|
54
|
+
basePath: AUTH_BASE_PATH,
|
|
55
|
+
secret: input.secret,
|
|
56
|
+
trustedOrigins: [urls.webOrigin, urls.publicApiUrl],
|
|
57
|
+
emailAndPassword: { enabled: true },
|
|
58
|
+
...(input.database ? { database: input.database } : {}),
|
|
59
|
+
plugins: [
|
|
60
|
+
jwt(),
|
|
61
|
+
emailOTP({
|
|
62
|
+
async sendVerificationOTP() {
|
|
63
|
+
/* Product mail is application-owned; OTP still issues locally. */
|
|
64
|
+
},
|
|
65
|
+
}),
|
|
66
|
+
oauthProvider(oauthProviderInput(urls)),
|
|
67
|
+
],
|
|
68
|
+
};
|
|
69
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { drizzleBillingAdapter } from "@codelitdev/billing/drizzle";
|
|
2
|
+
import { FakeBillingProvider } from "@codelitdev/billing/providers";
|
|
3
|
+
import { REFERENCE_OFFERS } from "@codelitdev/billing/testing";
|
|
4
|
+
import {
|
|
5
|
+
type BillingEngine,
|
|
6
|
+
createBilling,
|
|
7
|
+
MemoryAuditHook,
|
|
8
|
+
MemoryAuthorizationPort,
|
|
9
|
+
} from "@codelitdev/billing/workflows";
|
|
10
|
+
import type { Clock } from "@codelitdev/platform";
|
|
11
|
+
import * as billingSchema from "./db/schema/billing.generated.js";
|
|
12
|
+
import type { AppDb } from "./types.js";
|
|
13
|
+
|
|
14
|
+
export type BillingBundle = {
|
|
15
|
+
billing: BillingEngine;
|
|
16
|
+
fake: FakeBillingProvider;
|
|
17
|
+
authorization: MemoryAuthorizationPort;
|
|
18
|
+
audit: MemoryAuditHook;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export function composeBilling(db: AppDb, clock: Clock): BillingBundle {
|
|
22
|
+
const fake = new FakeBillingProvider({ clock });
|
|
23
|
+
fake.seedDefaultCatalog();
|
|
24
|
+
const authorization = new MemoryAuthorizationPort();
|
|
25
|
+
const audit = new MemoryAuditHook();
|
|
26
|
+
const store = drizzleBillingAdapter(db as never, {
|
|
27
|
+
schema: billingSchema,
|
|
28
|
+
clock,
|
|
29
|
+
});
|
|
30
|
+
const billing = createBilling({
|
|
31
|
+
database: store,
|
|
32
|
+
providers: [fake],
|
|
33
|
+
clock,
|
|
34
|
+
authorization,
|
|
35
|
+
hooks: {
|
|
36
|
+
audit,
|
|
37
|
+
lifecycle: {
|
|
38
|
+
async afterProjection() {
|
|
39
|
+
/* product-owned effect hook */
|
|
40
|
+
},
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
mode: "cloud",
|
|
44
|
+
checkoutProvider: "fake",
|
|
45
|
+
requestedRevision: 1,
|
|
46
|
+
requiredOfferKeys: REFERENCE_OFFERS.map((offer) => offer.key),
|
|
47
|
+
offers: REFERENCE_OFFERS,
|
|
48
|
+
returnUrlValidator: (url) => url.startsWith("https://app.test/"),
|
|
49
|
+
});
|
|
50
|
+
return { billing, fake, authorization, audit };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function runBoundedMaintenance(billing: BillingEngine): Promise<number> {
|
|
54
|
+
return billing.runWebhookInboxBatch({
|
|
55
|
+
limit: 25,
|
|
56
|
+
workerId: "reference-maintenance",
|
|
57
|
+
});
|
|
58
|
+
}
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
import { contract } from "@__PRODUCT_SLUG__/api-contract";
|
|
2
|
+
import { createObservability, redactText } from "@codelitdev/observability";
|
|
3
|
+
import { runPlatformConformance } from "@codelitdev/platform-conformance";
|
|
4
|
+
import { eq } from "drizzle-orm";
|
|
5
|
+
import { runBoundedMaintenance } from "./billing.js";
|
|
6
|
+
import { mcpFor } from "./dispatch.js";
|
|
7
|
+
import { createExpressApp } from "./express-app.js";
|
|
8
|
+
import type { Runtime } from "./runtime.js";
|
|
9
|
+
import type { SeededWorld } from "./seed.js";
|
|
10
|
+
|
|
11
|
+
type Principal = {
|
|
12
|
+
id: string;
|
|
13
|
+
sessionCookie: string;
|
|
14
|
+
oauthToken?: string;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export function createReferenceConformanceAdapter(
|
|
18
|
+
runtime: Runtime,
|
|
19
|
+
world: SeededWorld,
|
|
20
|
+
) {
|
|
21
|
+
const app = createExpressApp(runtime);
|
|
22
|
+
let server: ReturnType<typeof app.listen> | undefined;
|
|
23
|
+
let baseUrl: string | undefined;
|
|
24
|
+
async function ensureServer(): Promise<string> {
|
|
25
|
+
if (baseUrl) return baseUrl;
|
|
26
|
+
server = await new Promise<ReturnType<typeof app.listen>>((resolve) => {
|
|
27
|
+
const listening = app.listen(0, "127.0.0.1", () => resolve(listening));
|
|
28
|
+
});
|
|
29
|
+
const address = server.address();
|
|
30
|
+
if (!address || typeof address === "string") {
|
|
31
|
+
throw new Error("conformance_http_listener_unavailable");
|
|
32
|
+
}
|
|
33
|
+
baseUrl = `http://127.0.0.1:${address.port}`;
|
|
34
|
+
return baseUrl;
|
|
35
|
+
}
|
|
36
|
+
async function http(input: {
|
|
37
|
+
method: string;
|
|
38
|
+
path: string;
|
|
39
|
+
headers: Record<string, string | undefined>;
|
|
40
|
+
body?: unknown;
|
|
41
|
+
}) {
|
|
42
|
+
const url = `${await ensureServer()}${input.path}`;
|
|
43
|
+
const headers = new Headers();
|
|
44
|
+
for (const [name, value] of Object.entries(input.headers)) {
|
|
45
|
+
if (value !== undefined) headers.set(name, value);
|
|
46
|
+
}
|
|
47
|
+
const hasBody = input.body !== undefined;
|
|
48
|
+
if (hasBody && !headers.has("content-type")) {
|
|
49
|
+
headers.set("content-type", "application/json");
|
|
50
|
+
}
|
|
51
|
+
const response = await fetch(url, {
|
|
52
|
+
method: input.method,
|
|
53
|
+
headers,
|
|
54
|
+
...(hasBody ? { body: JSON.stringify(input.body) } : {}),
|
|
55
|
+
});
|
|
56
|
+
const text = await response.text();
|
|
57
|
+
let body: unknown = null;
|
|
58
|
+
if (text) {
|
|
59
|
+
try {
|
|
60
|
+
body = JSON.parse(text);
|
|
61
|
+
} catch {
|
|
62
|
+
body = text;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
status: response.status,
|
|
67
|
+
body,
|
|
68
|
+
headers: Object.fromEntries(response.headers.entries()),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
const owner: Principal = {
|
|
72
|
+
id: world.owner.id,
|
|
73
|
+
sessionCookie: world.owner.sessionCookie,
|
|
74
|
+
oauthToken: world.owner.oauthToken,
|
|
75
|
+
};
|
|
76
|
+
const member: Principal = {
|
|
77
|
+
id: world.member.id,
|
|
78
|
+
sessionCookie: world.member.sessionCookie,
|
|
79
|
+
};
|
|
80
|
+
let checkoutAuditEffectId: string | undefined;
|
|
81
|
+
return {
|
|
82
|
+
async reset() {
|
|
83
|
+
const schema = await import("./db/schema/index.js");
|
|
84
|
+
await runtime.db.delete(schema.notes).where(
|
|
85
|
+
// The conformance mutation has a fixed title and can be
|
|
86
|
+
// removed without disturbing seeded product data.
|
|
87
|
+
eq(schema.notes.title, "conformance note"),
|
|
88
|
+
);
|
|
89
|
+
},
|
|
90
|
+
async close() {
|
|
91
|
+
if (!server) return;
|
|
92
|
+
await new Promise<void>((resolve, reject) => {
|
|
93
|
+
server!.close((error) => (error ? reject(error) : resolve()));
|
|
94
|
+
});
|
|
95
|
+
server = undefined;
|
|
96
|
+
baseUrl = undefined;
|
|
97
|
+
},
|
|
98
|
+
fixtures: {
|
|
99
|
+
owner,
|
|
100
|
+
member,
|
|
101
|
+
outsider: {
|
|
102
|
+
id: world.outsider.id,
|
|
103
|
+
sessionCookie: world.outsider.sessionCookie,
|
|
104
|
+
},
|
|
105
|
+
tenantA: world.tenantA,
|
|
106
|
+
tenantB: world.tenantB,
|
|
107
|
+
},
|
|
108
|
+
credentials: {
|
|
109
|
+
async session(principal: Principal) {
|
|
110
|
+
return { cookie: principal.sessionCookie };
|
|
111
|
+
},
|
|
112
|
+
async oauth(principal: Principal) {
|
|
113
|
+
if (!principal.oauthToken) {
|
|
114
|
+
throw new Error("oauth_token_missing");
|
|
115
|
+
}
|
|
116
|
+
return { authorization: `Bearer ${principal.oauthToken}` };
|
|
117
|
+
},
|
|
118
|
+
async apiKey() {
|
|
119
|
+
return { apiKey: world.apiKeyA.raw };
|
|
120
|
+
},
|
|
121
|
+
async system() {
|
|
122
|
+
return { kind: "system" as const };
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
http,
|
|
126
|
+
async mcp(input: {
|
|
127
|
+
headers: Record<string, string | undefined>;
|
|
128
|
+
tool: string;
|
|
129
|
+
args?: unknown;
|
|
130
|
+
}) {
|
|
131
|
+
return http({
|
|
132
|
+
method: "POST",
|
|
133
|
+
path: "/mcp",
|
|
134
|
+
headers: input.headers,
|
|
135
|
+
body: {
|
|
136
|
+
jsonrpc: "2.0",
|
|
137
|
+
id: 1,
|
|
138
|
+
method: "tools/call",
|
|
139
|
+
params: { name: input.tool, arguments: input.args ?? {} },
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
},
|
|
143
|
+
async readAuditEvents() {
|
|
144
|
+
const schema = await import("./db/schema/index.js");
|
|
145
|
+
const rows = await runtime.db.select().from(schema.auditEvents);
|
|
146
|
+
return rows.map((row) => ({
|
|
147
|
+
action: row.action,
|
|
148
|
+
resourceId: row.resourceId,
|
|
149
|
+
actorId: row.actorId,
|
|
150
|
+
}));
|
|
151
|
+
},
|
|
152
|
+
async openapiDocument() {
|
|
153
|
+
const response = await http({
|
|
154
|
+
method: "GET",
|
|
155
|
+
path: "/openapi.json",
|
|
156
|
+
headers: {},
|
|
157
|
+
});
|
|
158
|
+
const document = response.body as { paths: Record<string, unknown> };
|
|
159
|
+
const contractOperationIds = Object.keys(contract);
|
|
160
|
+
return { paths: document.paths, contractOperationIds };
|
|
161
|
+
},
|
|
162
|
+
observability: {
|
|
163
|
+
async redact(secret: string) {
|
|
164
|
+
return redactText(secret);
|
|
165
|
+
},
|
|
166
|
+
async disabledDoesNotThrow() {
|
|
167
|
+
try {
|
|
168
|
+
const obs = createObservability({
|
|
169
|
+
serviceName: "reference-conformance",
|
|
170
|
+
environment: "test",
|
|
171
|
+
logs: { level: "silent" },
|
|
172
|
+
contextPolicy: { propertyAllowlist: new Set(["path"]) },
|
|
173
|
+
});
|
|
174
|
+
obs.captureEvent({ event: "noop", source: "conformance" });
|
|
175
|
+
obs.captureException({
|
|
176
|
+
error: new Error("noop"),
|
|
177
|
+
source: "conformance",
|
|
178
|
+
});
|
|
179
|
+
return { threw: false };
|
|
180
|
+
} catch {
|
|
181
|
+
return { threw: true };
|
|
182
|
+
}
|
|
183
|
+
},
|
|
184
|
+
async failingSinkDoesNotFailRequest() {
|
|
185
|
+
const obs = createObservability({
|
|
186
|
+
serviceName: "reference-conformance",
|
|
187
|
+
environment: "test",
|
|
188
|
+
logs: { level: "silent" },
|
|
189
|
+
contextPolicy: { propertyAllowlist: new Set(["path"]) },
|
|
190
|
+
posthog: {
|
|
191
|
+
apiKey: "phc_test",
|
|
192
|
+
client: {
|
|
193
|
+
captureException() {
|
|
194
|
+
throw new Error("sink-down");
|
|
195
|
+
},
|
|
196
|
+
capture() {
|
|
197
|
+
throw new Error("sink-down");
|
|
198
|
+
},
|
|
199
|
+
async shutdown() {
|
|
200
|
+
throw new Error("sink-down");
|
|
201
|
+
},
|
|
202
|
+
},
|
|
203
|
+
},
|
|
204
|
+
});
|
|
205
|
+
obs.captureEvent({ event: "x", source: "conformance" });
|
|
206
|
+
obs.captureException({
|
|
207
|
+
error: new Error("x"),
|
|
208
|
+
source: "conformance",
|
|
209
|
+
});
|
|
210
|
+
const health = await http({
|
|
211
|
+
method: "GET",
|
|
212
|
+
path: "/health",
|
|
213
|
+
headers: {},
|
|
214
|
+
});
|
|
215
|
+
return { requestStatus: health.status };
|
|
216
|
+
},
|
|
217
|
+
},
|
|
218
|
+
billingComposition: {
|
|
219
|
+
async generatedSchemaCurrent() {
|
|
220
|
+
const tables = await (
|
|
221
|
+
runtime.client as {
|
|
222
|
+
query(sql: string): Promise<{ rows: Array<unknown> }>;
|
|
223
|
+
}
|
|
224
|
+
).query(
|
|
225
|
+
"select tablename from pg_tables where schemaname = 'public' and tablename like 'billing_%'",
|
|
226
|
+
);
|
|
227
|
+
const names = new Set(
|
|
228
|
+
tables.rows.map((row) => (row as { tablename?: string }).tablename),
|
|
229
|
+
);
|
|
230
|
+
return [
|
|
231
|
+
"billing_catalog_revisions",
|
|
232
|
+
"billing_price_entries",
|
|
233
|
+
"billing_checkout_attempts",
|
|
234
|
+
"billing_subscriptions",
|
|
235
|
+
].every((name) => names.has(name));
|
|
236
|
+
},
|
|
237
|
+
async actionGrantRejected() {
|
|
238
|
+
try {
|
|
239
|
+
const now = runtime.clock.now();
|
|
240
|
+
await runtime.billing.billing.startCheckout({
|
|
241
|
+
grant: {
|
|
242
|
+
grantId: "conformance-invalid-grant",
|
|
243
|
+
actorId: world.owner.id,
|
|
244
|
+
action: "checkout",
|
|
245
|
+
target: { kind: "tenant", id: world.tenantB.id },
|
|
246
|
+
issuedAt: now,
|
|
247
|
+
expiresAt: new Date(now.getTime() + 60_000),
|
|
248
|
+
},
|
|
249
|
+
entity: { kind: "tenant", id: world.tenantB.id },
|
|
250
|
+
payer: {
|
|
251
|
+
id: world.owner.id,
|
|
252
|
+
email: "owner@example.test",
|
|
253
|
+
name: "Conformance owner",
|
|
254
|
+
},
|
|
255
|
+
offerKey: "pro_month",
|
|
256
|
+
catalogRevision: 1,
|
|
257
|
+
returnUrl: "https://app.test/billing",
|
|
258
|
+
});
|
|
259
|
+
return false;
|
|
260
|
+
} catch {
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
},
|
|
264
|
+
async fakeProviderWorks() {
|
|
265
|
+
const now = runtime.clock.now();
|
|
266
|
+
const grant = runtime.billing.authorization.issue({
|
|
267
|
+
grantId: "conformance-checkout-grant",
|
|
268
|
+
actorId: world.owner.id,
|
|
269
|
+
action: "checkout",
|
|
270
|
+
target: { kind: "tenant", id: world.tenantB.id },
|
|
271
|
+
issuedAt: now,
|
|
272
|
+
expiresAt: new Date(now.getTime() + 60_000),
|
|
273
|
+
});
|
|
274
|
+
const checkout = await runtime.billing.billing.startCheckout({
|
|
275
|
+
grant,
|
|
276
|
+
entity: { kind: "tenant", id: world.tenantB.id },
|
|
277
|
+
payer: {
|
|
278
|
+
id: world.owner.id,
|
|
279
|
+
email: "owner@example.test",
|
|
280
|
+
name: "Conformance owner",
|
|
281
|
+
},
|
|
282
|
+
offerKey: "pro_month",
|
|
283
|
+
catalogRevision: 1,
|
|
284
|
+
returnUrl: "https://app.test/billing",
|
|
285
|
+
});
|
|
286
|
+
checkoutAuditEffectId = `checkout:${checkout.attempt.id}:open`;
|
|
287
|
+
return (
|
|
288
|
+
checkout.attempt.status === "open" &&
|
|
289
|
+
checkout.checkoutUrl.startsWith("https://")
|
|
290
|
+
);
|
|
291
|
+
},
|
|
292
|
+
async maintenanceInvoked() {
|
|
293
|
+
const processed = await runBoundedMaintenance(runtime.billing.billing);
|
|
294
|
+
return processed >= 0;
|
|
295
|
+
},
|
|
296
|
+
async auditRecorded() {
|
|
297
|
+
return Boolean(
|
|
298
|
+
checkoutAuditEffectId &&
|
|
299
|
+
runtime.billing.audit.records.some(
|
|
300
|
+
(record) => record.effectId === checkoutAuditEffectId,
|
|
301
|
+
),
|
|
302
|
+
);
|
|
303
|
+
},
|
|
304
|
+
},
|
|
305
|
+
async shutdown() {
|
|
306
|
+
const mcp = mcpFor(runtime);
|
|
307
|
+
await mcp.shutdown();
|
|
308
|
+
const after = await http({
|
|
309
|
+
method: "POST",
|
|
310
|
+
path: "/mcp",
|
|
311
|
+
headers: {
|
|
312
|
+
authorization: `Bearer ${world.owner.oauthToken}`,
|
|
313
|
+
"x-tenant-id": world.tenantA.publicId,
|
|
314
|
+
},
|
|
315
|
+
body: { jsonrpc: "2.0", id: 99, method: "tools/list" },
|
|
316
|
+
});
|
|
317
|
+
return { mcpStatus: after.status };
|
|
318
|
+
},
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export async function runReferenceConformance(runtime: Runtime, world: SeededWorld) {
|
|
323
|
+
const adapter = createReferenceConformanceAdapter(runtime, world);
|
|
324
|
+
try {
|
|
325
|
+
return await runPlatformConformance(adapter, {
|
|
326
|
+
mcp: true,
|
|
327
|
+
billing: true,
|
|
328
|
+
observability: true,
|
|
329
|
+
openapi: true,
|
|
330
|
+
shutdown: true,
|
|
331
|
+
});
|
|
332
|
+
} finally {
|
|
333
|
+
await adapter.close?.();
|
|
334
|
+
}
|
|
335
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
|
|
5
|
+
const migrationDir = path.join(
|
|
6
|
+
path.dirname(fileURLToPath(import.meta.url)),
|
|
7
|
+
"migrations",
|
|
8
|
+
);
|
|
9
|
+
|
|
10
|
+
export const MIGRATION_FILES = [
|
|
11
|
+
"0000_auth.sql",
|
|
12
|
+
"0000_application.sql",
|
|
13
|
+
"0001_billing.sql",
|
|
14
|
+
] as const;
|
|
15
|
+
|
|
16
|
+
export async function applyMigrations(
|
|
17
|
+
exec: (sql: string) => Promise<unknown>,
|
|
18
|
+
): Promise<void> {
|
|
19
|
+
for (const file of MIGRATION_FILES) {
|
|
20
|
+
const sql = readFileSync(path.join(migrationDir, file), "utf8");
|
|
21
|
+
for (const statement of sql.split("--> statement-breakpoint")) {
|
|
22
|
+
const trimmed = statement.trim();
|
|
23
|
+
if (trimmed) await exec(trimmed);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|