Improve API token format and enhance auth status command

- Change token format to reviq_<base58> prefix instead of raw hex
- Add me.authStatus API endpoint for detailed auth information
- Enhance CLI `reviq auth status` to show token details from API
- Add comprehensive tests for token generation (18 tests)
- Extract bootstrap logic to @reviq/db for reusability and testing
- Remove default db export; callers must use createDb() directly

Token changes:
- New format: reviq_<base58-encoded-32-bytes>
- Added parseToken() for validation
- Added isValidTokenFormat() helper

Auth status endpoint returns:
- User profile information
- Auth method (api_token or session)
- Token/session details (name, expiration, last used)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
RevIQ
2026-01-09 17:59:02 +08:00
parent df9b8808d0
commit 6b9b04d1d0
20 changed files with 764 additions and 125 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 "./password.js";
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 = 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,
};
};