@karni/ui 0.0.0-stage → 0.3.1

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.
Files changed (96) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +288 -2
  3. package/dist/index.cjs +9 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.js +4764 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/manifest.json +85 -0
  8. package/dist/mockServiceWorker.js +361 -0
  9. package/dist/src/auth/AuthGuard.d.ts +12 -0
  10. package/dist/src/auth/LoginForm.d.ts +29 -0
  11. package/dist/src/auth/engine.d.ts +99 -0
  12. package/dist/src/auth/provider.d.ts +43 -0
  13. package/dist/src/auth/storage.d.ts +26 -0
  14. package/dist/src/auth/types.d.ts +32 -0
  15. package/dist/src/auth/usePermission.d.ts +7 -0
  16. package/dist/src/components/brand/karni-mark.d.ts +21 -0
  17. package/dist/src/components/brand/mark-paths.d.ts +8 -0
  18. package/dist/src/components/chart/data-chart.d.ts +74 -0
  19. package/dist/src/components/empty-state/empty-state.d.ts +20 -0
  20. package/dist/src/components/file-upload/FileUpload.d.ts +44 -0
  21. package/dist/src/components/layout/layout.d.ts +55 -0
  22. package/dist/src/components/modal/modal.d.ts +45 -0
  23. package/dist/src/components/page/page.d.ts +29 -0
  24. package/dist/src/components/primitives/button.d.ts +44 -0
  25. package/dist/src/components/primitives/checkbox.d.ts +5 -0
  26. package/dist/src/components/primitives/dropdown-menu.d.ts +24 -0
  27. package/dist/src/components/primitives/icons.d.ts +11 -0
  28. package/dist/src/components/primitives/input.d.ts +4 -0
  29. package/dist/src/components/primitives/label.d.ts +5 -0
  30. package/dist/src/components/primitives/select.d.ts +63 -0
  31. package/dist/src/components/primitives/skeleton.d.ts +4 -0
  32. package/dist/src/components/primitives/switch.d.ts +5 -0
  33. package/dist/src/components/primitives/tabs.d.ts +10 -0
  34. package/dist/src/components/primitives/textarea.d.ts +4 -0
  35. package/dist/src/components/resource/ResourceDetail.d.ts +7 -0
  36. package/dist/src/components/resource/ResourceForm.d.ts +7 -0
  37. package/dist/src/components/resource/ResourceSelect.d.ts +7 -0
  38. package/dist/src/components/resource/ResourceTable.d.ts +11 -0
  39. package/dist/src/components/resource/audit-fields.d.ts +17 -0
  40. package/dist/src/components/resource/detail/ResourceDetail.d.ts +30 -0
  41. package/dist/src/components/resource/displayLabel.d.ts +12 -0
  42. package/dist/src/components/resource/form/ResourceForm.d.ts +50 -0
  43. package/dist/src/components/resource/form/field-inputs.d.ts +20 -0
  44. package/dist/src/components/resource/form/fixtures.d.ts +24 -0
  45. package/dist/src/components/resource/form/prepare.d.ts +54 -0
  46. package/dist/src/components/resource/history/ChangeHistory.d.ts +18 -0
  47. package/dist/src/components/resource/import/ResourceImport.d.ts +18 -0
  48. package/dist/src/components/resource/select/ResourceSelect.d.ts +36 -0
  49. package/dist/src/components/resource/select/use-debounced-value.d.ts +2 -0
  50. package/dist/src/components/resource/table/BulkActionsBar.d.ts +20 -0
  51. package/dist/src/components/resource/table/ExportButtons.d.ts +17 -0
  52. package/dist/src/components/resource/table/FilterBar.d.ts +29 -0
  53. package/dist/src/components/resource/table/PaginationControls.d.ts +19 -0
  54. package/dist/src/components/resource/table/ResourceTable.d.ts +72 -0
  55. package/dist/src/components/resource/table/demo-fixtures.d.ts +25 -0
  56. package/dist/src/components/resource/table/derive-columns.d.ts +33 -0
  57. package/dist/src/components/resource/table/table-utils.d.ts +24 -0
  58. package/dist/src/components/resource/table/use-debounced-value.d.ts +1 -0
  59. package/dist/src/components/stat/stat.d.ts +24 -0
  60. package/dist/src/components/toast/toast-store.d.ts +36 -0
  61. package/dist/src/components/toast/toaster.d.ts +33 -0
  62. package/dist/src/components/toast/use-toast.d.ts +24 -0
  63. package/dist/src/hooks/keys.d.ts +24 -0
  64. package/dist/src/hooks/multipart.d.ts +44 -0
  65. package/dist/src/hooks/params.d.ts +25 -0
  66. package/dist/src/hooks/types.d.ts +41 -0
  67. package/dist/src/hooks/useChangeHistory.d.ts +29 -0
  68. package/dist/src/hooks/useResourceImport.d.ts +107 -0
  69. package/dist/src/hooks/useResourceItem.d.ts +4 -0
  70. package/dist/src/hooks/useResourceList.d.ts +4 -0
  71. package/dist/src/hooks/useResourceMutations.d.ts +13 -0
  72. package/dist/src/index.d.ts +95 -0
  73. package/dist/src/lib/cn.d.ts +8 -0
  74. package/dist/src/lib/roles.d.ts +45 -0
  75. package/dist/src/lib/variants.d.ts +33 -0
  76. package/dist/src/schema/client.d.ts +90 -0
  77. package/dist/src/schema/parse.d.ts +101 -0
  78. package/dist/src/schema/provider.d.ts +13 -0
  79. package/dist/src/schema/types.d.ts +84 -0
  80. package/dist/src/schema/useSchema.d.ts +17 -0
  81. package/dist/src/schema/zod.d.ts +4 -0
  82. package/dist/styles.css +87 -0
  83. package/dist/tailwind-preset.cjs +2 -0
  84. package/dist/tailwind-preset.cjs.map +1 -0
  85. package/dist/tailwind-preset.d.ts +58 -0
  86. package/dist/tailwind-preset.js +64 -0
  87. package/dist/tailwind-preset.js.map +1 -0
  88. package/eslint-plugin/index.js +72 -0
  89. package/eslint-plugin/lib/docs.js +11 -0
  90. package/eslint-plugin/lib/glob.js +51 -0
  91. package/eslint-plugin/rules/max-page-lines.js +65 -0
  92. package/eslint-plugin/rules/no-deep-imports.js +61 -0
  93. package/eslint-plugin/rules/no-direct-http.js +128 -0
  94. package/eslint-plugin/rules/no-raw-elements.js +65 -0
  95. package/eslint-plugin/rules.json +26 -0
  96. package/package.json +153 -4
@@ -0,0 +1,85 @@
1
+ {
2
+ "components": [
3
+ "AuthGuard",
4
+ "AuthProvider",
5
+ "Button",
6
+ "ChangeHistory",
7
+ "Checkbox",
8
+ "DataChart",
9
+ "DropdownMenu",
10
+ "DropdownMenuCheckboxItem",
11
+ "DropdownMenuContent",
12
+ "DropdownMenuGroup",
13
+ "DropdownMenuItem",
14
+ "DropdownMenuLabel",
15
+ "DropdownMenuPortal",
16
+ "DropdownMenuSeparator",
17
+ "DropdownMenuTrigger",
18
+ "EmptyState",
19
+ "FileUpload",
20
+ "Input",
21
+ "KarniMark",
22
+ "KarniProvider",
23
+ "Label",
24
+ "Layout",
25
+ "LoginForm",
26
+ "Modal",
27
+ "ModalClose",
28
+ "Page",
29
+ "ResourceDetail",
30
+ "ResourceForm",
31
+ "ResourceImport",
32
+ "ResourceSelect",
33
+ "ResourceTable",
34
+ "Select",
35
+ "SelectContent",
36
+ "SelectGroup",
37
+ "SelectItem",
38
+ "SelectLabel",
39
+ "SelectRoot",
40
+ "SelectSeparator",
41
+ "SelectTrigger",
42
+ "SelectValue",
43
+ "Skeleton",
44
+ "Stat",
45
+ "Switch",
46
+ "Tabs",
47
+ "TabsContent",
48
+ "TabsList",
49
+ "TabsTrigger",
50
+ "Textarea",
51
+ "Toaster"
52
+ ],
53
+ "hooks": [
54
+ "useAuth",
55
+ "useChangeHistory",
56
+ "useImportActions",
57
+ "useImportDescribe",
58
+ "useImportJob",
59
+ "useKarniClient",
60
+ "usePermission",
61
+ "useResourceItem",
62
+ "useResourceList",
63
+ "useResourceMutations",
64
+ "useSchema",
65
+ "useToast"
66
+ ],
67
+ "roles": {
68
+ "async-select": "ResourceSelect",
69
+ "auth-guard": "AuthGuard",
70
+ "change-history": "ChangeHistory",
71
+ "chart": "DataChart",
72
+ "data-table": "ResourceTable",
73
+ "detail-view": "ResourceDetail",
74
+ "empty-state": "EmptyState",
75
+ "file-upload": "FileUpload",
76
+ "layout-shell": "Layout",
77
+ "login-form": "LoginForm",
78
+ "modal": "Modal",
79
+ "page-shell": "Page",
80
+ "resource-form": "ResourceForm",
81
+ "resource-import": "ResourceImport",
82
+ "stat": "Stat",
83
+ "toast": "Toaster"
84
+ }
85
+ }
@@ -0,0 +1,361 @@
1
+ /* eslint-disable */
2
+ /* tslint:disable */
3
+
4
+ /**
5
+ * Mock Service Worker.
6
+ * @see https://github.com/mswjs/msw
7
+ * - Please do NOT modify this file.
8
+ */
9
+
10
+ const PACKAGE_VERSION = '2.15.0'
11
+ const INTEGRITY_CHECKSUM = '03cb67ac84128e63d7cd722a6e5b7f1e'
12
+ const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
13
+ const activeClientIds = new Set()
14
+
15
+ addEventListener('install', function () {
16
+ self.skipWaiting()
17
+ })
18
+
19
+ addEventListener('activate', function (event) {
20
+ event.waitUntil(self.clients.claim())
21
+ })
22
+
23
+ addEventListener('message', async function (event) {
24
+ const clientId = Reflect.get(event.source || {}, 'id')
25
+
26
+ if (!clientId || !self.clients) {
27
+ return
28
+ }
29
+
30
+ const client = await self.clients.get(clientId)
31
+
32
+ if (!client) {
33
+ return
34
+ }
35
+
36
+ const allClients = await self.clients.matchAll({
37
+ type: 'window',
38
+ })
39
+
40
+ switch (event.data) {
41
+ case 'KEEPALIVE_REQUEST': {
42
+ sendToClient(client, {
43
+ type: 'KEEPALIVE_RESPONSE',
44
+ })
45
+ break
46
+ }
47
+
48
+ case 'INTEGRITY_CHECK_REQUEST': {
49
+ sendToClient(client, {
50
+ type: 'INTEGRITY_CHECK_RESPONSE',
51
+ payload: {
52
+ packageVersion: PACKAGE_VERSION,
53
+ checksum: INTEGRITY_CHECKSUM,
54
+ },
55
+ })
56
+ break
57
+ }
58
+
59
+ case 'MOCK_ACTIVATE': {
60
+ activeClientIds.add(clientId)
61
+
62
+ sendToClient(client, {
63
+ type: 'MOCKING_ENABLED',
64
+ payload: {
65
+ client: {
66
+ id: client.id,
67
+ frameType: client.frameType,
68
+ },
69
+ },
70
+ })
71
+ break
72
+ }
73
+
74
+ case 'CLIENT_CLOSED': {
75
+ activeClientIds.delete(clientId)
76
+
77
+ const remainingClients = allClients.filter((client) => {
78
+ return client.id !== clientId
79
+ })
80
+
81
+ // Unregister itself when there are no more clients
82
+ if (remainingClients.length === 0) {
83
+ self.registration.unregister()
84
+ }
85
+
86
+ break
87
+ }
88
+ }
89
+ })
90
+
91
+ addEventListener('fetch', function (event) {
92
+ const requestInterceptedAt = Date.now()
93
+
94
+ // Bypass navigation requests.
95
+ if (event.request.mode === 'navigate') {
96
+ return
97
+ }
98
+
99
+ // Opening the DevTools triggers the "only-if-cached" request
100
+ // that cannot be handled by the worker. Bypass such requests.
101
+ if (
102
+ event.request.cache === 'only-if-cached' &&
103
+ event.request.mode !== 'same-origin'
104
+ ) {
105
+ return
106
+ }
107
+
108
+ // Bypass all requests when there are no active clients.
109
+ // Prevents the self-unregistered worked from handling requests
110
+ // after it's been terminated (still remains active until the next reload).
111
+ if (activeClientIds.size === 0) {
112
+ return
113
+ }
114
+
115
+ const requestId = crypto.randomUUID()
116
+ event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
117
+ })
118
+
119
+ /**
120
+ * @param {FetchEvent} event
121
+ * @param {string} requestId
122
+ * @param {number} requestInterceptedAt
123
+ */
124
+ async function handleRequest(event, requestId, requestInterceptedAt) {
125
+ const client = await resolveMainClient(event)
126
+ const requestCloneForEvents = event.request.clone()
127
+ const response = await getResponse(
128
+ event,
129
+ client,
130
+ requestId,
131
+ requestInterceptedAt,
132
+ )
133
+
134
+ // Send back the response clone for the "response:*" life-cycle events.
135
+ // Ensure MSW is active and ready to handle the message, otherwise
136
+ // this message will pend indefinitely.
137
+ if (client && activeClientIds.has(client.id)) {
138
+ const serializedRequest = await serializeRequest(requestCloneForEvents)
139
+
140
+ // Omit the body of server-sent event stream responses.
141
+ // Cloning such responses would prevent client-side stream cancelations
142
+ // from reaching the original stream (a teed stream only cancels its
143
+ // source once both of its branches cancel) and would buffer the
144
+ // entire stream into the unconsumed clone indefinitely.
145
+ const isEventStreamResponse = response.headers
146
+ .get('content-type')
147
+ ?.toLowerCase()
148
+ .startsWith('text/event-stream')
149
+
150
+ // Clone the response so both the client and the library could consume it.
151
+ const responseClone = isEventStreamResponse ? null : response.clone()
152
+
153
+ sendToClient(
154
+ client,
155
+ {
156
+ type: 'RESPONSE',
157
+ payload: {
158
+ isMockedResponse: IS_MOCKED_RESPONSE in response,
159
+ request: {
160
+ id: requestId,
161
+ ...serializedRequest,
162
+ },
163
+ response: {
164
+ type: response.type,
165
+ status: response.status,
166
+ statusText: response.statusText,
167
+ headers: Object.fromEntries(response.headers.entries()),
168
+ body: responseClone ? responseClone.body : null,
169
+ },
170
+ },
171
+ },
172
+ responseClone && responseClone.body
173
+ ? [serializedRequest.body, responseClone.body]
174
+ : [],
175
+ )
176
+ }
177
+
178
+ return response
179
+ }
180
+
181
+ /**
182
+ * Resolve the main client for the given event.
183
+ * Client that issues a request doesn't necessarily equal the client
184
+ * that registered the worker. It's with the latter the worker should
185
+ * communicate with during the response resolving phase.
186
+ * @param {FetchEvent} event
187
+ * @returns {Promise<Client | undefined>}
188
+ */
189
+ async function resolveMainClient(event) {
190
+ const client = await self.clients.get(event.clientId)
191
+
192
+ if (activeClientIds.has(event.clientId)) {
193
+ return client
194
+ }
195
+
196
+ if (client?.frameType === 'top-level') {
197
+ return client
198
+ }
199
+
200
+ const allClients = await self.clients.matchAll({
201
+ type: 'window',
202
+ })
203
+
204
+ return allClients
205
+ .filter((client) => {
206
+ // Get only those clients that are currently visible.
207
+ return client.visibilityState === 'visible'
208
+ })
209
+ .find((client) => {
210
+ // Find the client ID that's recorded in the
211
+ // set of clients that have registered the worker.
212
+ return activeClientIds.has(client.id)
213
+ })
214
+ }
215
+
216
+ /**
217
+ * @param {FetchEvent} event
218
+ * @param {Client | undefined} client
219
+ * @param {string} requestId
220
+ * @param {number} requestInterceptedAt
221
+ * @returns {Promise<Response>}
222
+ */
223
+ async function getResponse(event, client, requestId, requestInterceptedAt) {
224
+ // Clone the request because it might've been already used
225
+ // (i.e. its body has been read and sent to the client).
226
+ const requestClone = event.request.clone()
227
+
228
+ function passthrough() {
229
+ // Cast the request headers to a new Headers instance
230
+ // so the headers can be manipulated with.
231
+ const headers = new Headers(requestClone.headers)
232
+
233
+ // Remove the "accept" header value that marked this request as passthrough.
234
+ // This prevents request alteration and also keeps it compliant with the
235
+ // user-defined CORS policies.
236
+ const acceptHeader = headers.get('accept')
237
+ if (acceptHeader) {
238
+ const values = acceptHeader.split(',').map((value) => value.trim())
239
+ const filteredValues = values.filter(
240
+ (value) => value !== 'msw/passthrough',
241
+ )
242
+
243
+ if (filteredValues.length > 0) {
244
+ headers.set('accept', filteredValues.join(', '))
245
+ } else {
246
+ headers.delete('accept')
247
+ }
248
+ }
249
+
250
+ return fetch(requestClone, { headers })
251
+ }
252
+
253
+ // Bypass mocking when the client is not active.
254
+ if (!client) {
255
+ return passthrough()
256
+ }
257
+
258
+ // Bypass initial page load requests (i.e. static assets).
259
+ // The absence of the immediate/parent client in the map of the active clients
260
+ // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
261
+ // and is not ready to handle requests.
262
+ if (!activeClientIds.has(client.id)) {
263
+ return passthrough()
264
+ }
265
+
266
+ // Notify the client that a request has been intercepted.
267
+ const serializedRequest = await serializeRequest(event.request)
268
+ const clientMessage = await sendToClient(
269
+ client,
270
+ {
271
+ type: 'REQUEST',
272
+ payload: {
273
+ id: requestId,
274
+ interceptedAt: requestInterceptedAt,
275
+ ...serializedRequest,
276
+ },
277
+ },
278
+ [serializedRequest.body],
279
+ )
280
+
281
+ switch (clientMessage.type) {
282
+ case 'MOCK_RESPONSE': {
283
+ return respondWithMock(clientMessage.data)
284
+ }
285
+
286
+ case 'PASSTHROUGH': {
287
+ return passthrough()
288
+ }
289
+ }
290
+
291
+ return passthrough()
292
+ }
293
+
294
+ /**
295
+ * @param {Client} client
296
+ * @param {any} message
297
+ * @param {Array<Transferable>} transferrables
298
+ * @returns {Promise<any>}
299
+ */
300
+ function sendToClient(client, message, transferrables = []) {
301
+ return new Promise((resolve, reject) => {
302
+ const channel = new MessageChannel()
303
+
304
+ channel.port1.onmessage = (event) => {
305
+ if (event.data && event.data.error) {
306
+ return reject(event.data.error)
307
+ }
308
+
309
+ resolve(event.data)
310
+ }
311
+
312
+ client.postMessage(message, [
313
+ channel.port2,
314
+ ...transferrables.filter(Boolean),
315
+ ])
316
+ })
317
+ }
318
+
319
+ /**
320
+ * @param {Response} response
321
+ * @returns {Response}
322
+ */
323
+ function respondWithMock(response) {
324
+ // Setting response status code to 0 is a no-op.
325
+ // However, when responding with a "Response.error()", the produced Response
326
+ // instance will have status code set to 0. Since it's not possible to create
327
+ // a Response instance with status code 0, handle that use-case separately.
328
+ if (response.status === 0) {
329
+ return Response.error()
330
+ }
331
+
332
+ const mockedResponse = new Response(response.body, response)
333
+
334
+ Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
335
+ value: true,
336
+ enumerable: true,
337
+ })
338
+
339
+ return mockedResponse
340
+ }
341
+
342
+ /**
343
+ * @param {Request} request
344
+ */
345
+ async function serializeRequest(request) {
346
+ return {
347
+ url: request.url,
348
+ mode: request.mode,
349
+ method: request.method,
350
+ headers: Object.fromEntries(request.headers.entries()),
351
+ cache: request.cache,
352
+ credentials: request.credentials,
353
+ destination: request.destination,
354
+ integrity: request.integrity,
355
+ redirect: request.redirect,
356
+ referrer: request.referrer,
357
+ referrerPolicy: request.referrerPolicy,
358
+ body: await request.arrayBuffer(),
359
+ keepalive: request.keepalive,
360
+ }
361
+ }
@@ -0,0 +1,12 @@
1
+ import { ReactElement, ReactNode } from 'react';
2
+ export interface AuthGuardProps {
3
+ /** Grant access when the user holds AT LEAST ONE of these role names. */
4
+ roles?: string[];
5
+ /** Rendered for anonymous users and role mismatches; default nothing. */
6
+ fallback?: ReactNode;
7
+ /** Rendered while the auth status is still "loading"; default nothing. */
8
+ loading?: ReactNode;
9
+ children?: ReactNode;
10
+ }
11
+ /** Renders its children only for a signed-in user, optionally with one of the given roles; otherwise its `fallback`. */
12
+ export declare function AuthGuard({ roles, fallback, loading, children, }: AuthGuardProps): ReactElement | null;
@@ -0,0 +1,29 @@
1
+ import { KarniUser } from './types';
2
+ /**
3
+ * LoginForm — the sign-in form every app needs (contract: auth).
4
+ *
5
+ * Email + password against `useAuth().login`, with the error inline. On
6
+ * success it calls `onSuccess(user)` (navigate there). When the backend's
7
+ * 2FA gate fires, `on2FA` receives the ephemeral token so the app can render
8
+ * its code step (`POST <authBasePath>/2fa/login/`); without a handler the
9
+ * form explains that a code is required. Render it inside `AuthProvider`,
10
+ * e.g. as `AuthGuard`'s `fallback`.
11
+ */
12
+ import * as React from "react";
13
+ export interface LoginFormProps {
14
+ /** Called with the signed-in user; navigate from here. */
15
+ onSuccess?: (user: KarniUser) => void;
16
+ /** Called when the account needs a second factor (the token completes it). */
17
+ on2FA?: (ephemeralToken: string) => void;
18
+ /** Heading above the fields; `null` renders none. Default "Sign in". */
19
+ title?: React.ReactNode;
20
+ /** Text under the heading (demo logins, a signup link, ...). */
21
+ description?: React.ReactNode;
22
+ /** The submit button's label. Default "Sign in". */
23
+ submitLabel?: React.ReactNode;
24
+ /** Shown while the auth status is "loading" is irrelevant here; this disables the form. */
25
+ disabled?: boolean;
26
+ className?: string;
27
+ }
28
+ /** Email and password sign-in form with inline errors and a callback for the two-factor step. */
29
+ export declare function LoginForm({ onSuccess, on2FA, title, description, submitLabel, disabled, className, }: LoginFormProps): React.JSX.Element;
@@ -0,0 +1,99 @@
1
+ import { KarniClient } from '../schema/client';
2
+ import { TokenStorage } from './storage';
3
+ import { AuthStatus, KarniUser, LoginResult } from './types';
4
+ export type AuthMode = "jwt" | "session";
5
+ export interface AuthEngineOptions {
6
+ client: KarniClient;
7
+ tokenStorage: TokenStorage;
8
+ /** Skips schema-based mode detection entirely when set. */
9
+ modeOverride?: AuthMode;
10
+ /** Session-mode CSRF cookie name (A4 pin). Default "csrftoken". */
11
+ csrfCookieName?: string;
12
+ /** Session-mode CSRF header name (A4 pin). Default "X-CSRFToken". */
13
+ csrfHeaderName?: string;
14
+ /** Path prefix of the auth endpoints, relative to the client's baseUrl. */
15
+ authBasePath?: string;
16
+ /**
17
+ * Reads whatever the schema loader cached under karniKeys.schema() —
18
+ * consulted (shape-guarded) for `authMode` before fetching the document.
19
+ */
20
+ readCachedSchema?: () => unknown;
21
+ }
22
+ export interface AuthSnapshot {
23
+ readonly status: AuthStatus;
24
+ readonly user: KarniUser | null;
25
+ readonly mode: AuthMode | null;
26
+ }
27
+ /**
28
+ * Reads the auth mode out of either a ParsedSchema (`authMode`) or a raw
29
+ * OpenAPI document (root `x-karni-auth-mode`), shape-guarded.
30
+ */
31
+ export declare function readAuthMode(value: unknown): AuthMode | undefined;
32
+ /** Validates/normalizes a `me` payload into a KarniUser (roles default []). */
33
+ export declare function normalizeUser(value: unknown): KarniUser | null;
34
+ export declare class AuthEngine {
35
+ private readonly client;
36
+ private readonly tokenStorage;
37
+ private readonly modeOverride;
38
+ private readonly csrfCookieName;
39
+ private readonly csrfHeaderName;
40
+ private readonly authBasePath;
41
+ private readonly readCachedSchema;
42
+ private mode;
43
+ private accessToken;
44
+ private refreshPromise;
45
+ private initPromise;
46
+ private readonly listeners;
47
+ private state;
48
+ constructor(options: AuthEngineOptions);
49
+ /** Registers the D6 hook points on the client. Idempotent. */
50
+ attach(): void;
51
+ /**
52
+ * Clears every hook this engine registered (including a `getAccessToken`
53
+ * the app passed to createKarniClient — an unmounted AuthProvider leaves
54
+ * the client fully unauthenticated by design).
55
+ */
56
+ detach(): void;
57
+ private csrfHeaders;
58
+ /**
59
+ * The client calls this at most once per 401-ing request (D6). Returning
60
+ * true makes the client retry that request exactly once with
61
+ * freshly-injected credentials; the retry's outcome is always surfaced.
62
+ */
63
+ private handleUnauthorized;
64
+ readonly subscribe: (listener: () => void) => (() => void);
65
+ readonly getSnapshot: () => AuthSnapshot;
66
+ private setState;
67
+ /** Idempotent: the first call kicks off mode resolution + session restore. */
68
+ ensureInitialized(): Promise<void>;
69
+ private initialize;
70
+ private fetchSchemaAuthMode;
71
+ /** Fetches `/me/` and mirrors the result; any failure means anonymous. */
72
+ private syncUser;
73
+ /**
74
+ * Reads the CSRF cookie, bootstrapping it via `GET <authBasePath>/csrf/`
75
+ * when absent (A4). Returns null when the cookie stays unreadable (e.g.
76
+ * CSRF_COOKIE_HTTPONLY) — requests then go out without the header and the
77
+ * backend's 403 surfaces, which is the honest failure mode.
78
+ */
79
+ private ensureCsrfToken;
80
+ /** ONE shared in-flight refresh; resolves true on success. */
81
+ private ensureRefresh;
82
+ private performRefresh;
83
+ login(email: string, password: string): Promise<LoginResult>;
84
+ private fetchMe;
85
+ /** Best-effort server logout, then always clears local state (anonymous). */
86
+ logout(): Promise<void>;
87
+ /**
88
+ * Adopts tokens issued out of band — what `@karni/impersonation-ui` does
89
+ * when a support user starts or stops impersonating (the backend answers
90
+ * with tokens for the other identity). JWT mode only; in session mode the
91
+ * server-side session already changed, so this just re-syncs `/me/`.
92
+ */
93
+ adoptTokens(access: string | null, refresh: string | null): Promise<void>;
94
+ /**
95
+ * Re-syncs the session: rotates the tokens in JWT mode (A3: /refresh/ is
96
+ * 405 in session mode, so session mode only re-fetches /me/).
97
+ */
98
+ refresh(): Promise<void>;
99
+ }
@@ -0,0 +1,43 @@
1
+ import { ReactElement, ReactNode } from 'react';
2
+ import { TokenStorage } from './storage';
3
+ import { AuthStatus, KarniUser, LoginResult } from './types';
4
+ export interface AuthProviderProps {
5
+ /**
6
+ * "jwt" | "session"; when omitted, the mode comes from the schema root's
7
+ * x-karni-auth-mode (D6), falling back to "jwt" when the schema does not
8
+ * declare one.
9
+ */
10
+ mode?: "jwt" | "session";
11
+ /** JWT mode refresh-token storage; default localStorage adapter. */
12
+ tokenStorage?: TokenStorage;
13
+ /** Session mode CSRF cookie name; default "csrftoken" (D6/A4). */
14
+ csrfCookieName?: string;
15
+ /** Session mode CSRF header name; default "X-CSRFToken" (D6/A4). */
16
+ csrfHeaderName?: string;
17
+ /** Path prefix of the auth endpoints relative to baseUrl; default "/auth". */
18
+ authBasePath?: string;
19
+ children?: ReactNode;
20
+ }
21
+ export interface AuthContextValue {
22
+ user: KarniUser | null;
23
+ roles: string[];
24
+ status: AuthStatus;
25
+ login(email: string, password: string): Promise<LoginResult>;
26
+ logout(): Promise<void>;
27
+ refresh(): Promise<void>;
28
+ /**
29
+ * Adopts tokens issued out of band (JWT mode; session mode re-syncs `/me/`),
30
+ * e.g. after starting or stopping an impersonated session.
31
+ */
32
+ adoptTokens(access: string | null, refresh: string | null): Promise<void>;
33
+ }
34
+ /**
35
+ * The React mirror of the auth engine's state. Exported for advanced
36
+ * composition (stories, tests, custom providers); application code should
37
+ * use <AuthProvider> + useAuth().
38
+ */
39
+ export declare const AuthContext: import('react').Context<AuthContextValue | null>;
40
+ /** Holds the signed-in user and attaches credentials (JWT or session) to every request; render it inside `KarniProvider`. */
41
+ export declare function AuthProvider({ mode, tokenStorage, csrfCookieName, csrfHeaderName, authBasePath, children, }: AuthProviderProps): ReactElement;
42
+ /** Returns the signed-in user, auth status, `login` and `logout`; throws a descriptive error outside `AuthProvider`. */
43
+ export declare function useAuth(): AuthContextValue;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Pluggable refresh-token storage for JWT mode (contract "Hooks + auth").
3
+ *
4
+ * The default adapter is `localStorage`: it survives reloads and is the
5
+ * simplest thing that works, but any XSS on your page can read it. Stricter
6
+ * setups use `createMemoryTokenStorage()` (logout on reload) or implement
7
+ * the three-method `TokenStorage` interface themselves (e.g. backed by a
8
+ * worker, or by an HttpOnly-cookie BFF). Session mode needs no storage.
9
+ */
10
+ export interface TokenStorage {
11
+ get(): string | null;
12
+ set(token: string): void;
13
+ clear(): void;
14
+ }
15
+ /**
16
+ * Keeps the refresh token in localStorage; the default storage. `key` defaults to "karni.refreshToken". Every storage
17
+ * access is guarded: when localStorage is unavailable (SSR, private windows,
18
+ * blocked site data) the adapter degrades to a no-op that returns `null`
19
+ * instead of throwing.
20
+ */
21
+ export declare function createLocalStorageTokenStorage(key?: string): TokenStorage;
22
+ /**
23
+ * In-memory adapter: most secure (nothing persisted anywhere), but a page
24
+ * reload logs the user out.
25
+ */
26
+ export declare function createMemoryTokenStorage(): TokenStorage;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Public auth types (contract "Hooks + auth" + D6, accounts contract A15).
3
+ */
4
+ /**
5
+ * Shape of the `/api/auth/me/` response. The accounts contract (A15)
6
+ * guarantees `roles: string[]` on MeSerializer; every other field the
7
+ * backend's user serializer exposes rides along via the index signature.
8
+ */
9
+ export interface KarniUser {
10
+ id: string | number;
11
+ email: string;
12
+ roles: string[];
13
+ [extra: string]: unknown;
14
+ }
15
+ /**
16
+ * "loading" while the initial session restore runs, then "authenticated" or
17
+ * "anonymous". A failed token refresh always lands on "anonymous" (D6).
18
+ */
19
+ export type AuthStatus = "loading" | "authenticated" | "anonymous";
20
+ /**
21
+ * Discriminated login result (D6). When the backend's 2FA gate fires
22
+ * (accounts A6), `login()` resolves `{ requires2fa, ephemeralToken }` —
23
+ * the 2FA UI is out of scope in v0.1, so consumers exchange the ephemeral
24
+ * token themselves via `POST /api/auth/2fa/login/`.
25
+ */
26
+ export type LoginResult = {
27
+ ok: true;
28
+ user: KarniUser;
29
+ } | {
30
+ requires2fa: true;
31
+ ephemeralToken: string;
32
+ };