Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
38 changes: 28 additions & 10 deletions cli/src/commands/linear.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import {
resolveStoredGrantFields,
readExistingWebhookSecret,
resolveWebhookSecretAction,
StoredLinearOauthToken,
StoredLinearOauthToken, describePreservedFallback,
} from '../linear-oauth';
import {
clearPendingConsent,
Expand Down Expand Up @@ -1617,7 +1617,7 @@ export function makeLinearCommand(): Command {
console.log(` ✓ (${secretName})`);
// After the progress line closes, not during it.
if (preservedTokens) {
console.log(' ✓ Kept the existing Secrets Manager token as a fallback');
console.log(` ${describePreservedFallback(preservedTokens).message}`);
}

// ─── Step 5: Persist registry + user-mapping rows ─────────────
Expand Down Expand Up @@ -2552,10 +2552,9 @@ export function makeLinearCommand(): Command {
console.log(` ${i + 1}. ${m.name ?? m.id}${email}`);
});
console.log();
const pickRaw = (await promptLine(` Which one is the teammate? [1-${humans.length}]`)).trim();
const pickIdx = parseInt(pickRaw, 10) - 1;
if (Number.isNaN(pickIdx) || pickIdx < 0 || pickIdx >= humans.length) {
throw new CliError(`Invalid selection '${pickRaw}'.`);
const pickIdx = await promptChoice(` Which one is the teammate? [1-${humans.length}]`, humans.length);
if (pickIdx === undefined) {
throw new CliError('No valid selection.');
}
const picked = humans[pickIdx];
const pickedLabel = `${picked.name ?? picked.id}${picked.email ? ` (${picked.email})` : ''}`;
Expand Down Expand Up @@ -3091,6 +3090,26 @@ function promptLine(label: string, defaultValue?: string): Promise<string> {
});
}

/**
* Ask for a 1-based choice, re-asking on an empty or invalid answer. A paste that
* ends in a newline followed by Enter leaves a stray line for the NEXT prompt;
* failing on it would silently skip the choice. Returns undefined after `attempts`.
*/
export async function promptChoice(
label: string,
count: number,
ask: (label: string) => Promise<string> = promptLine,
attempts = 3,
): Promise<number | undefined> {
for (let attempt = 0; attempt < attempts; attempt++) {
const raw = (await ask(label)).trim();
const idx = /^\d+$/.test(raw) ? parseInt(raw, 10) - 1 : -1;
if (idx >= 0 && idx < count) return idx;
if (attempt < attempts - 1) process.stderr.write(raw ? ` '${raw}' is not between 1 and ${count}.\n` : '');
}
return undefined;
}

// ─── Auto-link ───────────────────────────────────────────────────────────────

interface LinearViewer {
Expand Down Expand Up @@ -3267,10 +3286,9 @@ async function runSelfLinkPicker(args: {
console.log(` ${i + 1}. ${m.name ?? m.id}${email}`);
});
console.log();
const pickRaw = (await promptLine(` Which one is you? [1-${humans.length}]`)).trim();
const pickIdx = parseInt(pickRaw, 10) - 1;
if (Number.isNaN(pickIdx) || pickIdx < 0 || pickIdx >= humans.length) {
console.log(` ⚠ Invalid selection '${pickRaw}'; skipping self-link.`);
const pickIdx = await promptChoice(` Which one is you? [1-${humans.length}]`, humans.length);
if (pickIdx === undefined) {
console.log(' ⚠ No valid selection; skipping self-link.');
console.log(' Re-run setup or pick yourself later via the picker that fires on first failed trigger.');
return false;
}
Expand Down
23 changes: 23 additions & 0 deletions cli/src/linear-oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -582,3 +582,26 @@ export async function verifyLinearRefreshAndPersist(args: {
}
return 'refreshed';
}

/**
* How setup should describe a Secrets-Manager token it kept when moving onto the
* vault. A refresh token cannot be checked without rotating it, so an expired
* access token is reported as unverified rather than as a working fallback:
* Linear rejects refresh tokens that went unused for too long.
*/
export function describePreservedFallback(
preserved: Pick<StoredLinearOauthToken, 'expires_at'>,
now: Date = new Date(),
): { readonly usable: boolean; readonly message: string } {
const expiresAt = Date.parse(preserved.expires_at);
if (Number.isFinite(expiresAt) && expiresAt <= now.getTime()) {
return {
usable: false,
message:
`⚠ Kept the existing Secrets Manager token, but its access token expired on ${preserved.expires_at}. `
+ 'It only works as a fallback if Linear still accepts its refresh token, which expires when '
+ 'unused. Treat the vault as the only verified credential for this workspace.',
};
}
return { usable: true, message: '✓ Kept the existing Secrets Manager token as a fallback' };
}
24 changes: 24 additions & 0 deletions cli/test/commands/linear.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
isWebhookSecretConfigured,
queryLinearTeamKeys,
parsePastedAuthorization,
promptChoice,
renderLinearAppTemplate,
} from '../../src/commands/linear';
import * as config from '../../src/config';
Expand Down Expand Up @@ -874,3 +875,26 @@ describe('parsePastedAuthorization', () => {
expect(parsePastedAuthorization('code=abc123&state=')).toEqual({ code: 'abc123' });
});
});

describe('promptChoice', () => {
const answers = (...values: string[]) => {
const queue = [...values];
return jest.fn(async () => queue.shift() ?? '');
};

test('re-asks after a stray empty line left by a pasted newline', async () => {
const ask = answers('', '2');
expect(await promptChoice('Which one is you?', 2, ask)).toBe(1);
expect(ask).toHaveBeenCalledTimes(2);
});

test('re-asks on out-of-range or non-numeric answers', async () => {
expect(await promptChoice('Pick', 3, answers('9', 'x2', '3'))).toBe(2);
});

test('gives up after the attempt budget instead of looping forever', async () => {
const ask = answers('', '', '');
expect(await promptChoice('Pick', 2, ask)).toBeUndefined();
expect(ask).toHaveBeenCalledTimes(3);
});
});
18 changes: 18 additions & 0 deletions cli/test/linear-oauth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { CliError } from '../src/errors';
import {
buildAuthorizationUrl,
computeExpiresAt,
describePreservedFallback,
exchangeAuthorizationCode,
generatePkce,
isAccessTokenExpiring,
Expand Down Expand Up @@ -703,3 +704,20 @@ describe('resolveStoredGrantFields — a preserved grant must never be overwritt
});
});
});

describe('describePreservedFallback', () => {
const now = new Date('2026-11-05T00:00:00Z');

test('an expired access token is reported as an unverified fallback, not a working one', () => {
const result = describePreservedFallback({ expires_at: '2026-07-29T10:09:20.000Z' }, now);
expect(result.usable).toBe(false);
expect(result.message).toContain('expired on 2026-07-29T10:09:20.000Z');
expect(result.message).not.toContain('✓');
});

test('a live access token is kept as a fallback', () => {
expect(describePreservedFallback({ expires_at: '2026-11-06T00:00:00Z' }, now)).toEqual({
usable: true, message: '✓ Kept the existing Secrets Manager token as a fallback',
});
});
});
Loading