@vdatacloud/cx-commons 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -1
- package/package.json +5 -4
- package/src/sdk/api-client.ts +92 -0
- package/src/sdk/html.ts +20 -0
- package/src/sdk/oidc-pkce.ts +178 -0
package/README.md
CHANGED
|
@@ -42,7 +42,7 @@ This repository publishes `@vdatacloud/cx-commons` with modular export entry poi
|
|
|
42
42
|
├── (default) --> exports index.ts (Astro integration plugin `cxCommons()`)
|
|
43
43
|
├── /styles/global.css --> exports canonical LNF design system tokens & Tailwind rules
|
|
44
44
|
├── /components/* --> exports shared Astro UI components (Nav, Footer, StatusBadge, EyebrowLabel, ApiErrorNotice, CantonId, LanguageSwitcher)
|
|
45
|
-
├── /sdk/* --> exports browser SDK helpers (i18n, cx-messages, dialogs, api-error, api-error-notice, canton-id, canton-id-view, agreement-sig, pending-approvals, status-colors)
|
|
45
|
+
├── /sdk/* --> exports browser SDK helpers (i18n, cx-messages, dialogs, api-error, api-error-notice, canton-id, canton-id-view, agreement-sig, pending-approvals, status-colors, oidc-pkce, api-client, html)
|
|
46
46
|
└── /schema/api-error.json --> the canonical API error JSON Schema
|
|
47
47
|
```
|
|
48
48
|
|
|
@@ -100,6 +100,19 @@ An act that isn't a proposal (daml-escrow PLAN.md Phase 92.5: a staged release i
|
|
|
100
100
|
|
|
101
101
|
---
|
|
102
102
|
|
|
103
|
+
### Sign-in, API calls and markup (`sdk/oidc-pkce`, `sdk/api-client`, `sdk/html`)
|
|
104
|
+
|
|
105
|
+
Shared by the escrow portal and the operator console (daml-escrow PLAN.md Phase 104).
|
|
106
|
+
|
|
107
|
+
- `sdk/oidc-pkce`: Authorization Code + PKCE against Okta or the dev issuer (daml-escrow-commons `devoidc`):
|
|
108
|
+
`startAuthorization` (stores verifier, state, issuer, client; returns the authorize URL), `validateState` (one use),
|
|
109
|
+
`exchangeCode`; `tokenScopes`, `tokenExpirySeconds`, `tokenClaims` for display only (servers enforce from the
|
|
110
|
+
verified token). Which scopes to ask for and the app's session store stay in the app.
|
|
111
|
+
- `sdk/api-client`: `createApiClient({ baseUrl, token, onError })` sends the bearer token and JSON, and throws
|
|
112
|
+
`ApiRequestError` (the parsed envelope, for `ApiErrorNotice`) on any refusal; `errorFromResponse` for apps that call
|
|
113
|
+
`fetch` themselves.
|
|
114
|
+
- `sdk/html`: `esc` for every value interpolated into markup built as a string, `fragment` to turn it into nodes.
|
|
115
|
+
|
|
103
116
|
### Internationalization (`sdk/i18n`, `sdk/cx-messages`)
|
|
104
117
|
|
|
105
118
|
Zero-dependency i18n for every app on the platform (English and French today; built so Japanese, Chinese and
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vdatacloud/cx-commons",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Product CX Commons - Shared design system, UI components, and Astro integration for Data Cloud web applications",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -30,7 +30,8 @@
|
|
|
30
30
|
"scripts": {
|
|
31
31
|
"build": "tsc",
|
|
32
32
|
"test": "vitest run",
|
|
33
|
-
"sync:api-error-fixtures": "scripts/sync-api-error-fixtures.sh"
|
|
33
|
+
"sync:api-error-fixtures": "scripts/sync-api-error-fixtures.sh",
|
|
34
|
+
"vuln-check": "npm audit --audit-level=high"
|
|
34
35
|
},
|
|
35
36
|
"peerDependencies": {
|
|
36
37
|
"@tailwindcss/typography": "^0.5.0",
|
|
@@ -39,8 +40,8 @@
|
|
|
39
40
|
},
|
|
40
41
|
"devDependencies": {
|
|
41
42
|
"@tailwindcss/typography": "^0.5.20",
|
|
42
|
-
"astro": "^7.
|
|
43
|
-
"happy-dom": "^
|
|
43
|
+
"astro": "^7.4.5",
|
|
44
|
+
"happy-dom": "^21.0.4",
|
|
44
45
|
"typescript": "^5.7.0",
|
|
45
46
|
"vitest": "^5.0.3"
|
|
46
47
|
},
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// Calling a platform service from a browser app: the bearer token on every
|
|
2
|
+
// request, JSON in and out, and every refusal as an ApiRequestError carrying
|
|
3
|
+
// the parsed error envelope (./api-error, the mirror of daml-escrow-commons
|
|
4
|
+
// apierror) for ApiErrorNotice to render.
|
|
5
|
+
//
|
|
6
|
+
// Shared by the escrow portal (its ApiRequestError) and the operator console
|
|
7
|
+
// (daml-escrow PLAN.md Phase 104). An app's own reactions to particular
|
|
8
|
+
// refusals (a step-up sign-in, a signing session) go in onError.
|
|
9
|
+
|
|
10
|
+
import { formatApiError, parseApiError, type ApiError } from './api-error';
|
|
11
|
+
|
|
12
|
+
/** A refused request: the parsed envelope, and a message for plain display. */
|
|
13
|
+
export class ApiRequestError extends Error {
|
|
14
|
+
constructor(readonly apiError: ApiError, message = formatApiError(apiError)) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = 'ApiRequestError';
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The ApiRequestError for a non-2xx response: any body (the envelope, a
|
|
22
|
+
* legacy {"error"} or plain text) parses; the X-Request-Id header fills in a
|
|
23
|
+
* missing request id. Reads a clone, so the caller can still read the body.
|
|
24
|
+
*/
|
|
25
|
+
export async function errorFromResponse(response: Response, fallback = 'Request failed'): Promise<ApiRequestError> {
|
|
26
|
+
const text = await response.clone().text().catch(() => '');
|
|
27
|
+
const e = parseApiError(response.status, text || fallback);
|
|
28
|
+
const id = response.headers.get('X-Request-Id');
|
|
29
|
+
if (!e.requestId && id) e.requestId = id;
|
|
30
|
+
return new ApiRequestError(e);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface ApiClientOptions {
|
|
34
|
+
/** The service's base URL, e.g. https://ops.example/api/v1. */
|
|
35
|
+
baseUrl: string;
|
|
36
|
+
/** The current access token; null sends no Authorization header. */
|
|
37
|
+
token: () => string | null;
|
|
38
|
+
/** Runs before a refusal is thrown (e.g. offer a new sign-in on 401). */
|
|
39
|
+
onError?: (response: Response) => void | Promise<void>;
|
|
40
|
+
fetchImpl?: typeof fetch;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface ApiClient {
|
|
44
|
+
get<T>(path: string, init?: RequestInit): Promise<T>;
|
|
45
|
+
post<T>(path: string, body?: unknown, init?: RequestInit): Promise<T>;
|
|
46
|
+
patch<T>(path: string, body?: unknown, init?: RequestInit): Promise<T>;
|
|
47
|
+
put<T>(path: string, body?: unknown, init?: RequestInit): Promise<T>;
|
|
48
|
+
delete<T>(path: string, init?: RequestInit): Promise<T>;
|
|
49
|
+
/** The raw response for anything else (downloads, uploads); throws on refusal. */
|
|
50
|
+
request(path: string, init?: RequestInit): Promise<Response>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A client for one service. Path segments that carry ids must be encodeURIComponent'ed by the caller. */
|
|
54
|
+
export function createApiClient(opts: ApiClientOptions): ApiClient {
|
|
55
|
+
const doFetch = opts.fetchImpl ?? fetch;
|
|
56
|
+
const base = opts.baseUrl.replace(/\/+$/, '');
|
|
57
|
+
|
|
58
|
+
async function request(path: string, init: RequestInit = {}): Promise<Response> {
|
|
59
|
+
const headers = new Headers(init.headers);
|
|
60
|
+
const token = opts.token();
|
|
61
|
+
if (token) headers.set('Authorization', `Bearer ${token}`);
|
|
62
|
+
if (!headers.has('Accept')) headers.set('Accept', 'application/json');
|
|
63
|
+
const response = await doFetch(base + (path.startsWith('/') ? path : '/' + path), { ...init, headers });
|
|
64
|
+
if (!response.ok) {
|
|
65
|
+
await opts.onError?.(response);
|
|
66
|
+
throw await errorFromResponse(response);
|
|
67
|
+
}
|
|
68
|
+
return response;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function json<T>(path: string, init: RequestInit): Promise<T> {
|
|
72
|
+
const response = await request(path, init);
|
|
73
|
+
if (response.status === 204) return undefined as T;
|
|
74
|
+
const text = await response.text();
|
|
75
|
+
return (text ? JSON.parse(text) : undefined) as T;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const withBody = (method: string) => <T>(path: string, body?: unknown, init: RequestInit = {}) => {
|
|
79
|
+
const headers = new Headers(init.headers);
|
|
80
|
+
if (body !== undefined && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json');
|
|
81
|
+
return json<T>(path, { ...init, method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
return {
|
|
85
|
+
get: <T>(path: string, init: RequestInit = {}) => json<T>(path, { ...init, method: 'GET' }),
|
|
86
|
+
post: withBody('POST'),
|
|
87
|
+
patch: withBody('PATCH'),
|
|
88
|
+
put: withBody('PUT'),
|
|
89
|
+
delete: <T>(path: string, init: RequestInit = {}) => json<T>(path, { ...init, method: 'DELETE' }),
|
|
90
|
+
request,
|
|
91
|
+
};
|
|
92
|
+
}
|
package/src/sdk/html.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Escaping for markup built as strings. Prefer DOM nodes with textContent;
|
|
2
|
+
// when a template literal goes into innerHTML, every interpolated value that
|
|
3
|
+
// came from a server, a wallet or a person goes through esc() -- attribute
|
|
4
|
+
// values included. Shared by the escrow portal (its FRONTEND-PROCESS F11) and
|
|
5
|
+
// the operator console (daml-escrow PLAN.md Phase 104).
|
|
6
|
+
|
|
7
|
+
const ENTITIES: Record<string, string> = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
|
8
|
+
|
|
9
|
+
/** v as text safe inside markup and quoted attribute values. */
|
|
10
|
+
export function esc(v: unknown): string {
|
|
11
|
+
return String(v ?? '').replace(/[&<>"']/g, (c) => ENTITIES[c]);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** html, markup built with esc(), as nodes: for a slot that takes a string
|
|
15
|
+
* only as text, such as a pending-approvals item's `what`. */
|
|
16
|
+
export function fragment(html: string): DocumentFragment {
|
|
17
|
+
const tpl = document.createElement('template');
|
|
18
|
+
tpl.innerHTML = html;
|
|
19
|
+
return tpl.content;
|
|
20
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// OpenID Connect sign-in for a browser app: Authorization Code + PKCE
|
|
2
|
+
// (RFC 7636) with state (RFC 6749 §10.12), against Okta or the dev issuer
|
|
3
|
+
// (daml-escrow-commons devoidc). No client secret: the code_verifier never
|
|
4
|
+
// leaves the browser, only its S256 hash goes in the authorize redirect.
|
|
5
|
+
//
|
|
6
|
+
// Shared by the escrow portal and the operator console (daml-escrow PLAN.md
|
|
7
|
+
// Phase 104). What each app keeps for itself -- which scopes to ask for, its
|
|
8
|
+
// session store, roles, signing sessions -- stays in the app.
|
|
9
|
+
//
|
|
10
|
+
// const url = await startAuthorization({ issuer, clientId, scope, redirectUri });
|
|
11
|
+
// window.location.href = url;
|
|
12
|
+
// // …on /callback:
|
|
13
|
+
// if (!validateState(params.get('state'))) throw …;
|
|
14
|
+
// const { accessToken, expiresIn } = await exchangeCode(params.get('code')!, { redirectUri });
|
|
15
|
+
//
|
|
16
|
+
// Display only: tokenScopes and tokenExpirySeconds read a token without
|
|
17
|
+
// verifying it. Servers enforce from the verified token, never from these.
|
|
18
|
+
|
|
19
|
+
// sessionStorage keys, unchanged from the escrow portal so a sign-in already
|
|
20
|
+
// under way when an app moves onto this module still completes.
|
|
21
|
+
export const PKCE_KEYS = {
|
|
22
|
+
verifier: 'pkce_code_verifier',
|
|
23
|
+
state: 'pkce_state',
|
|
24
|
+
issuer: 'pkce_issuer',
|
|
25
|
+
clientId: 'pkce_client_id',
|
|
26
|
+
} as const;
|
|
27
|
+
|
|
28
|
+
export interface AuthorizationRequest {
|
|
29
|
+
/** The issuer's base URL (Okta authorization server, or dev-oidc). */
|
|
30
|
+
issuer: string;
|
|
31
|
+
clientId: string;
|
|
32
|
+
/** Space-separated scopes. */
|
|
33
|
+
scope: string;
|
|
34
|
+
/** Where the issuer returns the code; registered with the client. */
|
|
35
|
+
redirectUri: string;
|
|
36
|
+
/** More authorize parameters: login_hint, idp, acr_values, max_age… */
|
|
37
|
+
extra?: Record<string, string>;
|
|
38
|
+
/** Okta's path; override for another issuer. */
|
|
39
|
+
authorizePath?: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Base64url without padding. */
|
|
43
|
+
export function base64UrlEncode(bytes: Uint8Array): string {
|
|
44
|
+
let binary = '';
|
|
45
|
+
for (const b of bytes) binary += String.fromCharCode(b);
|
|
46
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A fresh PKCE code_verifier (32 random bytes, base64url). */
|
|
50
|
+
export function generateCodeVerifier(): string {
|
|
51
|
+
const bytes = new Uint8Array(32);
|
|
52
|
+
crypto.getRandomValues(bytes);
|
|
53
|
+
return base64UrlEncode(bytes);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The S256 code_challenge for verifier. */
|
|
57
|
+
export async function codeChallenge(verifier: string): Promise<string> {
|
|
58
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
|
|
59
|
+
return base64UrlEncode(new Uint8Array(digest));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Prepares a sign-in: stores a new verifier, state, issuer and client in
|
|
64
|
+
* sessionStorage and returns the issuer's authorize URL to send the browser
|
|
65
|
+
* to. The caller navigates (so it can stash its own state first).
|
|
66
|
+
*/
|
|
67
|
+
export async function startAuthorization(req: AuthorizationRequest): Promise<string> {
|
|
68
|
+
const verifier = generateCodeVerifier();
|
|
69
|
+
const challenge = await codeChallenge(verifier);
|
|
70
|
+
const state = crypto.randomUUID();
|
|
71
|
+
sessionStorage.setItem(PKCE_KEYS.verifier, verifier);
|
|
72
|
+
sessionStorage.setItem(PKCE_KEYS.state, state);
|
|
73
|
+
sessionStorage.setItem(PKCE_KEYS.issuer, req.issuer);
|
|
74
|
+
sessionStorage.setItem(PKCE_KEYS.clientId, req.clientId);
|
|
75
|
+
const params = new URLSearchParams({
|
|
76
|
+
client_id: req.clientId,
|
|
77
|
+
response_type: 'code',
|
|
78
|
+
scope: req.scope,
|
|
79
|
+
redirect_uri: req.redirectUri,
|
|
80
|
+
state,
|
|
81
|
+
code_challenge: challenge,
|
|
82
|
+
code_challenge_method: 'S256',
|
|
83
|
+
...(req.extra ?? {}),
|
|
84
|
+
});
|
|
85
|
+
return `${req.issuer}${req.authorizePath ?? '/v1/authorize'}?${params.toString()}`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Checks the callback's state against the one stored at sign-in. One use:
|
|
90
|
+
* the stored state is removed whether it matches or not. Call it, and stop
|
|
91
|
+
* unless it returns true, before exchanging the code.
|
|
92
|
+
*/
|
|
93
|
+
export function validateState(returned: string | null): boolean {
|
|
94
|
+
const expected = sessionStorage.getItem(PKCE_KEYS.state);
|
|
95
|
+
sessionStorage.removeItem(PKCE_KEYS.state);
|
|
96
|
+
return !!expected && !!returned && expected === returned;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface TokenResponse {
|
|
100
|
+
accessToken: string;
|
|
101
|
+
/** Seconds; defaultExpiresIn when the issuer didn't say. */
|
|
102
|
+
expiresIn: number;
|
|
103
|
+
/** Granted scopes, when the issuer says. */
|
|
104
|
+
scope?: string;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export interface ExchangeOptions {
|
|
108
|
+
/** The same redirect_uri the authorization used. */
|
|
109
|
+
redirectUri: string;
|
|
110
|
+
tokenPath?: string;
|
|
111
|
+
defaultExpiresIn?: number;
|
|
112
|
+
fetchImpl?: typeof fetch;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Trades the authorization code and the stored verifier for an access token
|
|
117
|
+
* at the issuer's token endpoint. The stored verifier, issuer and client are
|
|
118
|
+
* removed first: a code is tried once.
|
|
119
|
+
*/
|
|
120
|
+
export async function exchangeCode(code: string, opts: ExchangeOptions): Promise<TokenResponse> {
|
|
121
|
+
const verifier = sessionStorage.getItem(PKCE_KEYS.verifier);
|
|
122
|
+
const issuer = sessionStorage.getItem(PKCE_KEYS.issuer);
|
|
123
|
+
const clientId = sessionStorage.getItem(PKCE_KEYS.clientId);
|
|
124
|
+
sessionStorage.removeItem(PKCE_KEYS.verifier);
|
|
125
|
+
sessionStorage.removeItem(PKCE_KEYS.issuer);
|
|
126
|
+
sessionStorage.removeItem(PKCE_KEYS.clientId);
|
|
127
|
+
if (!verifier || !issuer || !clientId) {
|
|
128
|
+
throw new Error('Missing PKCE state: sign in again');
|
|
129
|
+
}
|
|
130
|
+
const response = await (opts.fetchImpl ?? fetch)(`${issuer}${opts.tokenPath ?? '/v1/token'}`, {
|
|
131
|
+
method: 'POST',
|
|
132
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
133
|
+
body: new URLSearchParams({
|
|
134
|
+
grant_type: 'authorization_code',
|
|
135
|
+
code,
|
|
136
|
+
redirect_uri: opts.redirectUri,
|
|
137
|
+
client_id: clientId,
|
|
138
|
+
code_verifier: verifier,
|
|
139
|
+
}),
|
|
140
|
+
});
|
|
141
|
+
if (!response.ok) {
|
|
142
|
+
throw new Error('Token exchange failed');
|
|
143
|
+
}
|
|
144
|
+
const data = await response.json();
|
|
145
|
+
return {
|
|
146
|
+
accessToken: data.access_token,
|
|
147
|
+
expiresIn: Number(data.expires_in) || (opts.defaultExpiresIn ?? 600),
|
|
148
|
+
scope: typeof data.scope === 'string' ? data.scope : undefined,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** A JWT's payload, unverified; undefined when it isn't one. */
|
|
153
|
+
export function tokenClaims(token: string | null | undefined): Record<string, unknown> | undefined {
|
|
154
|
+
try {
|
|
155
|
+
const part = (token ?? '').split('.')[1];
|
|
156
|
+
if (!part) return undefined;
|
|
157
|
+
const json = atob(part.replace(/-/g, '+').replace(/_/g, '/'));
|
|
158
|
+
const claims = JSON.parse(json);
|
|
159
|
+
return claims && typeof claims === 'object' ? claims : undefined;
|
|
160
|
+
} catch {
|
|
161
|
+
return undefined;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** A token's scopes (Okta's `scp` array, or a `scope` string). Display only. */
|
|
166
|
+
export function tokenScopes(token: string | null | undefined): string[] {
|
|
167
|
+
const claims = tokenClaims(token);
|
|
168
|
+
const scp = claims?.scp ?? claims?.scope;
|
|
169
|
+
if (Array.isArray(scp)) return scp.filter((s: unknown): s is string => typeof s === 'string');
|
|
170
|
+
if (typeof scp === 'string') return scp.split(/\s+/).filter(Boolean);
|
|
171
|
+
return [];
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Seconds until the token's exp (0 once past), or undefined without one. */
|
|
175
|
+
export function tokenExpirySeconds(token: string | null | undefined, now = Date.now()): number | undefined {
|
|
176
|
+
const exp = tokenClaims(token)?.exp;
|
|
177
|
+
return typeof exp === 'number' ? Math.max(0, Math.floor(exp - now / 1000)) : undefined;
|
|
178
|
+
}
|