express-file-cluster 0.9.6 → 0.10.2
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/auth/index.cjs +7 -6
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +5 -5
- package/dist/chunk-3SWI46YK.js +74 -0
- package/dist/chunk-3SWI46YK.js.map +1 -0
- package/dist/{chunk-DCJOWFVD.cjs → chunk-4GHK27JA.cjs} +3 -3
- package/dist/{chunk-DCJOWFVD.cjs.map → chunk-4GHK27JA.cjs.map} +1 -1
- package/dist/{chunk-NI2BNGGV.js → chunk-5LPRKZPB.js} +2 -2
- package/dist/chunk-74BSJXWD.cjs +220 -0
- package/dist/chunk-74BSJXWD.cjs.map +1 -0
- package/dist/{chunk-6KHBJOLB.cjs → chunk-7BC3AN7R.cjs} +14 -14
- package/dist/{chunk-6KHBJOLB.cjs.map → chunk-7BC3AN7R.cjs.map} +1 -1
- package/dist/chunk-AGOYTFRO.cjs +42 -0
- package/dist/chunk-AGOYTFRO.cjs.map +1 -0
- package/dist/{chunk-HBYSKULC.js → chunk-B6MB6HEG.js} +5 -1
- package/dist/chunk-B6MB6HEG.js.map +1 -0
- package/dist/{chunk-OFA7OGN5.js → chunk-BG4A7Z32.js} +176 -7
- package/dist/chunk-BG4A7Z32.js.map +1 -0
- package/dist/{chunk-45BWAR6P.js → chunk-C2FOZ7ME.js} +4 -4
- package/dist/chunk-CGY7JU4Y.cjs +8 -0
- package/dist/chunk-CGY7JU4Y.cjs.map +1 -0
- package/dist/{chunk-BBSZLGZW.js → chunk-DN4TCGYB.js} +43 -14
- package/dist/chunk-DN4TCGYB.js.map +1 -0
- package/dist/{chunk-TI24L4XE.cjs → chunk-H2PVWCWC.cjs} +6 -2
- package/dist/chunk-H2PVWCWC.cjs.map +1 -0
- package/dist/{chunk-TYCYYLLM.cjs → chunk-IUZ6A7PB.cjs} +20 -53
- package/dist/chunk-IUZ6A7PB.cjs.map +1 -0
- package/dist/{chunk-DUADUR6R.cjs → chunk-JP36TLL4.cjs} +171 -14
- package/dist/chunk-JP36TLL4.cjs.map +1 -0
- package/dist/chunk-KLWL7XSC.js +220 -0
- package/dist/chunk-KLWL7XSC.js.map +1 -0
- package/dist/{chunk-QL6EWT4B.cjs → chunk-M53GODCX.cjs} +44 -15
- package/dist/chunk-M53GODCX.cjs.map +1 -0
- package/dist/{chunk-7ZESZG3J.js → chunk-MUVO7MGS.js} +4 -4
- package/dist/{chunk-VWSUQKCJ.cjs → chunk-R2K7AFIB.cjs} +286 -117
- package/dist/chunk-R2K7AFIB.cjs.map +1 -0
- package/dist/{chunk-ULWNHN6P.js → chunk-RETV3GKE.js} +9 -42
- package/dist/chunk-RETV3GKE.js.map +1 -0
- package/dist/{chunk-7YEX4MQV.cjs → chunk-RPL2IFWK.cjs} +46 -7
- package/dist/chunk-RPL2IFWK.cjs.map +1 -0
- package/dist/{chunk-FMA76PRH.cjs → chunk-TBIVIR6L.cjs} +15 -15
- package/dist/{chunk-FMA76PRH.cjs.map → chunk-TBIVIR6L.cjs.map} +1 -1
- package/dist/{chunk-73XJUT2S.js → chunk-V73R76I4.js} +162 -5
- package/dist/chunk-V73R76I4.js.map +1 -0
- package/dist/chunk-XPY5TQDK.js +42 -0
- package/dist/chunk-XPY5TQDK.js.map +1 -0
- package/dist/{chunk-RGT4ZVHL.cjs → chunk-Y4NKIXUL.cjs} +110 -55
- package/dist/chunk-Y4NKIXUL.cjs.map +1 -0
- package/dist/{chunk-2SETEVMO.js → chunk-Y75V5FCU.js} +100 -45
- package/dist/chunk-Y75V5FCU.js.map +1 -0
- package/dist/cli/db-runner.cjs +2059 -126
- package/dist/cli/db-runner.cjs.map +1 -1
- package/dist/cli/db-runner.js +2034 -102
- package/dist/cli/db-runner.js.map +1 -1
- package/dist/cli/index.cjs +50 -29
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +39 -21
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/auth.md +23 -0
- package/dist/docs/api-reference/collection.md +44 -1
- package/dist/docs/api-reference/compose.md +1 -1
- package/dist/docs/api-reference/db.md +8 -0
- package/dist/docs/api-reference/ignite.md +13 -1
- package/dist/docs/api-reference/testing.md +26 -0
- package/dist/docs/api-reference/types.md +99 -0
- package/dist/docs/cli/add.md +2 -2
- package/dist/docs/cli/db.md +2 -2
- package/dist/docs/core-concepts/background-tasks.md +6 -3
- package/dist/docs/core-concepts/file-based-routing.md +2 -0
- package/dist/docs/core-concepts/middleware.md +2 -2
- package/dist/docs/getting-started/index.md +6 -1
- package/dist/docs/guides/authentication.md +33 -0
- package/dist/docs/guides/caching.md +34 -1
- package/dist/docs/guides/database.md +17 -0
- package/dist/docs/guides/environment-variables.md +6 -0
- package/dist/docs/guides/feature-matrix.md +58 -0
- package/dist/docs/guides/generated-portals.md +3 -1
- package/dist/docs/guides/logging.md +17 -0
- package/dist/docs/guides/migrations.md +26 -3
- package/dist/docs/guides/testing.md +31 -0
- package/dist/docs/guides/which-api.md +2 -2
- package/dist/docs/index.md +4 -1
- package/dist/docs/skills/SKILL.md +5 -1
- package/dist/docs/skills/api-surface.md +25 -4
- package/dist/docs/skills/auth-internals.md +14 -1
- package/dist/docs/skills/pre-flight.md +6 -0
- package/dist/docs/skills/routing-rules.md +1 -1
- package/dist/docs/skills/tasks-internals.md +4 -3
- package/dist/docs/skills/what-not-to-invent.md +13 -4
- package/dist/docs/versioning.md +1 -1
- package/dist/index.cjs +135 -255
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +228 -3
- package/dist/index.d.ts +228 -3
- package/dist/index.js +96 -217
- package/dist/index.js.map +1 -1
- package/dist/pgboss-backend-4X2YT4RB.js +14 -0
- package/dist/pgboss-backend-UXQ3O2WT.cjs +15 -0
- package/dist/pgboss-backend-UXQ3O2WT.cjs.map +1 -0
- package/dist/registry/index.json +39 -3
- package/dist/registry/js-mongo/account-security.json +1 -1
- package/dist/registry/js-mongo/admin-users.json +1 -1
- package/dist/registry/js-mongo/auth.json +1 -1
- package/dist/registry/js-mongo/auth@apple.json +1 -1
- package/dist/registry/js-mongo/auth@google.json +1 -1
- package/dist/registry/js-mongo/forgot-password.json +1 -1
- package/dist/registry/js-mongo/user-profile.json +1 -1
- package/dist/registry/js-mongo-collection/_base.json +1 -0
- package/dist/registry/js-mongo-collection/account-security.json +1 -0
- package/dist/registry/js-mongo-collection/account-settings.json +1 -0
- package/dist/registry/js-mongo-collection/admin-admins.json +1 -0
- package/dist/registry/js-mongo-collection/admin-analytics.json +1 -0
- package/dist/registry/js-mongo-collection/admin-billing.json +1 -0
- package/dist/registry/js-mongo-collection/admin-content.json +1 -0
- package/dist/registry/js-mongo-collection/admin-logs.json +1 -0
- package/dist/registry/js-mongo-collection/admin-support.json +1 -0
- package/dist/registry/js-mongo-collection/admin-system.json +1 -0
- package/dist/registry/js-mongo-collection/admin-users.json +1 -0
- package/dist/registry/js-mongo-collection/admin.json +1 -0
- package/dist/registry/js-mongo-collection/auth.json +1 -0
- package/dist/registry/js-mongo-collection/auth@apple.json +1 -0
- package/dist/registry/js-mongo-collection/auth@google.json +1 -0
- package/dist/registry/js-mongo-collection/billing.json +1 -0
- package/dist/registry/js-mongo-collection/email-client.json +1 -0
- package/dist/registry/js-mongo-collection/email-verification.json +1 -0
- package/dist/registry/js-mongo-collection/files.json +1 -0
- package/dist/registry/js-mongo-collection/forgot-password.json +1 -0
- package/dist/registry/js-mongo-collection/notifications.json +1 -0
- package/dist/registry/js-mongo-collection/support.json +1 -0
- package/dist/registry/js-mongo-collection/user-profile.json +1 -0
- package/dist/registry/js-pg-model/account-security.json +1 -1
- package/dist/registry/js-pg-model/admin-users.json +1 -1
- package/dist/registry/js-pg-model/auth.json +1 -1
- package/dist/registry/js-pg-model/auth@apple.json +1 -1
- package/dist/registry/js-pg-model/auth@google.json +1 -1
- package/dist/registry/js-pg-model/forgot-password.json +1 -1
- package/dist/registry/js-pg-model/user-profile.json +1 -1
- package/dist/registry/js-pg-table/account-security.json +1 -1
- package/dist/registry/js-pg-table/admin-users.json +1 -1
- package/dist/registry/js-pg-table/auth.json +1 -1
- package/dist/registry/js-pg-table/auth@apple.json +1 -1
- package/dist/registry/js-pg-table/auth@google.json +1 -1
- package/dist/registry/js-pg-table/forgot-password.json +1 -1
- package/dist/registry/js-pg-table/user-profile.json +1 -1
- package/dist/registry/ts-mongo/account-security.json +1 -1
- package/dist/registry/ts-mongo/admin-users.json +1 -1
- package/dist/registry/ts-mongo/auth.json +1 -1
- package/dist/registry/ts-mongo/auth@apple.json +1 -1
- package/dist/registry/ts-mongo/auth@google.json +1 -1
- package/dist/registry/ts-mongo/forgot-password.json +1 -1
- package/dist/registry/ts-mongo/user-profile.json +1 -1
- package/dist/registry/ts-mongo-collection/_base.json +1 -0
- package/dist/registry/ts-mongo-collection/account-security.json +1 -0
- package/dist/registry/ts-mongo-collection/account-settings.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-admins.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-analytics.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-billing.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-content.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-logs.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-support.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-system.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-users.json +1 -0
- package/dist/registry/ts-mongo-collection/admin.json +1 -0
- package/dist/registry/ts-mongo-collection/auth.json +1 -0
- package/dist/registry/ts-mongo-collection/auth@apple.json +1 -0
- package/dist/registry/ts-mongo-collection/auth@google.json +1 -0
- package/dist/registry/ts-mongo-collection/billing.json +1 -0
- package/dist/registry/ts-mongo-collection/email-client.json +1 -0
- package/dist/registry/ts-mongo-collection/email-verification.json +1 -0
- package/dist/registry/ts-mongo-collection/files.json +1 -0
- package/dist/registry/ts-mongo-collection/forgot-password.json +1 -0
- package/dist/registry/ts-mongo-collection/notifications.json +1 -0
- package/dist/registry/ts-mongo-collection/support.json +1 -0
- package/dist/registry/ts-mongo-collection/user-profile.json +1 -0
- package/dist/registry/ts-pg-model/account-security.json +1 -1
- package/dist/registry/ts-pg-model/admin-users.json +1 -1
- package/dist/registry/ts-pg-model/auth.json +1 -1
- package/dist/registry/ts-pg-model/auth@apple.json +1 -1
- package/dist/registry/ts-pg-model/auth@google.json +1 -1
- package/dist/registry/ts-pg-model/forgot-password.json +1 -1
- package/dist/registry/ts-pg-model/user-profile.json +1 -1
- package/dist/registry/ts-pg-table/account-security.json +1 -1
- package/dist/registry/ts-pg-table/admin-users.json +1 -1
- package/dist/registry/ts-pg-table/auth.json +1 -1
- package/dist/registry/ts-pg-table/auth@apple.json +1 -1
- package/dist/registry/ts-pg-table/auth@google.json +1 -1
- package/dist/registry/ts-pg-table/forgot-password.json +1 -1
- package/dist/registry/ts-pg-table/user-profile.json +1 -1
- package/dist/tasks/index.cjs +5 -2
- package/dist/tasks/index.cjs.map +1 -1
- package/dist/tasks/index.d.cts +4 -2
- package/dist/tasks/index.d.ts +4 -2
- package/dist/tasks/index.js +3 -1
- package/dist/testing-cjs.cjs +5 -0
- package/dist/testing.cjs +59 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +27 -0
- package/dist/testing.d.ts +27 -0
- package/dist/testing.js +58 -0
- package/dist/testing.js.map +1 -0
- package/dist/thread-runner.cjs +9 -0
- package/dist/thread-runner.cjs.map +1 -0
- package/dist/thread-runner.d.cts +3 -0
- package/dist/thread-runner.d.ts +3 -0
- package/dist/thread-runner.js +8 -0
- package/dist/thread-runner.js.map +1 -0
- package/dist/{types-DAsBKVM-.d.ts → types-CPMFTVXm.d.cts} +15 -1
- package/dist/{types-DAsBKVM-.d.cts → types-CPMFTVXm.d.ts} +15 -1
- package/package.json +6 -1
- package/dist/chunk-2SETEVMO.js.map +0 -1
- package/dist/chunk-73XJUT2S.js.map +0 -1
- package/dist/chunk-7YEX4MQV.cjs.map +0 -1
- package/dist/chunk-BBSZLGZW.js.map +0 -1
- package/dist/chunk-DUADUR6R.cjs.map +0 -1
- package/dist/chunk-HBYSKULC.js.map +0 -1
- package/dist/chunk-LJNSJFOL.js +0 -38
- package/dist/chunk-LJNSJFOL.js.map +0 -1
- package/dist/chunk-OFA7OGN5.js.map +0 -1
- package/dist/chunk-QL6EWT4B.cjs.map +0 -1
- package/dist/chunk-RGT4ZVHL.cjs.map +0 -1
- package/dist/chunk-TI24L4XE.cjs.map +0 -1
- package/dist/chunk-TYCYYLLM.cjs.map +0 -1
- package/dist/chunk-ULWNHN6P.js.map +0 -1
- package/dist/chunk-VWSUQKCJ.cjs.map +0 -1
- package/dist/pgboss-backend-DSO3QTNK.cjs +0 -14
- package/dist/pgboss-backend-DSO3QTNK.cjs.map +0 -1
- package/dist/pgboss-backend-I6DFUNRM.js +0 -14
- /package/dist/{chunk-NI2BNGGV.js.map → chunk-5LPRKZPB.js.map} +0 -0
- /package/dist/{chunk-45BWAR6P.js.map → chunk-C2FOZ7ME.js.map} +0 -0
- /package/dist/{chunk-7ZESZG3J.js.map → chunk-MUVO7MGS.js.map} +0 -0
- /package/dist/{pgboss-backend-I6DFUNRM.js.map → pgboss-backend-4X2YT4RB.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"auth@google","files":[{"path":"src/api/auth/google/callback.ts","content":"import { HttpError } from 'express-file-cluster';\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport type { Request, Response } from 'express';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: { description: 'Google redirects here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst GOOGLE_KEYS = createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs'));\n\nexport const GET = async (req: Request, res: Response) => {\n const { code, state, error } = req.query;\n if (error) throw new HttpError(400, `Google sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'google', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://oauth2.googleapis.com/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n client_secret: process.env.GOOGLE_CLIENT_SECRET ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n code_verifier: saved.verifier ?? '',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Google rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json()) as { id_token: string };\n\n const { payload } = await jwtVerify(id_token, GOOGLE_KEYS, {\n issuer: ['https://accounts.google.com', 'accounts.google.com'],\n audience: process.env.GOOGLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n const token = await signInWithOAuth(res, {\n provider: 'google',\n providerId: String(payload.sub),\n email: payload.email as string | undefined,\n emailVerified: payload.email_verified === true,\n name: payload.name as string | undefined,\n });\n res.redirect(await successRedirect(token, saved.appChallenge));\n};\n"},{"path":"src/api/auth/google/index.ts","content":"import type { Request, Response } from 'express';\nimport { appChallengeFrom, pkceChallenge, randomToken, rememberState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: { description: 'Start \"Sign in with Google\": redirects to Google.' },\n};\n\n// Redirects to Google's consent screen; Google sends the browser back to the callback route\n// (GOOGLE_REDIRECT_URI — register that exact URL in the Google Cloud console).\n// Bearer apps add ?code_challenge=… (see appChallengeFrom in src/lib/oauth).\nexport const GET = async (req: Request, res: Response) => {\n const appChallenge = appChallengeFrom(req.query);\n const state = randomToken();\n const nonce = randomToken();\n const verifier = randomToken();\n rememberState(res, 'google', { state, nonce, verifier, ...(appChallenge ? { appChallenge } : {}) });\n const params = new URLSearchParams({\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n response_type: 'code',\n scope: 'openid email profile',\n state,\n nonce,\n code_challenge: pkceChallenge(verifier),\n code_challenge_method: 'S256',\n prompt: 'select_account',\n });\n res.redirect(`https://accounts.google.com/o/oauth2/v2/auth?${params}`);\n};\n"},{"path":"src/api/auth/oauth/exchange.ts","content":"import type { Request, Response } from 'express';\nimport { exchangeCode } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: { description: 'Bearer apps: trade the one-time code from the sign-in redirect (plus the PKCE code_verifier) for a token.' },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n res.json({ token: await exchangeCode(req.body?.code, req.body?.code_verifier) });\n};\n"},{"path":"src/lib/oauth.ts","content":"import crypto from 'node:crypto';\nimport { HttpError, cache } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\nconst CODE_TTL_S = 60; // a bearer app has a minute to exchange its sign-in code\n\nexport interface OAuthState {\n state: string;\n nonce: string;\n verifier?: string;\n /** Bearer apps: the S256 challenge of a verifier only the app knows (app ↔ this server). */\n appChallenge?: string;\n}\n\nexport interface OAuthProfile {\n provider: 'google' | 'apple';\n providerId: string;\n email?: string;\n emailVerified: boolean;\n name?: string;\n}\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken(): string {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier: string): string {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res: Response,\n provider: string,\n data: OAuthState,\n crossSite = false,\n): void {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req: Request,\n res: Response,\n provider: string,\n state: unknown,\n): OAuthState | undefined {\n const name = `efc_oauth_${provider}`;\n const raw = (req as Request & { cookies?: Record<string, string> }).cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw) as OAuthState;\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res: Response, profile: OAuthProfile): Promise<string | undefined> {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findFirst({ where: { key } });\n let user = account ? await User.findUnique({ where: { id: account.user } }) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findFirst({ where: { email } })) ??\n (await User.create({ data: {\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n } }));\n if (account) await OAuthAccount.update({ where: { id: account.id }, data: { user: user.id } });\n else {\n await OAuthAccount.create({ data: {\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n user: user.id,\n } });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n // http-only: sets the cookie, returns undefined. bearer: returns the token.\n return issueToken(res, { id: user.id, role: user.role, email: user.email });\n}\n\n/**\n * Bearer apps start sign-in with `?code_challenge=<base64url SHA-256 of a random verifier>`\n * (PKCE, RFC 7636, between the app and this server). Only the app holding the verifier can\n * redeem the sign-in code — another app catching the myapp:// redirect can't.\n */\nexport function appChallengeFrom(query: Request['query']): string | undefined {\n const challenge = query.code_challenge;\n if (challenge === undefined) return undefined;\n if (typeof challenge !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(challenge)) {\n throw new HttpError(400, 'code_challenge must be the base64url SHA-256 of your code_verifier');\n }\n return challenge;\n}\n\n/**\n * Where the browser goes once signed in. With authStrategy 'bearer' the JWT never goes in the\n * URL (history, screenshots, logs): it gets a one-time code, valid for a minute, which the app\n * that started the sign-in trades for the token at POST /auth/oauth/exchange.\n */\nexport async function successRedirect(\n token?: string,\n appChallenge?: string,\n): Promise<string> {\n const to = process.env.OAUTH_SUCCESS_REDIRECT || '/';\n if (!token) return to;\n if (!appChallenge) {\n throw new HttpError(\n 400,\n 'Bearer sign-in needs a code_challenge — start at /auth/<provider>?code_challenge=…',\n );\n }\n const code = randomToken();\n await cache.set(`oauth:code:${code}`, { token, appChallenge }, { ttl: CODE_TTL_S });\n return `${to}#code=${code}`;\n}\n\n/**\n * The token for a one-time sign-in code, given the verifier behind the challenge the sign-in\n * started with. Once: a second use (or after a minute) gets 400.\n */\nexport async function exchangeCode(code: unknown, verifier: unknown): Promise<string> {\n if (typeof code !== 'string' || !code) throw new HttpError(400, 'code is required');\n if (typeof verifier !== 'string' || !/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)) {\n throw new HttpError(400, 'code_verifier is required (43-128 characters)');\n }\n const key = `oauth:code:${code}`;\n const saved = await cache.get<{ token: string; appChallenge: string }>(key);\n const expected = Buffer.from(saved?.appChallenge ?? '');\n const actual = Buffer.from(pkceChallenge(verifier));\n // A wrong verifier leaves the code alone, so it can't be used to burn someone's sign-in.\n if (!saved || expected.length !== actual.length || !crypto.timingSafeEqual(expected, actual)) {\n throw new HttpError(400, 'Invalid or expired sign-in code');\n }\n // del is atomic: of two requests racing with the same code, only one removes it.\n if ((await cache.del(key)) !== 1) throw new HttpError(400, 'Invalid or expired sign-in code');\n return saved.token;\n}\n"},{"path":"src/model/OAuthAccount.ts","content":"import { defineTable } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineTable('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n user: { type: 'uuid', ref: 'User', required: true, onDelete: 'cascade' },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"GOOGLE_CLIENT_ID","value":"","example":"your-client-id.apps.googleusercontent.com"},{"key":"GOOGLE_CLIENT_SECRET","value":"","example":"your-client-secret"},{"key":"GOOGLE_REDIRECT_URI","value":"http://localhost:3000/v1/api/auth/google/callback","example":"https://api.yourapp.com/v1/api/auth/google/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}
|
|
1
|
+
{"name":"auth@google","files":[{"path":"src/api/auth/google/callback.ts","content":"import { HttpError } from 'express-file-cluster';\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport type { Request, Response } from 'express';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: { description: 'Google redirects here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst GOOGLE_KEYS = createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs'));\n\nexport const GET = async (req: Request, res: Response) => {\n const { code, state, error } = req.query;\n if (error) throw new HttpError(400, `Google sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'google', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://oauth2.googleapis.com/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n client_secret: process.env.GOOGLE_CLIENT_SECRET ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n code_verifier: saved.verifier ?? '',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Google rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json()) as { id_token: string };\n\n const { payload } = await jwtVerify(id_token, GOOGLE_KEYS, {\n issuer: ['https://accounts.google.com', 'accounts.google.com'],\n audience: process.env.GOOGLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n const token = await signInWithOAuth(res, {\n provider: 'google',\n providerId: String(payload.sub),\n email: payload.email as string | undefined,\n emailVerified: payload.email_verified === true,\n name: payload.name as string | undefined,\n });\n res.redirect(await successRedirect(token, saved.appChallenge));\n};\n"},{"path":"src/api/auth/google/index.ts","content":"import type { Request, Response } from 'express';\nimport { appChallengeFrom, pkceChallenge, randomToken, rememberState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: { description: 'Start \"Sign in with Google\": redirects to Google.' },\n};\n\n// Redirects to Google's consent screen; Google sends the browser back to the callback route\n// (GOOGLE_REDIRECT_URI — register that exact URL in the Google Cloud console).\n// Bearer apps add ?code_challenge=… (see appChallengeFrom in src/lib/oauth).\nexport const GET = async (req: Request, res: Response) => {\n const appChallenge = appChallengeFrom(req.query);\n const state = randomToken();\n const nonce = randomToken();\n const verifier = randomToken();\n rememberState(res, 'google', { state, nonce, verifier, ...(appChallenge ? { appChallenge } : {}) });\n const params = new URLSearchParams({\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n response_type: 'code',\n scope: 'openid email profile',\n state,\n nonce,\n code_challenge: pkceChallenge(verifier),\n code_challenge_method: 'S256',\n prompt: 'select_account',\n });\n res.redirect(`https://accounts.google.com/o/oauth2/v2/auth?${params}`);\n};\n"},{"path":"src/api/auth/oauth/exchange.ts","content":"import type { Request, Response } from 'express';\nimport { exchangeCode } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: { description: 'Bearer apps: trade the one-time code from the sign-in redirect (plus the PKCE code_verifier) for a token.' },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n res.json({ token: await exchangeCode(req.body?.code, req.body?.code_verifier) });\n};\n"},{"path":"src/lib/oauth.ts","content":"import crypto from 'node:crypto';\nimport { HttpError, cache } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\nconst CODE_TTL_S = 60; // a bearer app has a minute to exchange its sign-in code\n\nexport interface OAuthState {\n state: string;\n nonce: string;\n verifier?: string;\n /** Bearer apps: the S256 challenge of a verifier only the app knows (app ↔ this server). */\n appChallenge?: string;\n}\n\nexport interface OAuthProfile {\n provider: 'google' | 'apple';\n providerId: string;\n email?: string;\n emailVerified: boolean;\n name?: string;\n}\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken(): string {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier: string): string {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res: Response,\n provider: string,\n data: OAuthState,\n crossSite = false,\n): void {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req: Request,\n res: Response,\n provider: string,\n state: unknown,\n): OAuthState | undefined {\n const name = `efc_oauth_${provider}`;\n const raw = (req as Request & { cookies?: Record<string, string> }).cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw) as OAuthState;\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res: Response, profile: OAuthProfile): Promise<string | undefined> {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findFirst({ where: { key } });\n let user = account ? await User.findUnique({ where: { id: account.user } }) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findFirst({ where: { email } })) ??\n (await User.create({ data: {\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n } }));\n if (account) await OAuthAccount.update({ where: { id: account.id }, data: { user: user.id } });\n else {\n await OAuthAccount.create({ data: {\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n user: user.id,\n } });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n if (user.twoFactorEnabled) throw new HttpError(403, 'Use password login with an authenticator code for this account');\n // http-only: sets the cookie, returns undefined. bearer: returns the token.\n return issueToken(res, { id: user.id, role: user.role, email: user.email });\n}\n\n/**\n * Bearer apps start sign-in with `?code_challenge=<base64url SHA-256 of a random verifier>`\n * (PKCE, RFC 7636, between the app and this server). Only the app holding the verifier can\n * redeem the sign-in code — another app catching the myapp:// redirect can't.\n */\nexport function appChallengeFrom(query: Request['query']): string | undefined {\n const challenge = query.code_challenge;\n if (challenge === undefined) return undefined;\n if (typeof challenge !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(challenge)) {\n throw new HttpError(400, 'code_challenge must be the base64url SHA-256 of your code_verifier');\n }\n return challenge;\n}\n\n/**\n * Where the browser goes once signed in. With authStrategy 'bearer' the JWT never goes in the\n * URL (history, screenshots, logs): it gets a one-time code, valid for a minute, which the app\n * that started the sign-in trades for the token at POST /auth/oauth/exchange.\n */\nexport async function successRedirect(\n token?: string,\n appChallenge?: string,\n): Promise<string> {\n const to = process.env.OAUTH_SUCCESS_REDIRECT || '/';\n if (!token) return to;\n if (!appChallenge) {\n throw new HttpError(\n 400,\n 'Bearer sign-in needs a code_challenge — start at /auth/<provider>?code_challenge=…',\n );\n }\n const code = randomToken();\n await cache.set(`oauth:code:${code}`, { token, appChallenge }, { ttl: CODE_TTL_S });\n return `${to}#code=${code}`;\n}\n\n/**\n * The token for a one-time sign-in code, given the verifier behind the challenge the sign-in\n * started with. Once: a second use (or after a minute) gets 400.\n */\nexport async function exchangeCode(code: unknown, verifier: unknown): Promise<string> {\n if (typeof code !== 'string' || !code) throw new HttpError(400, 'code is required');\n if (typeof verifier !== 'string' || !/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)) {\n throw new HttpError(400, 'code_verifier is required (43-128 characters)');\n }\n const key = `oauth:code:${code}`;\n const saved = await cache.get<{ token: string; appChallenge: string }>(key);\n const expected = Buffer.from(saved?.appChallenge ?? '');\n const actual = Buffer.from(pkceChallenge(verifier));\n // A wrong verifier leaves the code alone, so it can't be used to burn someone's sign-in.\n if (!saved || expected.length !== actual.length || !crypto.timingSafeEqual(expected, actual)) {\n throw new HttpError(400, 'Invalid or expired sign-in code');\n }\n // del is atomic: of two requests racing with the same code, only one removes it.\n if ((await cache.del(key)) !== 1) throw new HttpError(400, 'Invalid or expired sign-in code');\n return saved.token;\n}\n"},{"path":"src/model/OAuthAccount.ts","content":"import { defineTable } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineTable('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n user: { type: 'uuid', ref: 'User', required: true, onDelete: 'cascade' },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"GOOGLE_CLIENT_ID","value":"","example":"your-client-id.apps.googleusercontent.com"},{"key":"GOOGLE_CLIENT_SECRET","value":"","example":"your-client-secret"},{"key":"GOOGLE_REDIRECT_URI","value":"http://localhost:3000/v1/api/auth/google/callback","example":"https://api.yourapp.com/v1/api/auth/google/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"forgot-password","files":[{"path":"src/api/auth/forgot-password.ts","content":"import type { Request, Response } from 'express';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Send a password reset email to the given address.',\n request: { body: { email: 'user@example.com' } },\n response: { status: 200, body: { message: 'Reset email sent' } },\n },\n};\n\nconst RESET_TOKEN_TTL_MS = 1000 * 60 * 60; // 1 hour\n\nexport const POST = async (req: Request, res: Response) => {\n const { email } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof email !== 'string' || !email) return res.status(400).json({ error: 'email is required' });\n\n const user = await User.findFirst({ where: { email } });\n const admin = user ? null : await Admin.findFirst({ where: { email } });\n\n // Always respond the same way whether or not the account exists, so this\n // endpoint can't be used to enumerate registered emails.\n if (user || admin) {\n const resetToken = crypto.randomBytes(32).toString('hex');\n const resetTokenExpiry = new Date(Date.now() + RESET_TOKEN_TTL_MS);\n if (user) await User.update({ where: { id: user.id }, data: { resetToken, resetTokenExpiry } });\n else if (admin) await Admin.update({ where: { id: admin.id }, data: { resetToken, resetTokenExpiry } });\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Reset your password',\n body: 'Reset your password: ' + appUrl + '/auth/reset-password?token=' + resetToken,\n });\n }\n\n res.json({ message: 'Reset email sent' });\n};\n"},{"path":"src/api/auth/reset-password.ts","content":"import type { Request, Response } from 'express';\nimport { hashPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Reset password using a valid reset token.',\n request: { body: { token: 'reset-token', password: 'newpassword' } },\n response: { status: 200, body: { message: 'Password reset successfully' } },\n },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { token, password } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof token !== 'string' || typeof password !== 'string' || !token || !password) {\n return res.status(400).json({ error: 'token and password are required' });\n }\n\n const user = await User.findFirst({ where: { resetToken: token } });\n const admin = user ? null : await Admin.findFirst({ where: { resetToken: token } });\n const account = user || admin;\n\n if (!account || !account.resetTokenExpiry || new Date(account.resetTokenExpiry) < new Date()) {\n return res.status(400).json({ error: 'Invalid or expired reset token' });\n }\n\n const hashed = await hashPassword(password);\n
|
|
1
|
+
{"name":"forgot-password","files":[{"path":"src/api/auth/forgot-password.ts","content":"import type { Request, Response } from 'express';\nimport crypto from 'node:crypto';\nimport { rateLimit } from 'express-file-cluster';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Send a password reset email to the given address.',\n request: { body: { email: 'user@example.com' } },\n response: { status: 200, body: { message: 'Reset email sent' } },\n },\n};\n\n// 5 reset emails per hour per address — keeps the endpoint from mail-bombing someone.\nexport const middlewares = [\n rateLimit({ window: '1h', max: 5, key: (req) => String(req.body?.email ?? '').toLowerCase() }),\n];\n\nconst RESET_TOKEN_TTL_MS = 1000 * 60 * 60; // 1 hour\n\nexport const POST = async (req: Request, res: Response) => {\n const { email } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof email !== 'string' || !email) return res.status(400).json({ error: 'email is required' });\n\n const user = await User.findFirst({ where: { email } });\n const admin = user ? null : await Admin.findFirst({ where: { email } });\n\n // Always respond the same way whether or not the account exists, so this\n // endpoint can't be used to enumerate registered emails.\n if (user || admin) {\n const resetToken = crypto.randomBytes(32).toString('hex');\n const resetTokenExpiry = new Date(Date.now() + RESET_TOKEN_TTL_MS);\n if (user) await User.update({ where: { id: user.id }, data: { resetToken, resetTokenExpiry } });\n else if (admin) await Admin.update({ where: { id: admin.id }, data: { resetToken, resetTokenExpiry } });\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Reset your password',\n body: 'Reset your password: ' + appUrl + '/auth/reset-password?token=' + resetToken,\n });\n }\n\n res.json({ message: 'Reset email sent' });\n};\n"},{"path":"src/api/auth/reset-password.ts","content":"import type { Request, Response } from 'express';\nimport { hashPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { updateSecurity } from '../../lib/two-factor.js';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Reset password using a valid reset token.',\n request: { body: { token: 'reset-token', password: 'newpassword' } },\n response: { status: 200, body: { message: 'Password reset successfully' } },\n },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { token, password } = req.body ?? {};\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof token !== 'string' || typeof password !== 'string' || !token || !password) {\n return res.status(400).json({ error: 'token and password are required' });\n }\n\n const user = await User.findFirst({ where: { resetToken: token } });\n const admin = user ? null : await Admin.findFirst({ where: { resetToken: token } });\n const account = user || admin;\n\n if (!account || !account.resetTokenExpiry || new Date(account.resetTokenExpiry) < new Date()) {\n return res.status(400).json({ error: 'Invalid or expired reset token' });\n }\n\n const hashed = await hashPassword(password);\n const consumed = await updateSecurity(user ? User : Admin, { id: account.id, resetToken: token, resetTokenExpiry: { gt: new Date() } }, { password: hashed, resetToken: '', resetTokenExpiry: new Date(0), refreshToken: '', refreshTokenExpiry: new Date(0), twoFactorPendingSecret: '', twoFactorPendingMethod: '', twoFactorPendingExpiry: new Date(0), twoFactorEmailHash: '', twoFactorEmailExpiry: new Date(0) });\n if (!consumed) return res.status(400).json({ error: 'Invalid, expired or already used reset token' });\n // Tokens issued with the old password stop working everywhere.\n await revokeAllSessions(account.id);\n\n res.json({ message: 'Password reset successfully' });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"user-profile","files":[{"path":"src/api/user/profile.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: \"Fetch the authenticated user's profile.\",\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n PUT: {\n description: \"Update the authenticated user's profile.\",\n request: { body: { name: 'Jane Doe', email: 'jane@example.com' } },\n response: { status: 200, body: { message: 'Profile updated', user: { id: '1', role: 'user', email: 'jane@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { id } = (req as any).user;\n const user = await User.findUnique({ where: { id } });\n if (!user) return res.status(404).json({ error: 'User not found' });\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, ...safe } = user;\n res.json({ user: safe });\n};\n\nexport const PUT = async (req: Request, res: Response) => {\n const { id } = (req as any).user;\n const { name, email } = req.body;\n const updated = await User.update({ where: { id }, data: { name, email } });\n if (!updated) return res.status(404).json({ error: 'User not found' });\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, ...safe } = updated;\n res.json({ message: 'Profile updated', user: safe });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
1
|
+
{"name":"user-profile","files":[{"path":"src/api/user/profile.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: \"Fetch the authenticated user's profile.\",\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n PUT: {\n description: \"Update the authenticated user's profile.\",\n request: { body: { name: 'Jane Doe', email: 'jane@example.com' } },\n response: { status: 200, body: { message: 'Profile updated', user: { id: '1', role: 'user', email: 'jane@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { id } = (req as any).user;\n const user = await User.findUnique({ where: { id } });\n if (!user) return res.status(404).json({ error: 'User not found' });\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, twoFactorSecret: _tfs, twoFactorPendingSecret: _tfp, twoFactorPendingExpiry: _tfpe, twoFactorLastStep: _tfl, twoFactorEmailHash: _tfeh, twoFactorEmailExpiry: _tfee, twoFactorEmailPurpose: _tfep, twoFactorPendingMethod: _tfpm, ...safe } = user;\n res.json({ user: safe });\n};\n\nexport const PUT = async (req: Request, res: Response) => {\n const { id } = (req as any).user;\n const { name, email } = req.body ?? {};\n if ((name !== undefined && typeof name !== 'string') || (email !== undefined && typeof email !== 'string')) return res.status(400).json({ error: 'name and email must be strings' });\n const existing = await User.findUnique({ where: { id } });\n if (!existing) return res.status(404).json({ error: 'User not found' });\n if (email !== undefined && email !== existing.email && existing.twoFactorEnabled && existing.twoFactorMethod === 'email') return res.status(409).json({ error: 'Disable email 2FA before changing the email address' });\n const updated = await User.update({ where: { id }, data: { name, email } });\n if (!updated) return res.status(404).json({ error: 'User not found' });\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, twoFactorSecret: _tfs, twoFactorPendingSecret: _tfp, twoFactorPendingExpiry: _tfpe, twoFactorLastStep: _tfl, twoFactorEmailHash: _tfeh, twoFactorEmailExpiry: _tfee, twoFactorEmailPurpose: _tfep, twoFactorPendingMethod: _tfpm, ...safe } = updated;\n res.json({ message: 'Profile updated', user: safe });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
package/dist/tasks/index.cjs
CHANGED
|
@@ -5,13 +5,16 @@
|
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
|
|
8
|
-
var _chunkTI24L4XEcjs = require('../chunk-TI24L4XE.cjs');
|
|
9
8
|
|
|
9
|
+
var _chunkH2PVWCWCcjs = require('../chunk-H2PVWCWC.cjs');
|
|
10
|
+
require('../chunk-CGY7JU4Y.cjs');
|
|
10
11
|
|
|
11
12
|
|
|
12
13
|
|
|
13
14
|
|
|
14
15
|
|
|
15
16
|
|
|
16
|
-
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
exports.ENQUEUE_BRIDGE = _chunkH2PVWCWCcjs.ENQUEUE_BRIDGE; exports.defineTask = _chunkH2PVWCWCcjs.defineTask; exports.enqueue = _chunkH2PVWCWCcjs.enqueue; exports.listTasks = _chunkH2PVWCWCcjs.listTasks; exports.registerTask = _chunkH2PVWCWCcjs.registerTask; exports.setEnqueueImpl = _chunkH2PVWCWCcjs.setEnqueueImpl; exports.taskRegistry = _chunkH2PVWCWCcjs.taskRegistry;
|
|
17
20
|
//# sourceMappingURL=index.cjs.map
|
package/dist/tasks/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/tasks/index.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACF,
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/tasks/index.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,oXAAC","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/tasks/index.cjs"}
|
package/dist/tasks/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { T as TaskOptions, a as TaskDefinition } from '../types-
|
|
1
|
+
import { T as TaskOptions, a as TaskDefinition } from '../types-CPMFTVXm.cjs';
|
|
2
2
|
import 'express';
|
|
3
3
|
|
|
4
4
|
declare const taskRegistry: Map<string, TaskDefinition<unknown>>;
|
|
@@ -10,6 +10,8 @@ type DefineTaskOverload = {
|
|
|
10
10
|
declare const defineTask: DefineTaskOverload;
|
|
11
11
|
type EnqueueImpl = (name: string, payload: unknown) => Promise<void>;
|
|
12
12
|
declare function setEnqueueImpl(impl: EnqueueImpl): void;
|
|
13
|
+
/** Set inside `{ thread: true }` task threads: forwards enqueue() to the main thread. */
|
|
14
|
+
declare const ENQUEUE_BRIDGE: unique symbol;
|
|
13
15
|
declare function enqueue<T>(name: string, payload: T): Promise<void>;
|
|
14
16
|
declare function registerTask(name: string, def: TaskDefinition): void;
|
|
15
17
|
/**
|
|
@@ -25,4 +27,4 @@ declare function listTasks(): ReadonlyArray<{
|
|
|
25
27
|
options: TaskOptions;
|
|
26
28
|
}>;
|
|
27
29
|
|
|
28
|
-
export { defineTask, enqueue, listTasks, registerTask, setEnqueueImpl, taskRegistry };
|
|
30
|
+
export { ENQUEUE_BRIDGE, defineTask, enqueue, listTasks, registerTask, setEnqueueImpl, taskRegistry };
|
package/dist/tasks/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { T as TaskOptions, a as TaskDefinition } from '../types-
|
|
1
|
+
import { T as TaskOptions, a as TaskDefinition } from '../types-CPMFTVXm.js';
|
|
2
2
|
import 'express';
|
|
3
3
|
|
|
4
4
|
declare const taskRegistry: Map<string, TaskDefinition<unknown>>;
|
|
@@ -10,6 +10,8 @@ type DefineTaskOverload = {
|
|
|
10
10
|
declare const defineTask: DefineTaskOverload;
|
|
11
11
|
type EnqueueImpl = (name: string, payload: unknown) => Promise<void>;
|
|
12
12
|
declare function setEnqueueImpl(impl: EnqueueImpl): void;
|
|
13
|
+
/** Set inside `{ thread: true }` task threads: forwards enqueue() to the main thread. */
|
|
14
|
+
declare const ENQUEUE_BRIDGE: unique symbol;
|
|
13
15
|
declare function enqueue<T>(name: string, payload: T): Promise<void>;
|
|
14
16
|
declare function registerTask(name: string, def: TaskDefinition): void;
|
|
15
17
|
/**
|
|
@@ -25,4 +27,4 @@ declare function listTasks(): ReadonlyArray<{
|
|
|
25
27
|
options: TaskOptions;
|
|
26
28
|
}>;
|
|
27
29
|
|
|
28
|
-
export { defineTask, enqueue, listTasks, registerTask, setEnqueueImpl, taskRegistry };
|
|
30
|
+
export { ENQUEUE_BRIDGE, defineTask, enqueue, listTasks, registerTask, setEnqueueImpl, taskRegistry };
|
package/dist/tasks/index.js
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import {
|
|
2
|
+
ENQUEUE_BRIDGE,
|
|
2
3
|
defineTask,
|
|
3
4
|
enqueue,
|
|
4
5
|
listTasks,
|
|
5
6
|
registerTask,
|
|
6
7
|
setEnqueueImpl,
|
|
7
8
|
taskRegistry
|
|
8
|
-
} from "../chunk-
|
|
9
|
+
} from "../chunk-B6MB6HEG.js";
|
|
9
10
|
export {
|
|
11
|
+
ENQUEUE_BRIDGE,
|
|
10
12
|
defineTask,
|
|
11
13
|
enqueue,
|
|
12
14
|
listTasks,
|
package/dist/testing.cjs
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
var _chunk74BSJXWDcjs = require('./chunk-74BSJXWD.cjs');
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
var _chunkY4NKIXULcjs = require('./chunk-Y4NKIXUL.cjs');
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
var _chunk4GHK27JAcjs = require('./chunk-4GHK27JA.cjs');
|
|
12
|
+
require('./chunk-TBIVIR6L.cjs');
|
|
13
|
+
require('./chunk-AGOYTFRO.cjs');
|
|
14
|
+
require('./chunk-RPL2IFWK.cjs');
|
|
15
|
+
require('./chunk-H2PVWCWC.cjs');
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
var _chunkJP36TLL4cjs = require('./chunk-JP36TLL4.cjs');
|
|
19
|
+
require('./chunk-CGY7JU4Y.cjs');
|
|
20
|
+
|
|
21
|
+
// src/testing.ts
|
|
22
|
+
var _path = require('path'); var _path2 = _interopRequireDefault(_path);
|
|
23
|
+
var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
|
|
24
|
+
var _express = require('express'); var _express2 = _interopRequireDefault(_express);
|
|
25
|
+
async function createTestApp(options) {
|
|
26
|
+
if (typeof options.apiDir !== "string" || !options.apiDir.trim()) {
|
|
27
|
+
throw new Error("[EFC] createTestApp requires a nonempty apiDir");
|
|
28
|
+
}
|
|
29
|
+
const apiDir = _path2.default.resolve(options.apiDir);
|
|
30
|
+
if (!_fs2.default.existsSync(apiDir) || !_fs2.default.statSync(apiDir).isDirectory()) {
|
|
31
|
+
throw new Error(`[EFC] createTestApp apiDir is not a directory: ${apiDir}`);
|
|
32
|
+
}
|
|
33
|
+
_chunkJP36TLL4cjs.configureLogger.call(void 0, false);
|
|
34
|
+
if (options.auth) {
|
|
35
|
+
_chunkY4NKIXULcjs.configureAuth.call(void 0, {
|
|
36
|
+
secret: options.auth.secret,
|
|
37
|
+
strategy: _nullishCoalesce(options.auth.strategy, () => ( "http-only")),
|
|
38
|
+
expiresIn: _nullishCoalesce(options.auth.expiresIn, () => ( "1h")),
|
|
39
|
+
...options.auth.cookieDomain !== void 0 && { cookieDomain: options.auth.cookieDomain }
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
const app = _chunk74BSJXWDcjs.createHttpApp.call(void 0, {
|
|
43
|
+
cors: false,
|
|
44
|
+
...options.globalMiddlewares !== void 0 && {
|
|
45
|
+
globalMiddlewares: options.globalMiddlewares
|
|
46
|
+
},
|
|
47
|
+
...options.requestTimeout !== void 0 && { requestTimeout: options.requestTimeout },
|
|
48
|
+
...options.trustProxy !== void 0 && { trustProxy: options.trustProxy }
|
|
49
|
+
});
|
|
50
|
+
const router = _express2.default.Router();
|
|
51
|
+
await _chunk74BSJXWDcjs.mountRoutes.call(void 0, router, _chunk4GHK27JAcjs.scanDir.call(void 0, apiDir));
|
|
52
|
+
app.use(_nullishCoalesce(options.basePath, () => ( "/v1/api")), router);
|
|
53
|
+
_chunk74BSJXWDcjs.mountErrorHandler.call(void 0, app, options.onError);
|
|
54
|
+
return app;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
exports.createTestApp = createTestApp;
|
|
59
|
+
//# sourceMappingURL=testing.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/testing.cjs","../src/testing.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B,gCAA6B;AAC7B,gCAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B;AACA;ACpBA,wEAAiB;AACjB,gEAAe;AACf,oFAAoB;AA8BpB,MAAA,SAAsB,aAAA,CAAc,OAAA,EAAmD;AACrF,EAAA,GAAA,CAAI,OAAO,OAAA,CAAQ,OAAA,IAAW,SAAA,GAAY,CAAC,OAAA,CAAQ,MAAA,CAAO,IAAA,CAAK,CAAA,EAAG;AAChE,IAAA,MAAM,IAAI,KAAA,CAAM,gDAAgD,CAAA;AAAA,EAClE;AACA,EAAA,MAAM,OAAA,EAAS,cAAA,CAAK,OAAA,CAAQ,OAAA,CAAQ,MAAM,CAAA;AAC1C,EAAA,GAAA,CAAI,CAAC,YAAA,CAAG,UAAA,CAAW,MAAM,EAAA,GAAK,CAAC,YAAA,CAAG,QAAA,CAAS,MAAM,CAAA,CAAE,WAAA,CAAY,CAAA,EAAG;AAChE,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,+CAAA,EAAkD,MAAM,CAAA,CAAA;AAC1E,EAAA;AACqB,EAAA;AACH,EAAA;AACF,IAAA;AACS,MAAA;AACc,MAAA;AACE,MAAA;AACkC,MAAA;AACxE,IAAA;AACH,EAAA;AAC0B,EAAA;AAClB,IAAA;AACyC,IAAA;AAClB,MAAA;AAC7B,IAAA;AACsE,IAAA;AACG,IAAA;AAC1E,EAAA;AAC6B,EAAA;AACW,EAAA;AACI,EAAA;AACP,EAAA;AAC/B,EAAA;AACT;ADP6E;AACA;AACA","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/testing.cjs","sourcesContent":[null,"import path from 'node:path';\nimport fs from 'node:fs';\nimport express from 'express';\nimport type { AuthStrategy, EFCConfig } from './types.js';\nimport { configureAuth } from './auth/index.js';\nimport { configureLogger } from './logger.js';\nimport { createHttpApp, mountErrorHandler } from './http-app.js';\nimport { scanDir } from './router/scan.js';\nimport { mountRoutes } from './router/mount.js';\n\nexport interface TestAppOptions {\n /** Explicit fixtures/app API directory. Does not change cwd or ignite() conventions. */\n apiDir: string;\n basePath?: string;\n globalMiddlewares?: express.RequestHandler[];\n requestTimeout?: number;\n trustProxy?: EFCConfig['trustProxy'];\n onError?: express.ErrorRequestHandler;\n /** Auth is process-wide, as in ignite(); use one configuration per test process. */\n auth?: {\n secret: string;\n strategy?: AuthStrategy;\n expiresIn?: string;\n cookieDomain?: string;\n };\n}\n\n/**\n * Mounts real file-based routes on an Express app for supertest (or another HTTP\n * harness). Does not listen, fork workers, start services, or install signal handlers.\n * Models and task queues need separately configured integration fixtures.\n */\nexport async function createTestApp(options: TestAppOptions): Promise<express.Express> {\n if (typeof options.apiDir !== 'string' || !options.apiDir.trim()) {\n throw new Error('[EFC] createTestApp requires a nonempty apiDir');\n }\n const apiDir = path.resolve(options.apiDir);\n if (!fs.existsSync(apiDir) || !fs.statSync(apiDir).isDirectory()) {\n throw new Error(`[EFC] createTestApp apiDir is not a directory: ${apiDir}`);\n }\n configureLogger(false);\n if (options.auth) {\n configureAuth({\n secret: options.auth.secret,\n strategy: options.auth.strategy ?? 'http-only',\n expiresIn: options.auth.expiresIn ?? '1h',\n ...(options.auth.cookieDomain !== undefined && { cookieDomain: options.auth.cookieDomain }),\n });\n }\n const app = createHttpApp({\n cors: false,\n ...(options.globalMiddlewares !== undefined && {\n globalMiddlewares: options.globalMiddlewares,\n }),\n ...(options.requestTimeout !== undefined && { requestTimeout: options.requestTimeout }),\n ...(options.trustProxy !== undefined && { trustProxy: options.trustProxy }),\n });\n const router = express.Router();\n await mountRoutes(router, scanDir(apiDir));\n app.use(options.basePath ?? '/v1/api', router);\n mountErrorHandler(app, options.onError);\n return app;\n}\n"]}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import express from 'express';
|
|
2
|
+
import { E as EFCConfig, A as AuthStrategy } from './types-CPMFTVXm.cjs';
|
|
3
|
+
|
|
4
|
+
interface TestAppOptions {
|
|
5
|
+
/** Explicit fixtures/app API directory. Does not change cwd or ignite() conventions. */
|
|
6
|
+
apiDir: string;
|
|
7
|
+
basePath?: string;
|
|
8
|
+
globalMiddlewares?: express.RequestHandler[];
|
|
9
|
+
requestTimeout?: number;
|
|
10
|
+
trustProxy?: EFCConfig['trustProxy'];
|
|
11
|
+
onError?: express.ErrorRequestHandler;
|
|
12
|
+
/** Auth is process-wide, as in ignite(); use one configuration per test process. */
|
|
13
|
+
auth?: {
|
|
14
|
+
secret: string;
|
|
15
|
+
strategy?: AuthStrategy;
|
|
16
|
+
expiresIn?: string;
|
|
17
|
+
cookieDomain?: string;
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Mounts real file-based routes on an Express app for supertest (or another HTTP
|
|
22
|
+
* harness). Does not listen, fork workers, start services, or install signal handlers.
|
|
23
|
+
* Models and task queues need separately configured integration fixtures.
|
|
24
|
+
*/
|
|
25
|
+
declare function createTestApp(options: TestAppOptions): Promise<express.Express>;
|
|
26
|
+
|
|
27
|
+
export { type TestAppOptions, createTestApp };
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import express from 'express';
|
|
2
|
+
import { E as EFCConfig, A as AuthStrategy } from './types-CPMFTVXm.js';
|
|
3
|
+
|
|
4
|
+
interface TestAppOptions {
|
|
5
|
+
/** Explicit fixtures/app API directory. Does not change cwd or ignite() conventions. */
|
|
6
|
+
apiDir: string;
|
|
7
|
+
basePath?: string;
|
|
8
|
+
globalMiddlewares?: express.RequestHandler[];
|
|
9
|
+
requestTimeout?: number;
|
|
10
|
+
trustProxy?: EFCConfig['trustProxy'];
|
|
11
|
+
onError?: express.ErrorRequestHandler;
|
|
12
|
+
/** Auth is process-wide, as in ignite(); use one configuration per test process. */
|
|
13
|
+
auth?: {
|
|
14
|
+
secret: string;
|
|
15
|
+
strategy?: AuthStrategy;
|
|
16
|
+
expiresIn?: string;
|
|
17
|
+
cookieDomain?: string;
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Mounts real file-based routes on an Express app for supertest (or another HTTP
|
|
22
|
+
* harness). Does not listen, fork workers, start services, or install signal handlers.
|
|
23
|
+
* Models and task queues need separately configured integration fixtures.
|
|
24
|
+
*/
|
|
25
|
+
declare function createTestApp(options: TestAppOptions): Promise<express.Express>;
|
|
26
|
+
|
|
27
|
+
export { type TestAppOptions, createTestApp };
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createHttpApp,
|
|
3
|
+
mountErrorHandler,
|
|
4
|
+
mountRoutes
|
|
5
|
+
} from "./chunk-KLWL7XSC.js";
|
|
6
|
+
import {
|
|
7
|
+
configureAuth
|
|
8
|
+
} from "./chunk-Y75V5FCU.js";
|
|
9
|
+
import {
|
|
10
|
+
scanDir
|
|
11
|
+
} from "./chunk-5LPRKZPB.js";
|
|
12
|
+
import "./chunk-C2FOZ7ME.js";
|
|
13
|
+
import "./chunk-XPY5TQDK.js";
|
|
14
|
+
import "./chunk-3SWI46YK.js";
|
|
15
|
+
import "./chunk-B6MB6HEG.js";
|
|
16
|
+
import {
|
|
17
|
+
configureLogger
|
|
18
|
+
} from "./chunk-V73R76I4.js";
|
|
19
|
+
|
|
20
|
+
// src/testing.ts
|
|
21
|
+
import path from "path";
|
|
22
|
+
import fs from "fs";
|
|
23
|
+
import express from "express";
|
|
24
|
+
async function createTestApp(options) {
|
|
25
|
+
if (typeof options.apiDir !== "string" || !options.apiDir.trim()) {
|
|
26
|
+
throw new Error("[EFC] createTestApp requires a nonempty apiDir");
|
|
27
|
+
}
|
|
28
|
+
const apiDir = path.resolve(options.apiDir);
|
|
29
|
+
if (!fs.existsSync(apiDir) || !fs.statSync(apiDir).isDirectory()) {
|
|
30
|
+
throw new Error(`[EFC] createTestApp apiDir is not a directory: ${apiDir}`);
|
|
31
|
+
}
|
|
32
|
+
configureLogger(false);
|
|
33
|
+
if (options.auth) {
|
|
34
|
+
configureAuth({
|
|
35
|
+
secret: options.auth.secret,
|
|
36
|
+
strategy: options.auth.strategy ?? "http-only",
|
|
37
|
+
expiresIn: options.auth.expiresIn ?? "1h",
|
|
38
|
+
...options.auth.cookieDomain !== void 0 && { cookieDomain: options.auth.cookieDomain }
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
const app = createHttpApp({
|
|
42
|
+
cors: false,
|
|
43
|
+
...options.globalMiddlewares !== void 0 && {
|
|
44
|
+
globalMiddlewares: options.globalMiddlewares
|
|
45
|
+
},
|
|
46
|
+
...options.requestTimeout !== void 0 && { requestTimeout: options.requestTimeout },
|
|
47
|
+
...options.trustProxy !== void 0 && { trustProxy: options.trustProxy }
|
|
48
|
+
});
|
|
49
|
+
const router = express.Router();
|
|
50
|
+
await mountRoutes(router, scanDir(apiDir));
|
|
51
|
+
app.use(options.basePath ?? "/v1/api", router);
|
|
52
|
+
mountErrorHandler(app, options.onError);
|
|
53
|
+
return app;
|
|
54
|
+
}
|
|
55
|
+
export {
|
|
56
|
+
createTestApp
|
|
57
|
+
};
|
|
58
|
+
//# sourceMappingURL=testing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/testing.ts"],"sourcesContent":["import path from 'node:path';\nimport fs from 'node:fs';\nimport express from 'express';\nimport type { AuthStrategy, EFCConfig } from './types.js';\nimport { configureAuth } from './auth/index.js';\nimport { configureLogger } from './logger.js';\nimport { createHttpApp, mountErrorHandler } from './http-app.js';\nimport { scanDir } from './router/scan.js';\nimport { mountRoutes } from './router/mount.js';\n\nexport interface TestAppOptions {\n /** Explicit fixtures/app API directory. Does not change cwd or ignite() conventions. */\n apiDir: string;\n basePath?: string;\n globalMiddlewares?: express.RequestHandler[];\n requestTimeout?: number;\n trustProxy?: EFCConfig['trustProxy'];\n onError?: express.ErrorRequestHandler;\n /** Auth is process-wide, as in ignite(); use one configuration per test process. */\n auth?: {\n secret: string;\n strategy?: AuthStrategy;\n expiresIn?: string;\n cookieDomain?: string;\n };\n}\n\n/**\n * Mounts real file-based routes on an Express app for supertest (or another HTTP\n * harness). Does not listen, fork workers, start services, or install signal handlers.\n * Models and task queues need separately configured integration fixtures.\n */\nexport async function createTestApp(options: TestAppOptions): Promise<express.Express> {\n if (typeof options.apiDir !== 'string' || !options.apiDir.trim()) {\n throw new Error('[EFC] createTestApp requires a nonempty apiDir');\n }\n const apiDir = path.resolve(options.apiDir);\n if (!fs.existsSync(apiDir) || !fs.statSync(apiDir).isDirectory()) {\n throw new Error(`[EFC] createTestApp apiDir is not a directory: ${apiDir}`);\n }\n configureLogger(false);\n if (options.auth) {\n configureAuth({\n secret: options.auth.secret,\n strategy: options.auth.strategy ?? 'http-only',\n expiresIn: options.auth.expiresIn ?? '1h',\n ...(options.auth.cookieDomain !== undefined && { cookieDomain: options.auth.cookieDomain }),\n });\n }\n const app = createHttpApp({\n cors: false,\n ...(options.globalMiddlewares !== undefined && {\n globalMiddlewares: options.globalMiddlewares,\n }),\n ...(options.requestTimeout !== undefined && { requestTimeout: options.requestTimeout }),\n ...(options.trustProxy !== undefined && { trustProxy: options.trustProxy }),\n });\n const router = express.Router();\n await mountRoutes(router, scanDir(apiDir));\n app.use(options.basePath ?? '/v1/api', router);\n mountErrorHandler(app, options.onError);\n return app;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,OAAO,aAAa;AA8BpB,eAAsB,cAAc,SAAmD;AACrF,MAAI,OAAO,QAAQ,WAAW,YAAY,CAAC,QAAQ,OAAO,KAAK,GAAG;AAChE,UAAM,IAAI,MAAM,gDAAgD;AAAA,EAClE;AACA,QAAM,SAAS,KAAK,QAAQ,QAAQ,MAAM;AAC1C,MAAI,CAAC,GAAG,WAAW,MAAM,KAAK,CAAC,GAAG,SAAS,MAAM,EAAE,YAAY,GAAG;AAChE,UAAM,IAAI,MAAM,kDAAkD,MAAM,EAAE;AAAA,EAC5E;AACA,kBAAgB,KAAK;AACrB,MAAI,QAAQ,MAAM;AAChB,kBAAc;AAAA,MACZ,QAAQ,QAAQ,KAAK;AAAA,MACrB,UAAU,QAAQ,KAAK,YAAY;AAAA,MACnC,WAAW,QAAQ,KAAK,aAAa;AAAA,MACrC,GAAI,QAAQ,KAAK,iBAAiB,UAAa,EAAE,cAAc,QAAQ,KAAK,aAAa;AAAA,IAC3F,CAAC;AAAA,EACH;AACA,QAAM,MAAM,cAAc;AAAA,IACxB,MAAM;AAAA,IACN,GAAI,QAAQ,sBAAsB,UAAa;AAAA,MAC7C,mBAAmB,QAAQ;AAAA,IAC7B;AAAA,IACA,GAAI,QAAQ,mBAAmB,UAAa,EAAE,gBAAgB,QAAQ,eAAe;AAAA,IACrF,GAAI,QAAQ,eAAe,UAAa,EAAE,YAAY,QAAQ,WAAW;AAAA,EAC3E,CAAC;AACD,QAAM,SAAS,QAAQ,OAAO;AAC9B,QAAM,YAAY,QAAQ,QAAQ,MAAM,CAAC;AACzC,MAAI,IAAI,QAAQ,YAAY,WAAW,MAAM;AAC7C,oBAAkB,KAAK,QAAQ,OAAO;AACtC,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
|
+
|
|
3
|
+
var _chunkRPL2IFWKcjs = require('./chunk-RPL2IFWK.cjs');
|
|
4
|
+
require('./chunk-H2PVWCWC.cjs');
|
|
5
|
+
require('./chunk-CGY7JU4Y.cjs');
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
exports.runInThread = _chunkRPL2IFWKcjs.runInThread;
|
|
9
|
+
//# sourceMappingURL=thread-runner.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/thread-runner.cjs"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACF,oDAAC","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/thread-runner.cjs"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -67,6 +67,10 @@ interface LoggingConfig {
|
|
|
67
67
|
queries?: boolean | QueryLogConfig;
|
|
68
68
|
}
|
|
69
69
|
interface QueryLogConfig {
|
|
70
|
+
/** Opt-in per-process query counters/latencies; default off, at most 1000 model/op entries. */
|
|
71
|
+
metrics?: boolean | {
|
|
72
|
+
maxEntries?: number;
|
|
73
|
+
};
|
|
70
74
|
/** Log every operation (info), not just slow ones. Default: false (true with `queries: true`). */
|
|
71
75
|
all?: boolean;
|
|
72
76
|
/** Operations taking at least this long are logged as warnings. Default: 500. */
|
|
@@ -86,6 +90,10 @@ interface CorsConfig {
|
|
|
86
90
|
}
|
|
87
91
|
/** Connection pool settings, per worker process (`databasePool` in `ignite()`). */
|
|
88
92
|
interface DatabasePoolConfig {
|
|
93
|
+
/** PostgreSQL model statements: default true (100 names per connection); false or { max: 0 } for incompatible poolers. */
|
|
94
|
+
preparedStatements?: boolean | {
|
|
95
|
+
max?: number;
|
|
96
|
+
};
|
|
89
97
|
/** Most open connections. Default: 10 (pg) / 100 (MongoDB). */
|
|
90
98
|
max?: number;
|
|
91
99
|
/** Close a connection idle this long, in ms. Default: 10000 (pg) / never (MongoDB). */
|
|
@@ -95,6 +103,12 @@ interface DatabasePoolConfig {
|
|
|
95
103
|
}
|
|
96
104
|
interface EFCConfig {
|
|
97
105
|
port?: number;
|
|
106
|
+
/**
|
|
107
|
+
* Express's `trust proxy`: set it when the app runs behind a proxy or load balancer
|
|
108
|
+
* (Render, Fly, Heroku, nginx, a cloud LB) so `req.ip` is the client, not the proxy —
|
|
109
|
+
* `true`, the number of hops, or addresses / subnets. `rateLimit` keys on `req.ip`.
|
|
110
|
+
*/
|
|
111
|
+
trustProxy?: boolean | number | string | string[];
|
|
98
112
|
basePath?: string;
|
|
99
113
|
dashboard?: boolean;
|
|
100
114
|
database?: DatabaseEngine;
|
|
@@ -637,4 +651,4 @@ interface MigrationContext {
|
|
|
637
651
|
engine: DatabaseEngine;
|
|
638
652
|
}
|
|
639
653
|
|
|
640
|
-
export type { AuthStrategy as A, ScalarKeys as B, CollectionSchema as C, DatabaseEngine as D, EFCConfig as E, FieldDefinition as F, GeoPoint as G, SchemaField as H, InferSchema as I, TableFieldDefinition as J, TableRelation as K, LoggingConfig as L, ModelSchema as M, TableSchemaField as N, Validator as O, QueryLogConfig as Q, RouteEntry as R, Simplify as S, TaskOptions as T, Update as U, ValidationIssue as V, TaskDefinition as a, InferCreateInput as b, ModelOptions as c, InferredModel as d, TableSchema as e, TableOptions as f, SortDirection as g,
|
|
654
|
+
export type { AuthStrategy as A, ScalarKeys as B, CollectionSchema as C, DatabaseEngine as D, EFCConfig as E, FieldDefinition as F, GeoPoint as G, SchemaField as H, InferSchema as I, TableFieldDefinition as J, TableRelation as K, LoggingConfig as L, ModelSchema as M, TableSchemaField as N, Validator as O, QueryLogConfig as Q, RouteEntry as R, Simplify as S, TaskOptions as T, Update as U, ValidationIssue as V, TaskDefinition as a, InferCreateInput as b, ModelOptions as c, InferredModel as d, TableSchema as e, TableOptions as f, SortDirection as g, InferRecord as h, CacheConfig as i, CollectionFieldDefinition as j, CorsConfig as k, DatabasePoolConfig as l, DefaultOperator as m, Filter as n, FilterOperators as o, FindOptions as p, IndexDefinition as q, InferCreate as r, MigrationContext as s, ModelCRUD as t, ModelQueryOptions as u, ModelRecord as v, RequestSchema as w, RouteMeta as x, RouteMethodMeta as y, RouteSchema as z };
|
|
@@ -67,6 +67,10 @@ interface LoggingConfig {
|
|
|
67
67
|
queries?: boolean | QueryLogConfig;
|
|
68
68
|
}
|
|
69
69
|
interface QueryLogConfig {
|
|
70
|
+
/** Opt-in per-process query counters/latencies; default off, at most 1000 model/op entries. */
|
|
71
|
+
metrics?: boolean | {
|
|
72
|
+
maxEntries?: number;
|
|
73
|
+
};
|
|
70
74
|
/** Log every operation (info), not just slow ones. Default: false (true with `queries: true`). */
|
|
71
75
|
all?: boolean;
|
|
72
76
|
/** Operations taking at least this long are logged as warnings. Default: 500. */
|
|
@@ -86,6 +90,10 @@ interface CorsConfig {
|
|
|
86
90
|
}
|
|
87
91
|
/** Connection pool settings, per worker process (`databasePool` in `ignite()`). */
|
|
88
92
|
interface DatabasePoolConfig {
|
|
93
|
+
/** PostgreSQL model statements: default true (100 names per connection); false or { max: 0 } for incompatible poolers. */
|
|
94
|
+
preparedStatements?: boolean | {
|
|
95
|
+
max?: number;
|
|
96
|
+
};
|
|
89
97
|
/** Most open connections. Default: 10 (pg) / 100 (MongoDB). */
|
|
90
98
|
max?: number;
|
|
91
99
|
/** Close a connection idle this long, in ms. Default: 10000 (pg) / never (MongoDB). */
|
|
@@ -95,6 +103,12 @@ interface DatabasePoolConfig {
|
|
|
95
103
|
}
|
|
96
104
|
interface EFCConfig {
|
|
97
105
|
port?: number;
|
|
106
|
+
/**
|
|
107
|
+
* Express's `trust proxy`: set it when the app runs behind a proxy or load balancer
|
|
108
|
+
* (Render, Fly, Heroku, nginx, a cloud LB) so `req.ip` is the client, not the proxy —
|
|
109
|
+
* `true`, the number of hops, or addresses / subnets. `rateLimit` keys on `req.ip`.
|
|
110
|
+
*/
|
|
111
|
+
trustProxy?: boolean | number | string | string[];
|
|
98
112
|
basePath?: string;
|
|
99
113
|
dashboard?: boolean;
|
|
100
114
|
database?: DatabaseEngine;
|
|
@@ -637,4 +651,4 @@ interface MigrationContext {
|
|
|
637
651
|
engine: DatabaseEngine;
|
|
638
652
|
}
|
|
639
653
|
|
|
640
|
-
export type { AuthStrategy as A, ScalarKeys as B, CollectionSchema as C, DatabaseEngine as D, EFCConfig as E, FieldDefinition as F, GeoPoint as G, SchemaField as H, InferSchema as I, TableFieldDefinition as J, TableRelation as K, LoggingConfig as L, ModelSchema as M, TableSchemaField as N, Validator as O, QueryLogConfig as Q, RouteEntry as R, Simplify as S, TaskOptions as T, Update as U, ValidationIssue as V, TaskDefinition as a, InferCreateInput as b, ModelOptions as c, InferredModel as d, TableSchema as e, TableOptions as f, SortDirection as g,
|
|
654
|
+
export type { AuthStrategy as A, ScalarKeys as B, CollectionSchema as C, DatabaseEngine as D, EFCConfig as E, FieldDefinition as F, GeoPoint as G, SchemaField as H, InferSchema as I, TableFieldDefinition as J, TableRelation as K, LoggingConfig as L, ModelSchema as M, TableSchemaField as N, Validator as O, QueryLogConfig as Q, RouteEntry as R, Simplify as S, TaskOptions as T, Update as U, ValidationIssue as V, TaskDefinition as a, InferCreateInput as b, ModelOptions as c, InferredModel as d, TableSchema as e, TableOptions as f, SortDirection as g, InferRecord as h, CacheConfig as i, CollectionFieldDefinition as j, CorsConfig as k, DatabasePoolConfig as l, DefaultOperator as m, Filter as n, FilterOperators as o, FindOptions as p, IndexDefinition as q, InferCreate as r, MigrationContext as s, ModelCRUD as t, ModelQueryOptions as u, ModelRecord as v, RequestSchema as w, RouteMeta as x, RouteMethodMeta as y, RouteSchema as z };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-file-cluster",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.2",
|
|
4
4
|
"description": "Enterprise-grade, zero-boilerplate backend framework with file-based routing and multi-core clustering",
|
|
5
5
|
"homepage": "https://efc.prashantadhikari7.com.np/",
|
|
6
6
|
"repository": {
|
|
@@ -33,6 +33,11 @@
|
|
|
33
33
|
"import": "./dist/auth/index.js",
|
|
34
34
|
"require": "./dist/auth/index.cjs"
|
|
35
35
|
},
|
|
36
|
+
"./testing": {
|
|
37
|
+
"types": "./dist/testing.d.ts",
|
|
38
|
+
"import": "./dist/testing.js",
|
|
39
|
+
"require": "./dist/testing-cjs.cjs"
|
|
40
|
+
},
|
|
36
41
|
"./tasks": {
|
|
37
42
|
"types": "./dist/tasks/index.d.ts",
|
|
38
43
|
"import": "./dist/tasks/index.js",
|