Skip to content

Commit fa46601

Browse files
committed
Merge remote-tracking branch 'origin/main' into claude/project-thread-f6p2x0
2 parents aecae3b + 8b90442 commit fa46601

8 files changed

Lines changed: 297 additions & 194 deletions
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@object-ui/fields': patch
3+
---
4+
5+
refactor(fields)!: retire three zero-consumer entry exports (the hex badge palette pair and the url cell renderer)
6+
7+
Clause-②: no (narrowing)
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (runtime-export-retired @object-ui/fields#deriveHexBadgePalette, @object-ui/fields#HexBadgePalette, @object-ui/fields#UrlCellRenderer) the retired operands are a colour helper, its return type and a React cell renderer of the fields package; nothing in the workspace or in hotcrm imports or names any of them outside the package, and no packages/spec schema, registered node type, conversion surface or stored shape names them, so there is nothing for `objectstack migrate meta` to rewrite -->
11+
12+
**BREAKING** for a host that imports any of these three names from `@object-ui/fields`. None had an importer or a mention anywhere outside the package, in the workspace or in hotcrm, so the Console and every `@object-ui/*` package are unaffected. Badges and dots with a declared hex colour and `url` cells render exactly as before.
13+
14+
The code stays in the package; only the entry stops publishing it. The hex colour math moves from `index.tsx` to an internal module that `getBadgeHexAppearance` and `getDotHexAppearance` read, and `UrlCellRenderer` stays the renderer the standard map serves for `url` fields. Every other name the entry exported stays exported unchanged, among them `getBadgeHexAppearance`, `getDotHexAppearance`, the `HexColorAppearance` type, `getBadgeColorClasses`, `getCellRenderer`, `EmailCellRenderer`, `PhoneCellRenderer` and `ColorSwatchCellRenderer`.
15+
16+
What leaves, and what to write instead:
17+
18+
- FROM `deriveHexBadgePalette` TO `getBadgeHexAppearance(hex)` for the pill colours and `getDotHexAppearance(hex)` for the dot colours; both return the derived colours as CSS custom properties on `style`.
19+
- FROM `HexBadgePalette` TO the `HexColorAppearance` type those two functions return.
20+
- FROM `UrlCellRenderer` TO `getCellRenderer('url')`, which returns the same renderer (or the one a host registered for `url` with `registerFieldRenderer`).
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(plugin-auth): the organization client-address read answers a revoked or expired API key with the key's own refusal, not a 500
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`GET /api/v1/auth/client-address` resolves its caller through the settings door's composition, which admits an API key. A key its own lifecycle refuses (revoked, expired, inactive) was answered `500 INTERNAL_ERROR` with an error log line. The route now relays that refusal as the error declares it: `403` with `API_KEY_REVOKED`, `API_KEY_EXPIRED` or `API_KEY_INACTIVE` and the refusal's located message, as the settings routes and REST already answer the same key, and logs nothing for it. The `503` store-outage answer, the `401` / `403` admission refusals and an organization administrator's answer are unchanged.

‎packages/plugins/plugin-auth/src/allowed-ip-ranges.pin.test.ts‎

Lines changed: 56 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ import {
4646
builtinSettingsManifests,
4747
registerSettingsRoutes,
4848
} from '@objectstack/service-settings';
49-
import { AuthzStoreUnavailableError } from '@objectstack/core';
49+
import { AuthzStoreUnavailableError, hashApiKey } from '@objectstack/core';
5050
import { AuthPlugin } from './auth-plugin.js';
5151
import type { AuthManager } from './auth-manager.js';
5252
import type { OrganizationAddressReaderContext } from './client-address-read.js';
@@ -89,9 +89,10 @@ interface Rig {
8989
* `GET /api/v1/auth/client-address` on the same routes. `caller` is what the
9090
* route's resolution of its caller answers (the settings door's composition,
9191
* stubbed at that one seam): an organization administrator unless a test
92-
* says otherwise; an `Error` is thrown from it.
92+
* says otherwise; an `Error` is thrown from it; `'resolved'` leaves that
93+
* seam unstubbed, so the route's own composition resolves the caller.
9394
*/
94-
orgRead(transport?: Transport, opts?: { caller?: OrganizationAddressReaderContext | Error; query?: string }):
95+
orgRead(transport?: Transport, opts?: { caller?: OrganizationAddressReaderContext | Error | 'resolved'; query?: string }):
9596
Promise<{ status: number; body: any; cacheControl: string | null }>;
9697
}
9798

@@ -184,10 +185,12 @@ async function boot(
184185
const orgRead: Rig['orgRead'] = async (transport = {}, opts = {}) => {
185186
const app = mounted();
186187
const caller = 'caller' in opts ? opts.caller : ORG_ADMIN_CALLER;
187-
const resolve = vi.spyOn(plugin as any, 'resolveOrganizationSettingsCaller').mockImplementation(async () => {
188-
if (caller instanceof Error) throw caller;
189-
return caller;
190-
});
188+
const resolve = caller === 'resolved'
189+
? undefined
190+
: vi.spyOn(plugin as any, 'resolveOrganizationSettingsCaller').mockImplementation(async () => {
191+
if (caller instanceof Error) throw caller;
192+
return caller;
193+
});
191194
try {
192195
const res = await app.request(
193196
`http://localhost:3000/api/v1/auth/client-address${opts.query ?? ''}`,
@@ -196,7 +199,7 @@ async function boot(
196199
);
197200
return { status: res.status, body: await res.json(), cacheControl: res.headers.get('cache-control') };
198201
} finally {
199-
resolve.mockRestore();
202+
resolve?.mockRestore();
200203
}
201204
};
202205
return { svc, manager, logger: ctx.logger, save, read, orgRead };
@@ -552,6 +555,51 @@ describe('the organization administrator reads the address their access-policy s
552555
});
553556
});
554557

558+
describe("an API key its own lifecycle refuses is answered that refusal at the organization address read, never a 500", () => {
559+
const KEY = 'osk_client_address_lifecycle_pin';
560+
const LONG_AGO = '2000-01-01T00:00:00.000Z';
561+
562+
/**
563+
* The route's own caller resolution (the settings door's composition) over
564+
* a data engine holding the one `sys_api_key` row `row` describes, read by
565+
* the key's at-rest hash, as the admission reads it.
566+
*/
567+
const readWithKey = async (row: Record<string, unknown>) => {
568+
const rig = await boot();
569+
const keyHash = hashApiKey(KEY);
570+
vi.spyOn(rig.manager, 'getDataEngine').mockReturnValue({
571+
find: async (object: string, q: any) => (
572+
object === 'sys_api_key' && q?.where?.key === keyHash
573+
? [{ id: 'key_1', key: keyHash, prefix: 'osk_client', user_id: 'usr_key_owner', revoked: false, scopes: '[]', ...row }]
574+
: []
575+
),
576+
} as any);
577+
const asked = vi.spyOn(rig.manager, 'trustsForwardedHeaders');
578+
const res = await rig.orgRead({ headers: { 'x-api-key': KEY }, remoteAddress: '203.0.113.9' }, { caller: 'resolved' });
579+
expect(asked).not.toHaveBeenCalled();
580+
expect(res.body.success).toBe(false);
581+
expect(res.body.data).toBeUndefined();
582+
// A refusal the caller was told is no fault: the route logs no error line for it.
583+
expect(rig.logger.error.mock.calls.map(([line]) => line), JSON.stringify(res)).toEqual([]);
584+
return res;
585+
};
586+
587+
it('a revoked key: 403 API_KEY_REVOKED, the refusal\'s own status, code and message', async () => {
588+
const res = await readWithKey({ revoked: true });
589+
expect(res.status).toBe(403);
590+
expect(res.body.error.code).toBe('API_KEY_REVOKED');
591+
// The refusal's own located message (its first sentence names the key), not the route's fault text.
592+
expect(res.body.error.message.startsWith('This API key (osk_client…) was revoked. ')).toBe(true);
593+
});
594+
595+
it('an expired key: 403 API_KEY_EXPIRED, the refusal\'s own status, code and message', async () => {
596+
const res = await readWithKey({ expires_at: LONG_AGO });
597+
expect(res.status).toBe(403);
598+
expect(res.body.error.code).toBe('API_KEY_EXPIRED');
599+
expect(res.body.error.message.startsWith(`This API key (osk_client…) expired on ${LONG_AGO}. `)).toBe(true);
600+
});
601+
});
602+
555603
describe('an allowed IP range whose prefix is not decimal digits within its family is refused at every save door and never matches at the gate', () => {
556604
// An entry is an address, or an address, `/` and a prefix length of one or
557605
// two decimal digits from 0 to 32 (IPv4) or one to three from 0 to 128

‎packages/plugins/plugin-auth/src/auth-plugin.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
isCloudManaged,
1010
resolveRequestExecutionContext,
1111
isAuthzStoreUnavailableError,
12+
isApiKeyLifecycleRefusalError,
1213
AUTHZ_STORE_UNAVAILABLE_CODE,
1314
AUTHZ_STORE_UNAVAILABLE_MESSAGE,
1415
AUTHZ_STORE_UNAVAILABLE_STATUS,
@@ -4100,6 +4101,12 @@ export class AuthPlugin implements Plugin {
41004101
AUTHZ_STORE_UNAVAILABLE_STATUS,
41014102
);
41024103
}
4104+
// An API key its own lifecycle refuses (revoked, expired, inactive) is
4105+
// the caller's refusal, never a fault: relayed as the error declares it,
4106+
// its status, code and located message, as the settings door relays it.
4107+
if (isApiKeyLifecycleRefusalError(error)) {
4108+
return c.json({ success: false, error: { code: error.code, message: error.message } }, error.status);
4109+
}
41034110
const err = error instanceof Error ? error : new Error(String(error));
41044111
ctx.logger.error('[AuthPlugin] client-address failed', err);
41054112
return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: 'Your client address could not be read.' } }, 500);

‎ui/packages/fields/src/__tests__/badge-hex-fidelity-5141.test.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ import {
3434
getBadgeHexAppearance,
3535
getDotHexAppearance,
3636
getSemanticColorName,
37-
deriveHexBadgePalette,
3837
} from '../index';
38+
import { deriveHexBadgePalette } from '../hexBadgePalette';
3939

4040
/* ---------------------------------------------------------------- colour math */
4141

‎ui/packages/fields/src/__tests__/cellRenderers.linkEllipsis-12523.test.tsx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,11 @@
3636
import { describe, it, expect } from 'vitest';
3737
import { render, screen } from '@testing-library/react';
3838
import * as React from 'react';
39-
import { EmailCellRenderer, PhoneCellRenderer, UrlCellRenderer } from '../index';
39+
import { EmailCellRenderer, PhoneCellRenderer, getCellRenderer } from '../index';
40+
41+
// The url renderer is not exported by name; read it through the registry face
42+
// every list and detail view uses.
43+
const UrlCellRenderer = getCellRenderer('url');
4044

4145
const EMAIL = 'mira.costa@atlasconstruction.example.com';
4246
const PHONE = '+1-555-0117-1119';
Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
/**
2+
* Explicit-hex badge colour math (objectui#5141): one author-declared hex in,
3+
* the soft-pill and dot palette out. The rendering half (the static Tailwind
4+
* utility strings, `getBadgeHexAppearance`, `getDotHexAppearance`) and the
5+
* block's rationale live in `index.tsx`, the only reader.
6+
*
7+
* Not re-exported from the package entry: `getBadgeHexAppearance` and
8+
* `getDotHexAppearance` are the public faces of this palette.
9+
*/
10+
11+
/** WCAG AA floor for badge label text against its own pill surface. */
12+
const BADGE_TEXT_CONTRAST = 4.5;
13+
14+
/**
15+
* Visibility floor for the `appearance: 'dot'` marker. A dot carries no text,
16+
* so the AA *text* ratio does not apply; this is the measured floor of the
17+
* -500 shades `DOT_COLOR_MAP` (in `index.tsx`) ships today (yellow-500
18+
* `#eab308` is the weakest at 1.92:1 on white). Pinning it here means an author-declared dot is never
19+
* less visible than the palette dot it replaces.
20+
*/
21+
const DOT_CONTRAST_FLOOR = 1.9;
22+
23+
interface Rgb { r: number; g: number; b: number }
24+
25+
/** Surfaces a dot sits on — used only to keep the dot itself visible. */
26+
const LIGHT_SURFACE: Rgb = { r: 255, g: 255, b: 255 };
27+
const DARK_SURFACE: Rgb = { r: 10, g: 10, b: 10 };
28+
29+
const clampNum = (v: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, v));
30+
31+
function parseHexColor(hex: string): Rgb | undefined {
32+
const m = /^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.exec(hex.trim());
33+
if (!m) return undefined;
34+
let h = m[1];
35+
if (h.length === 3) h = h.split('').map((c) => c + c).join('');
36+
return {
37+
r: parseInt(h.slice(0, 2), 16),
38+
g: parseInt(h.slice(2, 4), 16),
39+
b: parseInt(h.slice(4, 6), 16),
40+
};
41+
}
42+
43+
function rgbToHsl({ r, g, b }: Rgb): { h: number; s: number; l: number } {
44+
const rn = r / 255, gn = g / 255, bn = b / 255;
45+
const max = Math.max(rn, gn, bn);
46+
const min = Math.min(rn, gn, bn);
47+
const d = max - min;
48+
const l = (max + min) / 2;
49+
const s = d === 0 ? 0 : d / (1 - Math.abs(2 * l - 1));
50+
let h = 0;
51+
if (d !== 0) {
52+
if (max === rn) h = (((gn - bn) / d) % 6 + 6) % 6;
53+
else if (max === gn) h = (bn - rn) / d + 2;
54+
else h = (rn - gn) / d + 4;
55+
h *= 60;
56+
}
57+
return { h, s, l };
58+
}
59+
60+
function hslToRgb(h: number, s: number, l: number): Rgb {
61+
const hue = ((h % 360) + 360) % 360;
62+
const c = (1 - Math.abs(2 * l - 1)) * s;
63+
const x = c * (1 - Math.abs(((hue / 60) % 2) - 1));
64+
const m = l - c / 2;
65+
let p: [number, number, number];
66+
if (hue < 60) p = [c, x, 0];
67+
else if (hue < 120) p = [x, c, 0];
68+
else if (hue < 180) p = [0, c, x];
69+
else if (hue < 240) p = [0, x, c];
70+
else if (hue < 300) p = [x, 0, c];
71+
else p = [c, 0, x];
72+
return {
73+
r: Math.round((p[0] + m) * 255),
74+
g: Math.round((p[1] + m) * 255),
75+
b: Math.round((p[2] + m) * 255),
76+
};
77+
}
78+
79+
const rgbToHex = ({ r, g, b }: Rgb): string =>
80+
'#' + [r, g, b].map((v) => clampNum(Math.round(v), 0, 255).toString(16).padStart(2, '0')).join('');
81+
82+
/** WCAG relative luminance of an sRGB color. */
83+
function relativeLuminance({ r, g, b }: Rgb): number {
84+
const channel = (v: number): number => {
85+
const c = v / 255;
86+
return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
87+
};
88+
return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
89+
}
90+
91+
/** WCAG contrast ratio between two colors (1..21). */
92+
function contrastRatio(a: Rgb, b: Rgb): number {
93+
const la = relativeLuminance(a);
94+
const lb = relativeLuminance(b);
95+
return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
96+
}
97+
98+
/**
99+
* Walk the declared hue for the lightness *closest to the declared one* that
100+
* still clears `target` against `surface`.
101+
*
102+
* Choosing the closest passing lightness rather than simply maximizing
103+
* contrast is what keeps the author's colour recognizable — maximizing would
104+
* collapse every badge label to black or white and re-lose the declaration we
105+
* are here to preserve. Only when the hue cannot reach the target at any
106+
* lightness (a very low-chroma declaration against a mid surface) do we fall
107+
* back to black or white, whichever is further from the surface: legibility
108+
* outranks fidelity.
109+
*/
110+
function readableOnSurface(
111+
h: number,
112+
s: number,
113+
declaredL: number,
114+
surface: Rgb,
115+
target: number,
116+
): Rgb {
117+
let best: Rgb | undefined;
118+
let bestDistance = Infinity;
119+
for (let step = 0; step <= 100; step++) {
120+
const lightness = step / 100;
121+
const candidate = hslToRgb(h, s, lightness);
122+
if (contrastRatio(candidate, surface) < target) continue;
123+
const distance = Math.abs(lightness - declaredL);
124+
if (distance < bestDistance) {
125+
bestDistance = distance;
126+
best = candidate;
127+
}
128+
}
129+
if (best) return best;
130+
const black: Rgb = { r: 0, g: 0, b: 0 };
131+
const white: Rgb = { r: 255, g: 255, b: 255 };
132+
return contrastRatio(black, surface) >= contrastRatio(white, surface) ? black : white;
133+
}
134+
135+
/** The six pill colors plus the two dot colors derived from one declared hex. */
136+
export interface HexBadgePalette {
137+
bg: string;
138+
fg: string;
139+
border: string;
140+
bgDark: string;
141+
fgDark: string;
142+
borderDark: string;
143+
dot: string;
144+
dotDark: string;
145+
}
146+
147+
/**
148+
* Derive a full soft-pill palette from an author-declared hex.
149+
*
150+
* The declared LIGHTNESS is what separates two same-hue tiers (`#2ecc71` is
151+
* l=0.49, `#1e8449` is l=0.32 — their hues differ by 0.1°), so it has to
152+
* survive into the *surface*. A fixed pale tint — the obvious reading of
153+
* "compute a soft pill from the hex" — does not carry it: measured, that
154+
* leaves the reported pair ΔE 2.3 apart in Lab, at the ~2.3 just-noticeable
155+
* threshold, which would close this issue on paper while the user still cannot
156+
* tell the two badges apart. Letting the tint depth track the declared
157+
* lightness puts them ΔE 8.0 apart instead.
158+
*/
159+
export function deriveHexBadgePalette(color: string): HexBadgePalette | undefined {
160+
const rgb = parseHexColor(color);
161+
if (!rgb) return undefined;
162+
const { h, s, l } = rgbToHsl(rgb);
163+
// Keep a usable chroma at both ends: a fully desaturated declaration stays
164+
// neutral instead of being pushed into a hue it never declared, and a neon
165+
// one is reined in so the pill never fights the row it sits in.
166+
const sat = clampNum(s, 0.18, 0.92);
167+
168+
// Light theme: pale for light declarations (the -50 look we ship today),
169+
// deepening as the declared colour darkens.
170+
const bgLightness = 0.95 - 0.32 * (1 - l);
171+
const bg = hslToRgb(h, sat * (0.55 + 0.25 * (1 - l)), bgLightness);
172+
const border = hslToRgb(h, sat * 0.62, clampNum(bgLightness - 0.14, 0, 1));
173+
const fg = readableOnSurface(h, sat, l, bg, BADGE_TEXT_CONTRAST);
174+
175+
// Dark theme: the same idea mirrored — a dark surface whose depth tracks the
176+
// declared lightness, with the label lifted until it clears AA against it.
177+
const bgDarkLightness = 0.10 + 0.30 * l;
178+
const bgDark = hslToRgb(h, sat * 0.6, bgDarkLightness);
179+
const borderDark = hslToRgb(h, sat * 0.55, clampNum(bgDarkLightness + 0.12, 0, 1));
180+
const fgDark = readableOnSurface(h, sat, l, bgDark, BADGE_TEXT_CONTRAST);
181+
182+
return {
183+
bg: rgbToHex(bg),
184+
fg: rgbToHex(fg),
185+
border: rgbToHex(border),
186+
bgDark: rgbToHex(bgDark),
187+
fgDark: rgbToHex(fgDark),
188+
borderDark: rgbToHex(borderDark),
189+
dot: rgbToHex(readableOnSurface(h, sat, l, LIGHT_SURFACE, DOT_CONTRAST_FLOOR)),
190+
dotDark: rgbToHex(readableOnSurface(h, sat, l, DARK_SURFACE, DOT_CONTRAST_FLOOR)),
191+
};
192+
}

0 commit comments

Comments
 (0)