@devopsplaybook.io/common-web 0.13.0 → 0.14.0-beta.25.5639705

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/CHANGELOG.md CHANGED
@@ -5,6 +5,28 @@ All notable changes to this project are documented here.
5
5
  This project follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)
6
6
  and [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.14.0] - 2026-11-25
9
+
10
+ ### Added
11
+
12
+ - `LoginCodeService`, a client for the cross-device login-with-code protocol of
13
+ `@devopsplaybook.io/common-utils` 2.12.0: typed `capabilities`, `create`,
14
+ `poll`, `preview`, `approve` and `cancel` methods, an injectable HTTP client,
15
+ `AbortSignal` support, a configurable base URL and a typed `LoginCodeError`
16
+ with stable backend codes plus transport and parsing codes.
17
+ - `useLoginCode()`: the device-side state machine with server-clock countdowns,
18
+ recursive polling with exponential backoff, pause/resume on visibility and
19
+ focus, abortable requests, session capture and terminal states.
20
+ - `LoginCodeInput`, `LoginWithCodeCard` and `AuthorizeDeviceCard`: accessible
21
+ code entry, the requesting-device flow and the approver flow with an optional
22
+ password step-up, all localisable through `labels` props.
23
+ - A playground page plus component, service, composable, SSR, accessibility and
24
+ no-Nuxt-import tests.
25
+
26
+ Everything is additive: no existing export, prop or behaviour changed, and no
27
+ dependency was added or upgraded (the service reuses the existing axios
28
+ dependency).
29
+
8
30
  ## [0.13.0] - 2026-11-25
9
31
 
10
32
  ### Added
package/README.md CHANGED
@@ -29,6 +29,9 @@ required. The `playground/` directory demonstrates a consuming app.
29
29
  | `<AlertMessages />` | Accessible live regions displaying messages emitted on `EventBus`, each with a per-message **Dismiss** button. |
30
30
  | `<AppNavigation :links="links" :link-component="NuxtLink" label="Primary" />` | Navigation shell with a named `brand` slot, configurable links (`label`, `to`, optional `icon` and `active`) and an optional accessible `label`. |
31
31
  | `<OfflineBanner message="You are offline." />` | Announces offline status and accepts replacement content through its default slot. |
32
+ | `<LoginCodeInput v-model="code" :error="error" />` | Eight-character code entry: uppercases, strips spaces and hyphens, supports paste and Enter-to-submit, and exposes an accessible name that spells the code. |
33
+ | `<LoginWithCodeCard :service="service" @approved="…" @use-password="…" @cancel="…" />` | Device-side flow: creates the request, shows and counts down the code, polls, and reports the redeemed session. |
34
+ | `<AuthorizeDeviceCard :service="service" @approved="…" @cancel="…" />` | Approver-side flow: previews the requesting device and approves the code, with an optional password step-up. |
32
35
 
33
36
  `AlertMessages` listens for `EventTypes.ALERT_MESSAGE` events. Its payload is
34
37
  `{ text, type?, durationMs? }` with `type` limited to `info`, `success`,
@@ -198,6 +201,178 @@ The session model of each application (validity, absolute cap, renewal
198
201
  mechanism) is documented in the
199
202
  [common-utils auth session policy](https://github.com/devopsplaybook-io/common-utils/blob/main/docs/auth-session-policy.md).
200
203
 
204
+ ## Login with code
205
+
206
+ The layer ships a client for the cross-device "login with a code" protocol of
207
+ `@devopsplaybook.io/common-utils` 2.12.0, documented in
208
+ [`docs/login-with-code.md`](https://github.com/devopsplaybook-io/common-utils/blob/main/docs/login-with-code.md).
209
+ A device without usable credentials creates a short-lived request and shows an
210
+ 8 character code; a device where the user is already signed in previews and
211
+ approves it; the first device redeems the approval for a session. This package
212
+ is the client and UI only: the routes, store and session issuance live in the
213
+ backend, and are disabled there unless `LOGIN_CODE_ENABLED=true`.
214
+
215
+ ### `LoginCodeService`
216
+
217
+ `LoginCodeService` is plain ESM TypeScript with no Nuxt imports and no browser
218
+ globals, so it also runs during SSR.
219
+
220
+ ```ts
221
+ import {
222
+ LoginCodeError,
223
+ LoginCodeService,
224
+ } from "@devopsplaybook.io/common-web/services/LoginCodeService";
225
+
226
+ const service = new LoginCodeService({
227
+ // Optional: defaults to `${Config.SERVER_URL}/users/login-codes`.
228
+ baseUrl: "/api/users/login-codes",
229
+ // Optional: bearer header provider for preview/approve (the approver only).
230
+ getAuthHeader: () => AuthService.getAuthHeader(),
231
+ // Optional: persist the redeemed session (returned by approved polls).
232
+ onSession: (token, user) => AuthService.saveToken(token),
233
+ });
234
+
235
+ const capabilities = await service.capabilities();
236
+ if (capabilities.available) {
237
+ const request = await service.create(); // { requestToken, code, … }
238
+ const poll = await service.poll(request.requestToken); // pending | approved | …
239
+ }
240
+ ```
241
+
242
+ | Method | Request |
243
+ | --- | --- |
244
+ | `capabilities({ signal? })` | `GET <prefix>/capabilities` |
245
+ | `create({ signal? })` | `POST <prefix>/` (the trailing slash is added) |
246
+ | `poll(requestToken, { refreshCode?, signal? })` | `POST <prefix>/poll` |
247
+ | `preview(code, { signal? })` | `POST <prefix>/preview`, authenticated |
248
+ | `approve({ code, password? }, { signal? })` | `POST <prefix>/approve`, authenticated |
249
+ | `cancel(requestToken, { signal? })` | `POST <prefix>/cancel` |
250
+
251
+ Every method accepts an `AbortSignal` and resolves with the parsed response body;
252
+ requests time out after 10 seconds by default (`timeoutMs` option). Failures
253
+ throw `LoginCodeError` with a stable `code`, an optional HTTP `status` and a
254
+ `retryable` flag. The backend codes are `INVALID_CODE`, `ALREADY_USED`,
255
+ `RATE_LIMITED`, `LOGIN_CODE_UNAVAILABLE`, `PASSWORD_REQUIRED`,
256
+ `UNAUTHENTICATED` and `FORBIDDEN`; transport and parsing failures map to
257
+ `NETWORK`, `TIMEOUT`, `ABORTED`, `HTTP_ERROR`, `INVALID_RESPONSE` or `FAILED`.
258
+ Messages are fixed and never include a code, a request token or a response body,
259
+ so they are safe to log. `getAuthHeader` may return a header map or `{ headers }`
260
+ and may be async; if it throws, the call fails with `UNAUTHENTICATED` rather than
261
+ sending an unauthenticated approval. A rejected `onSession` does not turn a
262
+ successful redemption into an error.
263
+
264
+ ### `useLoginCode()`
265
+
266
+ `useLoginCode({ service?, onSession? })` owns the device-side state machine and
267
+ is safe during SSR (it touches browser APIs only in `onMounted`). It exposes:
268
+
269
+ - `status`: `idle`, `creating`, `waiting`, `approved`, `expired`, `cancelled` or
270
+ `error`; `code`, `formattedCode` (grouped as `BCDF-GHJK`), `error`,
271
+ `capabilities`, `enabled`, `available`, `session` and `user`;
272
+ - `secondsUntilRefresh` and `secondsUntilExpiry`, countdowns computed against the
273
+ server clock (the offset is derived from each response's `serverTime`, never
274
+ from the local clock alone);
275
+ - `start()`, `cancel()` and `retry()`.
276
+
277
+ `start()` loads the capabilities and, when available, creates one request and
278
+ polls every `pollIntervalMs` (2 seconds by default). While the page is hidden
279
+ polling pauses and in-flight requests are aborted; it resumes immediately on
280
+ `visibilitychange` or `focus`. Poll failures back off exponentially (up to 30
281
+ seconds) and stop after 5 consecutive failures. A rotation that returns a new
282
+ code replaces the displayed one; otherwise no code is exposed again. `approved`
283
+ stores the session and calls `onSession`; `expired`, `cancelled` and `failed`
284
+ are terminal, as is `error`. `cancel()` is best-effort and a no-op outside
285
+ `creating`/`waiting`. Unmounting aborts requests, clears timers and invalidates
286
+ pending continuations.
287
+
288
+ ### Components
289
+
290
+ `<LoginCodeInput v-model="code" label="Login code" :error="error" :length="8" />`
291
+ renders a visible label, normalises input to the documented alphabet (uppercase,
292
+ spaces and hyphens stripped), prevents paste from doubling characters and emits
293
+ `submit` on Enter when complete. Its accessible name spells the characters
294
+ (`Login code: B C D F G H J K`), and an `error` renders a `role="alert"` message
295
+ linked by `aria-describedby`.
296
+
297
+ `<LoginWithCodeCard>` shows the created code with copy, refresh and expiry
298
+ countdowns, a polite live status region and Cancel / Use password instead /
299
+ Try again actions. Props: `service`, `autoStart` (default `true`), `onSession`
300
+ and `labels` (a `Partial` of the English defaults: `title`, `instructions`,
301
+ `codeLabel`, `preparing`, `waiting`, `approved`, `expired`, `cancelled`, `error`,
302
+ `unavailable`, `refreshIn` / `expiresIn` (`{seconds}` placeholder), `copy`,
303
+ `copied`, `cancel`, `usePassword`, `retry`). Events: `approved` with
304
+ `{ token, user }` (emitted after `onSession` settles), `cancel` and
305
+ `use-password`, so the host can switch to its password form.
306
+
307
+ `<AuthorizeDeviceCard>` previews the requesting device label, raw user agent,
308
+ request and expiry times and the approving account before approval, and requires
309
+ a password only when the capabilities say so. Props: `service` and `labels`
310
+ (`title`, `warning`, `codeLabel`, `preview`, `approve`, `cancel`, `password`,
311
+ `willSignInAs`, `deviceLabel`, `userAgentLabel`, `requestedAt`, `expiresAt`,
312
+ `approved`, `unavailable`, `preparing`, `invalidCode`, `alreadyUsed`,
313
+ `rateLimited`, `passwordRequired`, `unauthenticated`, `forbidden`, `network`,
314
+ `generic`). Events: `approved` with the approval body and `cancel`. Error copy
315
+ is local and generic; the server message is never rendered. Both cards render a
316
+ live region only for status changes, and `AuthorizeDeviceCard` keeps the warning
317
+ visible in every state.
318
+
319
+ ### Using the layer
320
+
321
+ With the layer extended, the components and composable are auto-imported:
322
+
323
+ ```vue
324
+ <script setup lang="ts">
325
+ import { AuthService } from "@devopsplaybook.io/common-web/services/AuthService";
326
+ import { LoginCodeService } from "@devopsplaybook.io/common-web/services/LoginCodeService";
327
+
328
+ const service = new LoginCodeService({
329
+ getAuthHeader: () => AuthService.getAuthHeader(),
330
+ });
331
+
332
+ function signedIn({ token }: { token: string }) {
333
+ AuthService.saveToken(token);
334
+ AuthService.startSessionRenewal();
335
+ }
336
+ </script>
337
+
338
+ <template>
339
+ <LoginWithCodeCard :service="service" @approved="signedIn" @use-password="showPassword = true" />
340
+ </template>
341
+ ```
342
+
343
+ Approving must happen on a device with an interactive session; a backend API
344
+ token cannot approve (`403 FORBIDDEN`). Always pass a token provider for the
345
+ approver (`getAuthHeader`), and treat `409 ALREADY_USED`, `expired`, `cancelled`
346
+ and `failed` as "start a new request".
347
+
348
+ Outside a Nuxt layer (plain Vue/Vite or a non-extending app), import the files
349
+ explicitly and transpile the package:
350
+
351
+ ```ts
352
+ // vite.config.ts / nuxt.config.ts
353
+ export default defineConfig({
354
+ build: { transpile: ["@devopsplaybook.io/common-web"] },
355
+ vite: {
356
+ optimizeDeps: { exclude: ["@devopsplaybook.io/common-web"] },
357
+ },
358
+ });
359
+ ```
360
+
361
+ ```vue
362
+ <script setup lang="ts">
363
+ import LoginWithCodeCard from "@devopsplaybook.io/common-web/components/LoginWithCodeCard.vue";
364
+ import LoginCodeInput from "@devopsplaybook.io/common-web/components/LoginCodeInput.vue";
365
+ import AuthorizeDeviceCard from "@devopsplaybook.io/common-web/components/AuthorizeDeviceCard.vue";
366
+ import { useLoginCode } from "@devopsplaybook.io/common-web/composables/useLoginCode";
367
+ import { LoginCodeService } from "@devopsplaybook.io/common-web/services/LoginCodeService";
368
+ </script>
369
+ ```
370
+
371
+ The shipped files import only `vue`, `axios`, `./Config`, the login-code service
372
+ and each other; a regression test fails if Nuxt auto-imports (`#imports`,
373
+ `useRuntimeConfig`, `navigateTo`, …) creep in. The feature adds no dependency:
374
+ the service reuses the package's existing axios dependency.
375
+
201
376
  ## Authentication state and HTTP integration
202
377
 
203
378
  `AuthService.saveToken()` and `removeToken()` emit
@@ -298,6 +473,9 @@ composables guard their browser-only access.
298
473
  offline page shows the banner right after hydration instead of in server
299
474
  HTML.
300
475
  - `useAppHeight()` touches `window` only inside `onMounted`.
476
+ - `useLoginCode()` loads capabilities and starts polling only in `onMounted`, so
477
+ the server renders `idle` (the card shows `Preparing a code…`); `LoginCodeService`
478
+ touches no browser global and is safe to call from a server context.
301
479
  - `AuthService`, `PreferencesService` and `RefreshIntervalService` guard every
302
480
  `localStorage` access: during SSR reads return their documented fallback and
303
481
  writes are no-ops.