Skip to content

Single User Auth #202

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 16 commits into from
Aug 9, 2025
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions codecov.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
ignore:
- "*.config.js"
- "*.config.ts"
- "/packages/cli/scripts/generate-secrets.mjs"

# Coverage checks shouldn't fail the build
coverage:
Expand Down
5 changes: 4 additions & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,15 @@
"lint": "eslint .",
"test": "vitest run",
"test-ci": "vitest run --coverage",
"test:watch": "vitest"
"test:watch": "vitest",
"generate-secrets": "node scripts/generate-secrets.mjs"
},
"dependencies": {
"@clack/prompts": "^0.10.0",
"@counterscale/server": "3.1.0",
"@types/bcryptjs": "^3.0.0",
"@types/node": "^22.10.2",
"bcryptjs": "^3.0.2",
"chalk": "^5.3.0",
"cli-highlight": "^2.1.11",
"figlet": "^1.7.0",
Expand Down
40 changes: 40 additions & 0 deletions packages/cli/scripts/generate-secrets.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#!/usr/bin/env node

import { intro, note, outro, isCancel, cancel } from "@clack/prompts";
import { generateCryptoSecret, generatePasswordHash } from "../dist/auth.js";
import { promptAppPassword } from "../dist/install.js";

async function main() {
intro('🔐 Counterscale Development Secret Generator');

const jwtSecret = generateCryptoSecret();
;

const userPassword = await promptAppPassword();

if (isCancel(userPassword)) {
cancel('Operation cancelled');
process.exit(0);
}

try {
const passwordHash = await generatePasswordHash(userPassword, jwtSecret);

const output = [
'Copy these values to your .dev.vars file:',
'',
`CF_CRYPTO_SECRET='${jwtSecret}'`,
`CF_PASSWORD_HASH='${passwordHash}'`
].join('\n');

note(output, 'Generated Secrets');
outro('✅ Secrets generated successfully!');

} catch (error) {
cancel(`Error generating password hash: ${error.message}`);
process.exit(1);
}
}

main().catch(console.error);

119 changes: 114 additions & 5 deletions packages/cli/src/__tests__/install.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
promptDeploy,
promptProjectConfig,
promptAccountSelection,
promptAppPassword,
type AccountInfo,
} from "../install.js";

Expand Down Expand Up @@ -232,7 +233,7 @@ describe("install prompts", () => {
{ id: "abcdef1234567890abcdef1234567890", name: "Account 2" },
];
const selectedAccountId = "abcdef1234567890abcdef1234567890";

const mockPrompts = await import("@clack/prompts");
(isCancel as unknown as ReturnType<typeof vi.fn>).mockReturnValue(
false,
Expand All @@ -250,7 +251,7 @@ describe("install prompts", () => {
{ id: "1234567890abcdef1234567890abcdef", name: "Account 1" },
{ id: "abcdef1234567890abcdef1234567890", name: "Account 2" },
];

(isCancel as unknown as ReturnType<typeof vi.fn>).mockReturnValue(
true,
);
Expand All @@ -269,7 +270,7 @@ describe("install prompts", () => {
{ id: "1234567890abcdef1234567890abcdef", name: "Account 1" },
{ id: "abcdef1234567890abcdef1234567890", name: "Account 2" },
];

const mockPrompts = await import("@clack/prompts");
(isCancel as unknown as ReturnType<typeof vi.fn>).mockReturnValue(
false,
Expand Down Expand Up @@ -299,7 +300,7 @@ describe("install prompts", () => {
const mockAccounts: AccountInfo[] = [
{ id: "1234567890abcdef1234567890abcdef", name: "Account 1" },
];

const mockPrompts = await import("@clack/prompts");
(isCancel as unknown as ReturnType<typeof vi.fn>).mockReturnValue(
false,
Expand All @@ -310,7 +311,7 @@ describe("install prompts", () => {

const result = await promptAccountSelection(mockAccounts);
expect(result).toBe("1234567890abcdef1234567890abcdef");

expect(mockPrompts.select).toHaveBeenCalledWith({
message: "Select a Cloudflare account:",
options: [
Expand Down Expand Up @@ -372,4 +373,112 @@ describe("install prompts", () => {
expect(shouldPrompt).toBe(true);
});
});

describe("promptAppPassword", () => {
it("should return valid app password", async () => {
const mockPassword = "mySecurePassword123";
(isCancel as unknown as ReturnType<typeof vi.fn>).mockReturnValue(
false,
);
const mockPrompts = await import("@clack/prompts");
(
mockPrompts.password as unknown as ReturnType<typeof vi.fn>
).mockResolvedValue(mockPassword);

const result = await promptAppPassword();
expect(result).toBe(mockPassword);
});

it("should throw error if user cancels", async () => {
(isCancel as unknown as ReturnType<typeof vi.fn>).mockReturnValue(
true,
);
const mockPrompts = await import("@clack/prompts");
(
mockPrompts.password as unknown as ReturnType<typeof vi.fn>
).mockResolvedValue("password");

await expect(promptAppPassword()).rejects.toThrow(
"Operation canceled",
);
});

it("should throw error if password is not a string", async () => {
(isCancel as unknown as ReturnType<typeof vi.fn>).mockReturnValue(
false,
);
const mockPrompts = await import("@clack/prompts");
(
mockPrompts.password as unknown as ReturnType<typeof vi.fn>
).mockResolvedValue(undefined);

await expect(promptAppPassword()).rejects.toThrow(
"App password is required",
);
});

it("should validate password has at least 8 characters", async () => {
const mockPrompts = await import("@clack/prompts");
(
mockPrompts.password as unknown as ReturnType<typeof vi.fn>
).mockImplementationOnce(({ validate }: PasswordOptions) => {
if (!validate) {
throw new Error("validate function missing");
}

expect(validate("")).toBe(
"A password of 8 characters or longer is required",
);
expect(validate("short")).toBe(
"A password of 8 characters or longer is required",
);
expect(validate("password")).toBeUndefined(); // 8 chars, should pass
return "mock-password";
});

await promptAppPassword();
expect(mockPrompts.password).toHaveBeenCalled();
});

it("should call password prompt with correct options", async () => {
const mockPrompts = await import("@clack/prompts");
(isCancel as unknown as ReturnType<typeof vi.fn>).mockReturnValue(
false,
);
(
mockPrompts.password as unknown as ReturnType<typeof vi.fn>
).mockResolvedValue("test-password");

await promptAppPassword();

expect(mockPrompts.password).toHaveBeenCalledWith({
message:
"Enter the password you will use to access the Counterscale Dashboard",
mask: "*",
validate: expect.any(Function),
});
});

it("should accept passwords with 12 or more characters", async () => {
const testPasswords = [
"password1234", // exactly 12 chars
"a very long password with spaces and symbols!@#$%", // much longer
"123456789012", // exactly 12 chars
"verylongpassword", // longer than 12
];

for (const testPassword of testPasswords) {
(
isCancel as unknown as ReturnType<typeof vi.fn>
).mockReturnValue(false);
const mockPrompts = await import("@clack/prompts");
(
mockPrompts.password as unknown as ReturnType<typeof vi.fn>
).mockResolvedValue(testPassword);

const result = await promptAppPassword();
expect(result).toBe(testPassword);
}
});
});
});
17 changes: 17 additions & 0 deletions packages/cli/src/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import bcrypt from "bcryptjs";
import crypto from "node:crypto";

export async function generatePasswordHash(password:string, secret:string) {
// Create a consistent salt from the secret
const hash = crypto.createHash('sha256').update(secret).digest();
const saltBase64 = hash.subarray(0, 16).toString('base64').replace(/[+/=]/g, (c) =>
c === '+' ? '.' : c === '/' ? '/' : ''
).substring(0, 22);

const salt = `$2b$12$${saltBase64}`;
return await bcrypt.hash(password, salt);
}

export function generateCryptoSecret() {
return crypto.randomBytes(64).toString('hex');
}
63 changes: 61 additions & 2 deletions packages/cli/src/install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {

import { CloudflareClient } from "./cloudflare.js";
import { getScriptSnippet, getPackageSnippet, CLI_COLORS } from "./ui.js";
import { generateCryptoSecret, generatePasswordHash } from "./auth.js";

export function bail() {
cancel("Operation canceled.");
Expand Down Expand Up @@ -60,6 +61,30 @@ export async function promptApiToken(): Promise<string> {
return cfApiToken;
}

export const MIN_PASSWORD_LENGTH = 8;
export async function promptAppPassword(): Promise<string> {
const appPassword = await password({
message:
"Enter the password you will use to access the Counterscale Dashboard",
mask: "*",
validate: (val) => {
if (val.length < MIN_PASSWORD_LENGTH) {
return `A password of ${MIN_PASSWORD_LENGTH} characters or longer is required`;
}
},
});

if (isCancel(appPassword)) {
bail();
}

if (typeof appPassword !== "string") {
throw new Error("App password is required");
}

return appPassword;
}

export async function promptDeploy(
counterscaleVersion: string,
): Promise<boolean> {
Expand Down Expand Up @@ -260,7 +285,9 @@ export async function install(

if (Object.keys(secrets).length === 0) {
note(
`Create an API token from your Cloudflare Profile page: ${chalk.bold("https://dash.cloudflare.com/profile/api-tokens")}
`Create an API token from your Cloudflare Profile page: ${chalk.bold(
"https://dash.cloudflare.com/profile/api-tokens",
)}

Your token needs these permissions:

Expand All @@ -284,6 +311,36 @@ Your token needs these permissions:
throw new Error("Error setting Cloudflare API token");
}
}

const appPassword = await promptAppPassword();
if (appPassword) {
const s = spinner();
s.start(`Setting CounterScale Application Password ...`);
const cryptoSecret = generateCryptoSecret();
const passwordHash = await generatePasswordHash(
appPassword,
cryptoSecret,
);

if (
await cloudflare.setCloudflareSecrets({
CF_PASSWORD_HASH: passwordHash,
CF_CRYPTO_SECRET: cryptoSecret,
})
) {
s.stop(
"Setting CounterScale Application Password ... Done!",
);
} else {
s.stop(
"Error setting CounterScale Application Password",
1,
);
throw new Error(
"Error setting CounterScale Application Password",
);
}
}
} catch (err) {
console.error(err);
process.exit(1);
Expand Down Expand Up @@ -323,7 +380,9 @@ Your token needs these permissions:

await tick(() =>
outro(
`⚡️ Visit your dashboard: ${chalk.rgb(...CLI_COLORS.tan).underline(deployUrl)}`,
`⚡️ Visit your dashboard: ${chalk
.rgb(...CLI_COLORS.tan)
.underline(deployUrl)}`,
),
);

Expand Down
4 changes: 3 additions & 1 deletion packages/server/.dev.vars.example
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
# You also need to specify these as environment variables in
# your Cloudflare configuration
CF_BEARER_TOKEN=''
CF_ACCOUNT_ID=''
CF_ACCOUNT_ID=''
CF_PASSWORD_HASH=''
CF_CRYPTO_SECRET=''
Loading
Loading