Skip to content

Commit

Permalink
Merge branch 'main' into include-src-blitz-console
Browse files Browse the repository at this point in the history
  • Loading branch information
Dillon Raphael authored Nov 4, 2022
2 parents a052a64 + 55a43ce commit e7d26f7
Show file tree
Hide file tree
Showing 16 changed files with 96 additions and 50 deletions.
6 changes: 6 additions & 0 deletions .changeset/afraid-ears-repair.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"blitz": patch
"@blitzjs/generator": patch
---

Upgrade `tslog` to the latest version
6 changes: 6 additions & 0 deletions .changeset/heavy-students-buy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@blitzjs/auth": minor
"@blitzjs/rpc": minor
---

maybe fix anon session CSRF issue + add ability to customize anon session expiry time
6 changes: 6 additions & 0 deletions .changeset/light-squids-draw.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"blitz": patch
"@blitzjs/generator": patch
---

Fix `cannot find module db error` in JavaScript template. Replace requiring the config using `esbuild` with parsing using `jscodeshift` to get the `cliConfig` values. Added logic to find the `blitz-server` file in `src` directory
5 changes: 5 additions & 0 deletions .changeset/odd-bears-run.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@blitzjs/next": minor
---

Change setupBlitzServer logger config to be optional. Will default to BlitzLogger
9 changes: 8 additions & 1 deletion packages/blitz-auth/src/client/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,17 @@ export const getPublicDataStore = (): PublicDataStore => {
return (window as any).__publicDataStore
}

export const getAntiCSRFToken = () => {
// because safari automatically deletes non-httponly cookies after 7 days
export const backupAntiCSRFTokenToLocalStorage = () => {
const cookieValue = readCookie(COOKIE_CSRF_TOKEN())
if (cookieValue) {
localStorage.setItem(LOCALSTORAGE_CSRF_TOKEN(), cookieValue)
}
}

export const getAntiCSRFToken = () => {
const cookieValue = readCookie(COOKIE_CSRF_TOKEN())
if (cookieValue) {
return cookieValue
} else {
return localStorage.getItem(LOCALSTORAGE_CSRF_TOKEN())
Expand Down
5 changes: 3 additions & 2 deletions packages/blitz-auth/src/global.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import {SessionConfig} from "./shared/types"
import {AuthPluginOptions} from "./server"
import {SessionConfigMethods} from "./shared"

declare global {
var sessionConfig: SessionConfig
var sessionConfig: AuthPluginOptions & SessionConfigMethods
var __BLITZ_SESSION_COOKIE_PREFIX: string | undefined
var __BLITZ_SUSPENSE_ENABLED: boolean
}
4 changes: 3 additions & 1 deletion packages/blitz-auth/src/server/auth-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {getSession} from "./auth-sessions"
interface SessionConfigOptions {
cookiePrefix?: string
sessionExpiryMinutes?: number
anonSessionExpiryMinutes?: number
method?: "essential" | "advanced"
sameSite?: "none" | "lax" | "strict"
secureCookies?: boolean
Expand Down Expand Up @@ -69,13 +70,14 @@ export const PrismaStorage = <Client extends PrismaClientWithSession>(

const defaultConfig_: SessionConfigOptions = {
sessionExpiryMinutes: 30 * 24 * 60, // Sessions expire after 30 days of being idle
anonSessionExpiryMinutes: 5 * 365 * 24 * 60, // Sessions expire after 5 years of being idle
method: "essential",
sameSite: "lax",
publicDataKeysToSyncAcrossSessions: ["role", "roles"],
secureCookies: !process.env.DISABLE_SECURE_COOKIES && process.env.NODE_ENV === "production",
}

interface AuthPluginOptions extends Partial<SessionConfigOptions>, IsAuthorized {
export interface AuthPluginOptions extends Partial<SessionConfigOptions>, IsAuthorized {
storage: SessionConfigMethods
}

Expand Down
5 changes: 4 additions & 1 deletion packages/blitz-auth/src/server/auth-sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -690,7 +690,10 @@ async function createNewSession(
const anonymousSessionToken = createAnonymousSessionToken(payload)
const publicDataToken = createPublicDataToken(args.publicData)

const expiresAt = addYears(new Date(), 30)
const expiresAt = addMinutes(
new Date(),
global.sessionConfig.anonSessionExpiryMinutes as number,
)
setAnonymousSessionCookie(req, res, anonymousSessionToken, expiresAt)
setCSRFCookie(req, res, antiCSRFToken, expiresAt)
setPublicDataCookie(req, res, publicDataToken, expiresAt)
Expand Down
11 changes: 0 additions & 11 deletions packages/blitz-auth/src/shared/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,17 +50,6 @@ export interface SessionConfigMethods {
deleteSession: (handle: string) => Promise<SessionModel | undefined>
}

export interface SessionConfig extends SessionConfigMethods {
cookiePrefix?: string
sessionExpiryMinutes?: number
method?: "essential" | "advanced"
sameSite?: "none" | "lax" | "strict"
secureCookies?: boolean
domain?: string
publicDataKeysToSyncAcrossSessions?: string[]
isAuthorized: (data: {ctx: BlitzCtx; args: any}) => boolean
}

export interface SessionContextBase {
$handle: string | null
$publicData: unknown
Expand Down
4 changes: 2 additions & 2 deletions packages/blitz-next/src/index-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export type NextApiHandler<TResult> = (
type SetupBlitzOptions = {
plugins: BlitzServerPlugin<RequestMiddleware, Ctx>[]
onError?: (err: Error) => void
logger: ReturnType<typeof BlitzLogger>
logger?: ReturnType<typeof BlitzLogger>
}

export type Redirect =
Expand Down Expand Up @@ -131,7 +131,7 @@ const prefetchQueryFactory = (
}

export const setupBlitzServer = ({plugins, onError, logger}: SetupBlitzOptions) => {
initializeLogger(logger)
initializeLogger(logger ?? BlitzLogger())

const middlewares = plugins.flatMap((p) => p.requestMiddlewares)
const contextMiddleware = plugins.flatMap((p) => p.contextMiddleware).filter(Boolean)
Expand Down
2 changes: 2 additions & 0 deletions packages/blitz-rpc/src/data-client/rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {stringify} from "superjson"
import {
getAntiCSRFToken,
getPublicDataStore,
backupAntiCSRFTokenToLocalStorage,
HEADER_CSRF,
HEADER_CSRF_ERROR,
HEADER_PUBLIC_DATA_TOKEN,
Expand Down Expand Up @@ -121,6 +122,7 @@ export function __internal_buildRpcClient({
.then(async (response) => {
debug("Received request for", routePath)
if (response.headers) {
backupAntiCSRFTokenToLocalStorage()
if (response.headers.get(HEADER_PUBLIC_DATA_TOKEN)) {
getPublicDataStore().updateState()
debug("Public data updated")
Expand Down
2 changes: 1 addition & 1 deletion packages/blitz/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
"tar": "6.1.11",
"ts-node": "10.7.0",
"tsconfig-paths": "4.0.0",
"tslog": "3.3.1",
"tslog": "3.3.4",
"watchpack": "2.1.1"
},
"devDependencies": {
Expand Down
16 changes: 4 additions & 12 deletions packages/blitz/src/cli/commands/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
MutationsGenerator,
ModelGenerator,
QueryGenerator,
addCustomTemplatesBlitzConfig,
customTemplatesBlitzConfig,
} from "@blitzjs/generator"
import {log} from "../../logging"

Expand Down Expand Up @@ -65,7 +65,7 @@ const createCustomTemplates = async () => {
})
const templatesPathValue: string = templatesPath.value
const isTypeScript = await getIsTypeScript()
addCustomTemplatesBlitzConfig(templatesPathValue, isTypeScript)
await customTemplatesBlitzConfig(isTypeScript, templatesPathValue, true) // to run the codemod
log.success(`🚀 Custom templates path added/updated in app/blitz-server file`)
const customTemplatesPath = require("path").join(process.cwd(), templatesPathValue)
const fsExtra = await import("fs-extra")
Expand Down Expand Up @@ -275,20 +275,12 @@ const generate: CliCommand = async () => {
const generators = generatorMap[selectedType as keyof typeof generatorMap]

const isTypeScript = await getIsTypeScript()
const blitzServerPath = isTypeScript ? "app/blitz-server.ts" : "app/blitz-server.js"
const blitzServer = require("path").join(process.cwd(), blitzServerPath)
const {register} = require("esbuild-register/dist/node")
const {unregister} = register({
target: "es6",
})
const blitzConfig = require(blitzServer)
const {cliConfig} = blitzConfig
unregister()
const cliConfig = await customTemplatesBlitzConfig(isTypeScript)

for (const GeneratorClass of generators) {
const generator = new GeneratorClass({
destinationRoot: require("path").resolve(),
templateDir: cliConfig?.customTemplates,
templateDir: cliConfig,
extraArgs: args["_"].slice(3) as string[],
modelName: singularRootContext,
modelNames: modelNames(singularRootContext),
Expand Down
3 changes: 2 additions & 1 deletion packages/generator/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"diff": "5.0.0",
"enquirer": "2.3.6",
"fs-extra": "10.0.1",
"globby": "13.1.2",
"got": "^11.8.1",
"jscodeshift": "0.13.0",
"mem-fs": "1.2.0",
Expand All @@ -41,7 +42,7 @@
"prettier": "^2.5.1",
"recast": "0.20.5",
"supports-color": "8.1.1",
"tslog": "3.3.1",
"tslog": "3.3.4",
"username": "5.1.0",
"vinyl": "2.2.1"
},
Expand Down
36 changes: 30 additions & 6 deletions packages/generator/src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,31 @@ import {readdirRecursive} from "./utils/readdir-recursive"
import prettier from "prettier"
const debug = require("debug")("blitz:generator")

export const addCustomTemplatesBlitzConfig = (
customTemplatesPath: string,
export function getProjectRootSync() {
return path.dirname(getConfigSrcPath())
}

export function getConfigSrcPath() {
const jsPath = path.resolve(path.join(process.cwd(), "next.config.js"))
return jsPath
}

export const customTemplatesBlitzConfig = async (
isTypeScript: boolean,
customTemplatesPath = "",
codemod = false,
) => {
const blitzServer = isTypeScript ? "app/blitz-server.ts" : "app/blitz-server.js"
const blitzServerPath = require("path").join(process.cwd(), blitzServer)
const {globby} = await import("globby")
const blitzServer = await globby(["{app,src}/**/blitz-server.{ts,js}"], {
cwd: getProjectRootSync(),
})
if (blitzServer.length === 0) {
throw new Error("Could not find blitz-server.js or blitz-server.ts in app or src folder")
}
if (blitzServer.length > 1) {
throw new Error("Found more than one blitz-server.js or blitz-server.ts in app or src folder")
}
const blitzServerPath = require("path").join(process.cwd(), blitzServer.at(0))
const userConfigModuleSource = fs.readFileSync(blitzServerPath, {encoding: "utf-8"})
const userConfigModule = j(userConfigModuleSource, {parser: customTsParser})
const program = userConfigModule.get()
Expand Down Expand Up @@ -86,6 +105,9 @@ export const addCustomTemplatesBlitzConfig = (
if (customTemplatesProperty.type === "ObjectProperty") {
const customValue = customTemplatesProperty.value
if (customValue.type === "StringLiteral") {
if (!codemod) {
return customValue.value
}
customValue.value = customTemplatesPath
}
}
Expand All @@ -94,8 +116,10 @@ export const addCustomTemplatesBlitzConfig = (
}
}
}
const newSource = userConfigModule.toSource()
fs.writeFileSync(blitzServerPath, newSource)
if (codemod) {
const newSource = userConfigModule.toSource()
fs.writeFileSync(blitzServerPath, newSource)
}
}

export const customTsParser = {
Expand Down
26 changes: 14 additions & 12 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit e7d26f7

Please sign in to comment.