From 89fcf060696617d6b6281d8d3b0328b05b4400d7 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Fri, 4 Dec 2026 17:48:36 +0800 Subject: [PATCH] fix(token): name the organization a token is pinned to MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit flb token create -o ended its success line with "pinned to undefined". The Registry Service returns a token's organization as its id (org_…), and the CLI read .slug from it as if it were an object. The token itself was pinned correctly. The message now names the organization passed with -o, and otherwise whatever the response carries: a slug from an object, or the id. The same assumption left the ORG column of flb token list empty for pinned tokens; it now shows the slug, looked up from the account when a token carries only the id, and the id when that lookup fails. token create --save also kept the previous default organization instead of the one the new token is pinned to. --json output is unchanged: it passes the service's response through. --- src/commands/token.ts | 53 +++++++++++++++++++++--- src/types.ts | 3 +- test/unit/auth.test.ts | 91 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 141 insertions(+), 6 deletions(-) diff --git a/src/commands/token.ts b/src/commands/token.ts index 66b9792..2c85e62 100644 --- a/src/commands/token.ts +++ b/src/commands/token.ts @@ -2,7 +2,7 @@ import type { Command } from 'commander'; import { clearToken, configDisplayPath, hostMeta, setToken, updateConfig } from '../config.js'; import { type Context, context } from '../context.js'; import { colors, formatDate, log, table } from '../output.js'; -import type { IssuedToken, TokenDetails } from '../types.js'; +import type { Account, IssuedToken, TokenDetails } from '../types.js'; import { CliError, parseDays, splitList } from '../util.js'; import { validateScopes } from './auth.js'; @@ -35,6 +35,35 @@ export function register(program: Command): void { .action((ids: string[], _opts, command: Command) => revokeTokens(context(command), ids)); } +type TokenOrganization = TokenDetails['organization']; + +/** + * Names the organization a token is pinned to. The service sends the organization's id (`org_…`), not + * an object, so the slug comes from `slugs` (id → slug) when there is one, and the id is shown otherwise. + */ +export function organizationLabel(organization: TokenOrganization | undefined, slugs: Record = {}): string { + if (!organization) { + return ''; + } + if (typeof organization === 'string') { + return slugs[organization] || organization; + } + return organization.slug || (organization.id && slugs[organization.id]) || organization.id || ''; +} + +/** The slug of the organization a new token is pinned to, when it is known: from the response, or the one passed with `-o`. */ +function pinnedSlug(organization: TokenOrganization, requested?: string): string | undefined { + if (!organization) { + return undefined; + } + if (typeof organization !== 'string' && organization.slug) { + return organization.slug; + } + const id = typeof organization === 'string' ? organization : organization.id; + // `-o` also takes an organization id, which is not a slug + return requested && requested !== id ? requested : undefined; +} + interface CreateOptions { name: string; scopes: string; @@ -66,7 +95,7 @@ export async function createToken(ctx: Context, opts: CreateOptions): Promise { - const tokens = await ctx.authed().get('v1/account/tokens'); + const client = ctx.authed(); + const tokens = await client.get('v1/account/tokens'); if (ctx.json) { log.json(tokens); return; @@ -100,13 +131,25 @@ export async function listTokens(ctx: Context): Promise { return; } const current = hostMeta(ctx.config, ctx.registry).tokenId; + // a pinned token carries its organization's id; the account knows the slug. Without it the id is shown. + const slugs: Record = {}; + if (tokens.some((t) => t.organization && (typeof t.organization === 'string' || !t.organization.slug))) { + try { + const account = await client.get('v1/account'); + for (const org of account.organizations || []) { + slugs[org.id] = org.slug; + } + } catch { + // the ids still name the organizations + } + } log.line( table(tokens, [ { header: 'ID', value: (t) => (t.id === current ? `${t.id} ${colors.green('*')}` : t.id) }, { header: 'NAME', value: (t) => t.name, max: 32 }, { header: 'TOKEN', value: (t) => t.masked }, { header: 'SCOPES', value: (t) => t.scopes.join(',') }, - { header: 'ORG', value: (t) => t.organization?.slug || '' }, + { header: 'ORG', value: (t) => organizationLabel(t.organization, slugs) }, { header: 'LAST USED', value: (t) => formatDate(t.last_used_at) }, { header: 'EXPIRES', value: (t) => (t.revoked_at ? colors.red('revoked') : formatDate(t.expires_at)) }, ]), diff --git a/src/types.ts b/src/types.ts index 95b3347..89ec08c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -25,7 +25,8 @@ export interface TokenDetails { prefix: string; last_four: string; scopes: string[]; - organization: { id: string; slug: string; name: string } | null; + /** The organization the token is pinned to: the service sends its id (`org_…`); an object with a slug is read too. */ + organization: string | { id?: string; slug?: string; name?: string } | null; expires_at: string | null; last_used_at: string | null; revoked_at: string | null; diff --git a/test/unit/auth.test.ts b/test/unit/auth.test.ts index b264e65..7050e63 100644 --- a/test/unit/auth.test.ts +++ b/test/unit/auth.test.ts @@ -173,6 +173,59 @@ describe('token', () => { expect(readConfigFile().hosts['registry.test:8000']).toMatchObject({ tokenId: 'tok_2', source: 'token-create' }); }); + it('create names the organization a token is pinned to, whichever shape the service answers with', async () => { + const created = (organization: unknown) => ({ + 'POST /v1/account/tokens': { status: 201, body: { token: OTHER_TOKEN, token_type: 'Bearer', expires_at: null, token_details: tokenDetails({ id: 'tok_2', name: 'ci', scopes: ['install'], organization }) } }, + }); + const create = async (...args: string[]) => { + const out = capture(); + expect(await flb('token', 'create', '--name', 'ci', '--scopes', 'install', '--show-token', ...args)).toBe(0); + return out.stderr; + }; + + // what the service sends: the organization's id + const { requests } = fakeRegistry(created('org_1')); + let message = await create('-o', 'acme'); + expect(requests[0].body).toMatchObject({ organization: 'acme' }); + expect(message).toMatch(/Created token ci \(tok_2\), scopes install, expires .*, pinned to acme\./); + expect(message).not.toContain('undefined'); + + // an object with a slug + fakeRegistry(created({ id: 'org_1', slug: 'acme', name: 'Acme' })); + expect(await create('-o', 'acme')).toMatch(/, pinned to acme\./); + + // no slug given on the command line: the response names it, by slug when it has one + fakeRegistry(created({ id: 'org_1', slug: 'acme', name: 'Acme' })); + expect(await create()).toMatch(/, pinned to acme\./); + fakeRegistry(created('org_1')); + expect(await create()).toMatch(/, pinned to org_1\./); + + // not pinned: nothing is said, even with -o + fakeRegistry(created(null)); + message = await create('-o', 'acme'); + expect(message).toMatch(/expires [^,]*\.\n/); + expect(message).not.toContain('pinned'); + }); + + it('create --save keeps the pinned organization as the default, by slug', async () => { + const created = (organization: unknown) => ({ + 'POST /v1/account/tokens': { status: 201, body: { token: OTHER_TOKEN, token_type: 'Bearer', expires_at: null, token_details: tokenDetails({ id: 'tok_2', name: 'ci', organization }) } }, + }); + const saved = async (...args: string[]) => { + capture(); + expect(await flb('token', 'create', '--name', 'ci', '--save', ...args)).toBe(0); + return readConfigFile().hosts['registry.test:8000'].organization; + }; + + fakeRegistry(created('org_1')); + expect(await saved('-o', 'acme')).toBe('acme'); + fakeRegistry(created({ id: 'org_2', slug: 'globex', name: 'Globex' })); + expect(await saved('-o', 'globex')).toBe('globex'); + // an id is not a slug: the default stays as it was + fakeRegistry(created('org_1')); + expect(await saved('-o', 'org_1')).toBe('globex'); + }); + it('create rejects unknown scopes', async () => { fakeRegistry({}); const out = capture(); @@ -188,6 +241,44 @@ describe('token', () => { expect(out.stdout).toContain('flbp_…Q7k2'); }); + it('list names the organization of a pinned token, by slug when the account gives one', async () => { + const tokens = [ + tokenDetails(), + tokenDetails({ id: 'tok_2', name: 'pinned-by-id', organization: 'org_1' }), + tokenDetails({ id: 'tok_3', name: 'pinned-by-object', organization: { id: 'org_2', slug: 'globex', name: 'Globex' } }), + tokenDetails({ id: 'tok_4', name: 'pinned-elsewhere', organization: 'org_9' }), + ]; + const org = (output: string, name: string) => output.split('\n').find((line) => line.includes(name))!; + + const { requests } = fakeRegistry({ 'GET /v1/account/tokens': tokens, 'GET /v1/account': account }); + let out = capture(); + expect(await flb('token', 'list')).toBe(0); + expect(requests.map((request) => request.path)).toEqual(['/v1/account/tokens', '/v1/account']); + expect(out.stdout).not.toContain('undefined'); + expect(org(out.stdout, 'pinned-by-id')).toMatch(/\bacme\b/); + expect(org(out.stdout, 'pinned-by-object')).toMatch(/\bglobex\b/); + expect(org(out.stdout, 'pinned-elsewhere')).toMatch(/\borg_9\b/); + + // the account cannot be read: the ids are shown + fakeRegistry({ 'GET /v1/account/tokens': tokens }); + out = capture(); + expect(await flb('token', 'list')).toBe(0); + expect(org(out.stdout, 'pinned-by-id')).toMatch(/\borg_1\b/); + expect(org(out.stdout, 'pinned-by-object')).toMatch(/\bglobex\b/); + + // nothing to look up when no token is pinned by id + const plain = fakeRegistry({ 'GET /v1/account/tokens': [tokenDetails(), tokens[2]], 'GET /v1/account': account }); + capture(); + expect(await flb('token', 'list')).toBe(0); + expect(plain.requests.map((request) => request.path)).toEqual(['/v1/account/tokens']); + + // --json passes the response through + fakeRegistry({ 'GET /v1/account/tokens': tokens }); + out = capture(); + expect(await flb('token', 'list', '--json')).toBe(0); + expect(JSON.parse(out.stdout).map((token: { organization: unknown }) => token.organization)).toEqual([null, 'org_1', { id: 'org_2', slug: 'globex', name: 'Globex' }, 'org_9']); + }); + it('revoking the current token removes it from the config', async () => { const { requests } = fakeRegistry({ 'DELETE /v1/account/tokens/tok_1': { status: 204, body: undefined }, 'DELETE /v1/account/tokens/tok_9': { status: 404, body: { errors: ['Resource not found.'] } } }); const out = capture();