import { batch, first, run, stmt } from "../db";
import { randomId, randomToken, sha256Hex } from "../crypto";
import { PAT_PREFIX } from "../auth";
import { assertBelowCap, CAPS } from "../limits";
import type { TokenPermissions } from "../token-scope";
const VISIBLE_TOKEN_CHARS = 6;
/** OAuth-issued tokens are tracked separately so agents cannot crowd out a user's personal tokens. */
const OAUTH_TOKENS_PER_USER = 100;
export type GrantSpec = {
permissions: TokenPermissions;
allRepos: boolean;
repoIds: string[];
agent: string;
};
export type MintedToken = { id: string; token: string; expiresAt: number | null };
/**
* Issues an ordinary fine-grained personal access token (`access_tokens` + `access_token_repos`) and
* records the agent it belongs to, so OAuth grants inherit every existing permission check unchanged.
*/
export async function mintFineGrainedToken(input: {
userId: string;
name: string;
scopes: string;
grant: GrantSpec;
ttlMs: number | null;
clientId: string | null;
/** Set for tokens delegated by another token; they are revoked along with it. */
parentTokenId?: string;
/** Hard ceiling on the expiry, e.g. the delegating token's own expiry. */
notAfter?: number | null;
}): Promise<MintedToken> {
const oauth = input.scopes.startsWith("oauth:") || input.parentTokenId !== undefined;
const count = await first<{ count: number }>(
oauth
? "SELECT COUNT(*) AS count FROM access_tokens WHERE user_id = ? AND scopes LIKE 'oauth:%' AND (expires_at IS NULL OR expires_at > ?)"
: "SELECT COUNT(*) AS count FROM access_tokens WHERE user_id = ? AND (expires_at IS NULL OR expires_at > ?)",