Merge branch 'cli-improvements-1' with @reviq/utils password hashing

- Use executeBootstrap helper from @reviq/db for CLI bootstrap
- Update @reviq/db to use @reviq/utils for PBKDF2-SHA256 password hashing
  (Cloudflare Workers compatible)
- Keep @scure/base for base58 token encoding
- Remove redundant password.ts from @reviq/db (import directly from @reviq/utils)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
RevIQ
2026-01-09 18:17:45 +08:00
19 changed files with 785 additions and 154 deletions

View File

@@ -0,0 +1,168 @@
/**
* Core bootstrap logic for creating a superuser and initial organization
*
* This is extracted from the CLI bootstrap command to make it reusable
* and testable. It operates on a database transaction.
*/
import type { Database } from "@reviq/db-schema";
import type { Kysely, Transaction } from "kysely";
import { hashPassword } from "@reviq/utils";
import { generateToken, hashToken } from "./token.js";
/**
* Input for the bootstrap operation
*/
export interface BootstrapInput {
/** Email address for the superuser */
email: string;
/** Password for the superuser */
password: string;
/** Optional organization slug (defaults to "reviq") */
orgSlug?: string;
/** Optional organization display name (defaults to "RevIQ") */
orgDisplayName?: string;
/** Optional token name (defaults to "CLI bootstrap token") */
tokenName?: string;
/** Optional token expiration in days (defaults to 365) */
tokenExpirationDays?: number;
}
/**
* Result of the bootstrap operation
*/
export interface BootstrapResult {
/** The created user */
user: {
id: number;
email: string;
};
/** The created organization */
org: {
id: number;
slug: string;
};
/** The created API token (raw token, not hashed) */
token: string;
}
/**
* Execute the bootstrap operation within a transaction
*
* Creates:
* - A superuser with the given email and password
* - An organization with the superuser as owner
* - An API token for the superuser
*
* @param trx - Database transaction (use db.transaction() or pass a Transaction)
* @param input - Bootstrap configuration
* @returns The created user, org, and API token
* @throws Error if user already exists or validation fails
*/
export const executeBootstrap = async (
trx: Kysely<Database> | Transaction<Database>,
input: BootstrapInput,
): Promise<BootstrapResult> => {
const {
email,
password,
orgSlug = "reviq",
orgDisplayName = "RevIQ",
tokenName = "CLI bootstrap token",
tokenExpirationDays = 365,
} = input;
// Validate password length
if (password.length < 8) {
throw new Error("Password must be at least 8 characters");
}
// Validate email format (basic check)
if (!email.includes("@")) {
throw new Error("Invalid email address");
}
const normalizedEmail = email.toLowerCase();
// Check if user already exists
const existing = await trx
.selectFrom("users")
.where("email", "=", normalizedEmail)
.select("id")
.executeTakeFirst();
if (existing) {
throw new Error(`User with email ${email} already exists`);
}
// Hash the password
const passwordHash = await hashPassword(password);
// Create superuser
const [user] = await trx
.insertInto("users")
.values({
email: normalizedEmail,
password_hash: passwordHash,
is_superuser: true,
email_verified_at: new Date(),
})
.returning(["id", "email"])
.execute();
if (!user) {
throw new Error("Failed to create user");
}
// Create organization
const [org] = await trx
.insertInto("orgs")
.values({
slug: orgSlug,
display_name: orgDisplayName,
})
.returning(["id", "slug"])
.execute();
if (!org) {
throw new Error("Failed to create organization");
}
// Add user as owner of the org
await trx
.insertInto("org_members")
.values({
org_id: org.id,
user_id: user.id,
role: "owner",
})
.execute();
// Generate API token
const token = generateToken();
const tokenHashValue = hashToken(token);
await trx
.insertInto("api_tokens")
.values({
user_id: user.id,
token_hash: tokenHashValue,
name: tokenName,
expires_at: new Date(
Date.now() + tokenExpirationDays * 24 * 60 * 60 * 1000,
),
})
.execute();
return {
user: {
id: user.id,
email: user.email,
},
org: {
id: org.id,
slug: org.slug,
},
token,
};
};

View File

@@ -0,0 +1,51 @@
/**
* Token generation and hashing utilities
*/
import { sha256 } from "@noble/hashes/sha2.js";
import { randomBytes } from "@noble/hashes/utils.js";
import { base58 } from "@scure/base";
/**
* Token prefix for all RevIQ API tokens
*/
export const TOKEN_PREFIX = "reviq_";
/**
* Generate a cryptographically secure random token
* Format: reviq_<base58-encoded-32-bytes>
* Example: reviq_5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ
*/
export const generateToken = (): string => {
const bytes = randomBytes(32);
return TOKEN_PREFIX + base58.encode(bytes);
};
/**
* Validate that a token has the correct format
* Returns the raw bytes if valid, null if invalid
*/
export const parseToken = (token: string): Uint8Array | null => {
if (!token.startsWith(TOKEN_PREFIX)) {
return null;
}
const encoded = token.slice(TOKEN_PREFIX.length);
try {
const bytes = base58.decode(encoded);
// Expect 32 bytes of entropy
if (bytes.length !== 32) {
return null;
}
return bytes;
} catch {
return null;
}
};
/**
* Hash a token using SHA-256
* Returns a hex string
*/
export const hashToken = (token: string): string => {
return Buffer.from(sha256(Buffer.from(token))).toString("hex");
};