refactor(device-pairing): share token update context

This commit is contained in:
Peter Steinberger
2026-02-16 02:19:45 +00:00
parent a7cbce1b3d
commit 60ad2c2e96

View File

@@ -428,17 +428,16 @@ export async function ensureDeviceToken(params: {
}): Promise<DeviceAuthToken | null> {
return await withLock(async () => {
const state = await loadState(params.baseDir);
const device = getPairedDeviceFromState(state, params.deviceId);
if (!device) {
return null;
}
const role = normalizeRole(params.role);
if (!role) {
return null;
}
const requestedScopes = normalizeScopes(params.scopes);
const tokens = cloneDeviceTokens(device);
const existing = tokens[role];
const context = resolveDeviceTokenUpdateContext({
state,
deviceId: params.deviceId,
role: params.role,
});
if (!context) {
return null;
}
const { device, role, tokens, existing } = context;
if (existing && !existing.revokedAtMs) {
if (scopesAllow(requestedScopes, existing.scopes)) {
return existing;
@@ -460,6 +459,29 @@ export async function ensureDeviceToken(params: {
});
}
function resolveDeviceTokenUpdateContext(params: {
state: DevicePairingStateFile;
deviceId: string;
role: string;
}): {
device: PairedDevice;
role: string;
tokens: Record<string, DeviceAuthToken>;
existing: DeviceAuthToken | undefined;
} | null {
const device = getPairedDeviceFromState(params.state, params.deviceId);
if (!device) {
return null;
}
const role = normalizeRole(params.role);
if (!role) {
return null;
}
const tokens = cloneDeviceTokens(device);
const existing = tokens[role];
return { device, role, tokens, existing };
}
export async function rotateDeviceToken(params: {
deviceId: string;
role: string;
@@ -468,16 +490,15 @@ export async function rotateDeviceToken(params: {
}): Promise<DeviceAuthToken | null> {
return await withLock(async () => {
const state = await loadState(params.baseDir);
const device = getPairedDeviceFromState(state, params.deviceId);
if (!device) {
const context = resolveDeviceTokenUpdateContext({
state,
deviceId: params.deviceId,
role: params.role,
});
if (!context) {
return null;
}
const role = normalizeRole(params.role);
if (!role) {
return null;
}
const tokens = cloneDeviceTokens(device);
const existing = tokens[role];
const { device, role, tokens, existing } = context;
const requestedScopes = normalizeScopes(params.scopes ?? existing?.scopes ?? device.scopes);
const now = Date.now();
const next = buildDeviceAuthToken({