@devopsplaybook.io/common-web 0.13.0 → 0.14.0-beta.25.2850fe8
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 +23 -0
- package/README.md +179 -0
- package/components/AuthorizeDeviceCard.vue +575 -0
- package/components/LoginCodeInput.vue +141 -0
- package/components/LoginWithCodeCard.vue +408 -0
- package/composables/useLoginCode.ts +436 -0
- package/package.json +1 -1
- package/services/LoginCodeService.ts +460 -0
|
@@ -0,0 +1,460 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client for the cross-device "login with a code" protocol shipped by
|
|
3
|
+
* `@devopsplaybook.io/common-utils` 2.12.0
|
|
4
|
+
* (`docs/login-with-code.md`). Plain ESM TypeScript: no Nuxt or browser
|
|
5
|
+
* globals, so it also runs during SSR.
|
|
6
|
+
*
|
|
7
|
+
* `baseUrl` is the login-code route prefix, not the server root: the default
|
|
8
|
+
* is `Config.SERVER_URL + "/users/login-codes"` (for example
|
|
9
|
+
* `/api/users/login-codes`). A supplied `baseUrl` wins and is trimmed of
|
|
10
|
+
* trailing slashes.
|
|
11
|
+
*/
|
|
12
|
+
import axios from "axios";
|
|
13
|
+
import Config from "./Config";
|
|
14
|
+
|
|
15
|
+
export type LoginCodeErrorCode =
|
|
16
|
+
| "INVALID_CODE"
|
|
17
|
+
| "ALREADY_USED"
|
|
18
|
+
| "RATE_LIMITED"
|
|
19
|
+
| "LOGIN_CODE_UNAVAILABLE"
|
|
20
|
+
| "PASSWORD_REQUIRED"
|
|
21
|
+
| "UNAUTHENTICATED"
|
|
22
|
+
| "FORBIDDEN"
|
|
23
|
+
| "NETWORK"
|
|
24
|
+
| "TIMEOUT"
|
|
25
|
+
| "ABORTED"
|
|
26
|
+
| "HTTP_ERROR"
|
|
27
|
+
| "INVALID_RESPONSE"
|
|
28
|
+
| "FAILED";
|
|
29
|
+
|
|
30
|
+
const STABLE_ERROR_CODES = new Set<string>([
|
|
31
|
+
"INVALID_CODE",
|
|
32
|
+
"ALREADY_USED",
|
|
33
|
+
"RATE_LIMITED",
|
|
34
|
+
"LOGIN_CODE_UNAVAILABLE",
|
|
35
|
+
"PASSWORD_REQUIRED",
|
|
36
|
+
"UNAUTHENTICATED",
|
|
37
|
+
"FORBIDDEN",
|
|
38
|
+
]);
|
|
39
|
+
|
|
40
|
+
const ERROR_MESSAGES: Record<LoginCodeErrorCode, string> = {
|
|
41
|
+
INVALID_CODE: "The login code is invalid or expired",
|
|
42
|
+
ALREADY_USED: "The login code was already used",
|
|
43
|
+
RATE_LIMITED: "Too many login code attempts",
|
|
44
|
+
LOGIN_CODE_UNAVAILABLE: "Login with a code is unavailable",
|
|
45
|
+
PASSWORD_REQUIRED: "A password is required to approve this sign-in",
|
|
46
|
+
UNAUTHENTICATED: "Sign in to approve a device",
|
|
47
|
+
FORBIDDEN: "This session cannot approve a sign-in",
|
|
48
|
+
NETWORK: "The login code request could not reach the server",
|
|
49
|
+
TIMEOUT: "The login code request timed out",
|
|
50
|
+
ABORTED: "The login code request was cancelled",
|
|
51
|
+
HTTP_ERROR: "The login code request failed",
|
|
52
|
+
INVALID_RESPONSE: "The server returned an unexpected login code response",
|
|
53
|
+
FAILED: "The login code request failed",
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/** A typed protocol error. Messages never include codes or request tokens. */
|
|
57
|
+
export class LoginCodeError extends Error {
|
|
58
|
+
readonly code: LoginCodeErrorCode;
|
|
59
|
+
|
|
60
|
+
readonly status?: number;
|
|
61
|
+
|
|
62
|
+
readonly retryable: boolean;
|
|
63
|
+
|
|
64
|
+
constructor(
|
|
65
|
+
code: LoginCodeErrorCode,
|
|
66
|
+
message: string = ERROR_MESSAGES[code],
|
|
67
|
+
options: { status?: number; retryable?: boolean } = {},
|
|
68
|
+
) {
|
|
69
|
+
super(message);
|
|
70
|
+
this.name = "LoginCodeError";
|
|
71
|
+
this.code = code;
|
|
72
|
+
this.status = options.status;
|
|
73
|
+
this.retryable = options.retryable ?? false;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface LoginCodeCapabilities {
|
|
78
|
+
enabled: boolean;
|
|
79
|
+
available: boolean;
|
|
80
|
+
codeLength: number;
|
|
81
|
+
rotationSeconds: number;
|
|
82
|
+
graceSeconds: number;
|
|
83
|
+
ttlSeconds: number;
|
|
84
|
+
pollIntervalMs: number;
|
|
85
|
+
approveRequiresPassword: boolean;
|
|
86
|
+
serverTime: string;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface LoginCodeRequest {
|
|
90
|
+
requestToken: string;
|
|
91
|
+
code: string;
|
|
92
|
+
codeExpiresAt: string;
|
|
93
|
+
expiresAt: string;
|
|
94
|
+
serverTime: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export type LoginCodePollResult =
|
|
98
|
+
| {
|
|
99
|
+
status: "pending";
|
|
100
|
+
code?: string;
|
|
101
|
+
codeExpiresAt: string;
|
|
102
|
+
expiresAt: string;
|
|
103
|
+
serverTime: string;
|
|
104
|
+
}
|
|
105
|
+
| {
|
|
106
|
+
status: "approved";
|
|
107
|
+
token: string;
|
|
108
|
+
user: unknown;
|
|
109
|
+
expiresAt: string;
|
|
110
|
+
serverTime: string;
|
|
111
|
+
}
|
|
112
|
+
| {
|
|
113
|
+
status: "expired" | "cancelled" | "failed";
|
|
114
|
+
expiresAt: string;
|
|
115
|
+
serverTime: string;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
export interface LoginCodePreview {
|
|
119
|
+
deviceLabel: string;
|
|
120
|
+
userAgent: string;
|
|
121
|
+
createdAt: string;
|
|
122
|
+
expiresAt: string;
|
|
123
|
+
userName: string;
|
|
124
|
+
serverTime: string;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export interface LoginCodeApproval {
|
|
128
|
+
approved: true;
|
|
129
|
+
expiresAt: string;
|
|
130
|
+
serverTime: string;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export interface LoginCodeCancellation {
|
|
134
|
+
status: "cancelled";
|
|
135
|
+
serverTime: string;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export interface LoginCodeHttpConfig {
|
|
139
|
+
signal?: AbortSignal;
|
|
140
|
+
headers?: Record<string, string>;
|
|
141
|
+
timeout?: number;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Minimal HTTP seam. A caller can pass its own axios instance (with its base
|
|
146
|
+
* URL and interceptors) because axios satisfies this shape at runtime.
|
|
147
|
+
*/
|
|
148
|
+
export interface LoginCodeHttpClient {
|
|
149
|
+
get<T = unknown>(
|
|
150
|
+
url: string,
|
|
151
|
+
config?: LoginCodeHttpConfig,
|
|
152
|
+
): Promise<{ data: T }>;
|
|
153
|
+
post<T = unknown>(
|
|
154
|
+
url: string,
|
|
155
|
+
data?: unknown,
|
|
156
|
+
config?: LoginCodeHttpConfig,
|
|
157
|
+
): Promise<{ data: T }>;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export type LoginCodeAuthHeaders =
|
|
161
|
+
| Record<string, string>
|
|
162
|
+
| { headers?: Record<string, string> };
|
|
163
|
+
|
|
164
|
+
export type LoginCodeAuthHeaderProvider = () =>
|
|
165
|
+
| LoginCodeAuthHeaders
|
|
166
|
+
| undefined
|
|
167
|
+
| Promise<LoginCodeAuthHeaders | undefined>;
|
|
168
|
+
|
|
169
|
+
export interface LoginCodeServiceOptions {
|
|
170
|
+
baseUrl?: string;
|
|
171
|
+
http?: LoginCodeHttpClient;
|
|
172
|
+
getAuthHeader?: LoginCodeAuthHeaderProvider;
|
|
173
|
+
onSession?: (token: string, user: unknown) => void | Promise<void>;
|
|
174
|
+
timeoutMs?: number;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
interface LoginCodeRequestOptions {
|
|
178
|
+
signal?: AbortSignal;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
interface LoginCodePollOptions extends LoginCodeRequestOptions {
|
|
182
|
+
refreshCode?: boolean;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
interface LoginCodeApprovePayload {
|
|
186
|
+
code: string;
|
|
187
|
+
password?: string;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
interface ErrorLike {
|
|
191
|
+
code?: unknown;
|
|
192
|
+
name?: unknown;
|
|
193
|
+
response?: { status?: unknown; data?: unknown };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
197
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function invalidResponse(message?: string): LoginCodeError {
|
|
201
|
+
return new LoginCodeError("INVALID_RESPONSE", message);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function positiveTimeout(value: number | undefined): number {
|
|
205
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0
|
|
206
|
+
? value
|
|
207
|
+
: 10_000;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Map any thrown value to a {@link LoginCodeError}. */
|
|
211
|
+
export function toLoginCodeError(error: unknown): LoginCodeError {
|
|
212
|
+
if (error instanceof LoginCodeError) return error;
|
|
213
|
+
|
|
214
|
+
const candidate = error as ErrorLike | null | undefined;
|
|
215
|
+
const status =
|
|
216
|
+
typeof candidate?.response?.status === "number"
|
|
217
|
+
? candidate.response.status
|
|
218
|
+
: undefined;
|
|
219
|
+
const data = candidate?.response?.data;
|
|
220
|
+
const bodyCode =
|
|
221
|
+
isRecord(data) && typeof data.code === "string" ? data.code : undefined;
|
|
222
|
+
|
|
223
|
+
if (bodyCode && STABLE_ERROR_CODES.has(bodyCode)) {
|
|
224
|
+
const code = bodyCode as LoginCodeErrorCode;
|
|
225
|
+
return new LoginCodeError(code, ERROR_MESSAGES[code], {
|
|
226
|
+
status,
|
|
227
|
+
// Only transient answers are worth retrying; the rest are terminal.
|
|
228
|
+
retryable: code === "RATE_LIMITED",
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (status === 401) {
|
|
233
|
+
return new LoginCodeError("UNAUTHENTICATED", ERROR_MESSAGES.UNAUTHENTICATED, {
|
|
234
|
+
status,
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
if (status === 403) {
|
|
238
|
+
return new LoginCodeError("FORBIDDEN", ERROR_MESSAGES.FORBIDDEN, { status });
|
|
239
|
+
}
|
|
240
|
+
if (status !== undefined) {
|
|
241
|
+
return new LoginCodeError(
|
|
242
|
+
"HTTP_ERROR",
|
|
243
|
+
`${ERROR_MESSAGES.HTTP_ERROR} (status ${status})`,
|
|
244
|
+
{ status, retryable: status >= 500 },
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const errorCode = candidate?.code;
|
|
249
|
+
const errorName = candidate?.name;
|
|
250
|
+
if (errorCode === "ECONNABORTED" || errorCode === "ETIMEDOUT") {
|
|
251
|
+
return new LoginCodeError("TIMEOUT", ERROR_MESSAGES.TIMEOUT, {
|
|
252
|
+
retryable: true,
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
if (
|
|
256
|
+
errorCode === "ERR_CANCELED" ||
|
|
257
|
+
errorCode === "ABORT_ERR" ||
|
|
258
|
+
errorName === "CanceledError" ||
|
|
259
|
+
errorName === "AbortError"
|
|
260
|
+
) {
|
|
261
|
+
return new LoginCodeError("ABORTED", ERROR_MESSAGES.ABORTED);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
return new LoginCodeError("NETWORK", ERROR_MESSAGES.NETWORK, {
|
|
265
|
+
retryable: true,
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export class LoginCodeService {
|
|
270
|
+
private readonly explicitBaseUrl?: string;
|
|
271
|
+
|
|
272
|
+
private readonly http: LoginCodeHttpClient;
|
|
273
|
+
|
|
274
|
+
private readonly authHeaderProvider?: LoginCodeAuthHeaderProvider;
|
|
275
|
+
|
|
276
|
+
private readonly sessionHandler?: (token: string, user: unknown) => void | Promise<void>;
|
|
277
|
+
|
|
278
|
+
private readonly timeout: number;
|
|
279
|
+
|
|
280
|
+
private resolvedBaseUrl: string | null = null;
|
|
281
|
+
|
|
282
|
+
constructor(options: LoginCodeServiceOptions = {}) {
|
|
283
|
+
this.explicitBaseUrl = options.baseUrl;
|
|
284
|
+
// Axios's config type is wider than the seam (it accepts extra fields);
|
|
285
|
+
// it is structurally compatible with the members used here.
|
|
286
|
+
this.http = options.http ?? (axios as unknown as LoginCodeHttpClient);
|
|
287
|
+
this.authHeaderProvider = options.getAuthHeader;
|
|
288
|
+
this.sessionHandler = options.onSession;
|
|
289
|
+
this.timeout = positiveTimeout(options.timeoutMs);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
async capabilities(
|
|
293
|
+
options: LoginCodeRequestOptions = {},
|
|
294
|
+
): Promise<LoginCodeCapabilities> {
|
|
295
|
+
const data = await this.send<unknown>(
|
|
296
|
+
"get",
|
|
297
|
+
"/capabilities",
|
|
298
|
+
undefined,
|
|
299
|
+
options.signal,
|
|
300
|
+
);
|
|
301
|
+
if (!isRecord(data)) throw invalidResponse();
|
|
302
|
+
return data as unknown as LoginCodeCapabilities;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
async create(options: LoginCodeRequestOptions = {}): Promise<LoginCodeRequest> {
|
|
306
|
+
// The collection route requires the trailing slash.
|
|
307
|
+
const data = await this.send<unknown>("post", "/", undefined, options.signal);
|
|
308
|
+
if (
|
|
309
|
+
!isRecord(data) ||
|
|
310
|
+
typeof data.requestToken !== "string" ||
|
|
311
|
+
typeof data.code !== "string" ||
|
|
312
|
+
typeof data.codeExpiresAt !== "string" ||
|
|
313
|
+
typeof data.expiresAt !== "string"
|
|
314
|
+
) {
|
|
315
|
+
throw invalidResponse();
|
|
316
|
+
}
|
|
317
|
+
return data as unknown as LoginCodeRequest;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
async poll(
|
|
321
|
+
requestToken: string,
|
|
322
|
+
options: LoginCodePollOptions = {},
|
|
323
|
+
): Promise<LoginCodePollResult> {
|
|
324
|
+
const body: { requestToken: string; refreshCode?: boolean } = {
|
|
325
|
+
requestToken,
|
|
326
|
+
};
|
|
327
|
+
if (options.refreshCode) body.refreshCode = true;
|
|
328
|
+
const data = await this.send<unknown>("post", "/poll", body, options.signal);
|
|
329
|
+
if (!isRecord(data)) throw invalidResponse();
|
|
330
|
+
|
|
331
|
+
const status = data.status;
|
|
332
|
+
if (status === "pending" || status === "expired" || status === "cancelled") {
|
|
333
|
+
return data as unknown as LoginCodePollResult;
|
|
334
|
+
}
|
|
335
|
+
if (status === "failed") {
|
|
336
|
+
return data as unknown as LoginCodePollResult;
|
|
337
|
+
}
|
|
338
|
+
if (status === "approved") {
|
|
339
|
+
if (typeof data.token !== "string") throw invalidResponse();
|
|
340
|
+
if (this.sessionHandler) {
|
|
341
|
+
// The redemption already happened on the server: a failing session
|
|
342
|
+
// writer must not turn a successful login into an error.
|
|
343
|
+
try {
|
|
344
|
+
await this.sessionHandler(data.token, data.user);
|
|
345
|
+
} catch {
|
|
346
|
+
// Ignored on purpose; see above.
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
return data as unknown as LoginCodePollResult;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
throw invalidResponse();
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
async preview(
|
|
356
|
+
code: string,
|
|
357
|
+
options: LoginCodeRequestOptions = {},
|
|
358
|
+
): Promise<LoginCodePreview> {
|
|
359
|
+
const data = await this.send<unknown>(
|
|
360
|
+
"post",
|
|
361
|
+
"/preview",
|
|
362
|
+
{ code },
|
|
363
|
+
options.signal,
|
|
364
|
+
await this.resolveAuthHeaders(),
|
|
365
|
+
);
|
|
366
|
+
if (!isRecord(data)) throw invalidResponse();
|
|
367
|
+
return data as unknown as LoginCodePreview;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
async approve(
|
|
371
|
+
payload: LoginCodeApprovePayload,
|
|
372
|
+
options: LoginCodeRequestOptions = {},
|
|
373
|
+
): Promise<LoginCodeApproval> {
|
|
374
|
+
const body: LoginCodeApprovePayload = { code: payload.code };
|
|
375
|
+
if (typeof payload.password === "string" && payload.password.length > 0) {
|
|
376
|
+
body.password = payload.password;
|
|
377
|
+
}
|
|
378
|
+
const data = await this.send<unknown>(
|
|
379
|
+
"post",
|
|
380
|
+
"/approve",
|
|
381
|
+
body,
|
|
382
|
+
options.signal,
|
|
383
|
+
await this.resolveAuthHeaders(),
|
|
384
|
+
);
|
|
385
|
+
if (!isRecord(data)) throw invalidResponse();
|
|
386
|
+
return data as unknown as LoginCodeApproval;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
async cancel(
|
|
390
|
+
requestToken: string,
|
|
391
|
+
options: LoginCodeRequestOptions = {},
|
|
392
|
+
): Promise<LoginCodeCancellation> {
|
|
393
|
+
const data = await this.send<unknown>(
|
|
394
|
+
"post",
|
|
395
|
+
"/cancel",
|
|
396
|
+
{ requestToken },
|
|
397
|
+
options.signal,
|
|
398
|
+
);
|
|
399
|
+
if (!isRecord(data)) throw invalidResponse();
|
|
400
|
+
return data as unknown as LoginCodeCancellation;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
private async resolveAuthHeaders(): Promise<Record<string, string> | undefined> {
|
|
404
|
+
if (!this.authHeaderProvider) return undefined;
|
|
405
|
+
|
|
406
|
+
let provided: LoginCodeAuthHeaders | undefined;
|
|
407
|
+
try {
|
|
408
|
+
provided = await this.authHeaderProvider();
|
|
409
|
+
} catch {
|
|
410
|
+
throw new LoginCodeError("UNAUTHENTICATED", ERROR_MESSAGES.UNAUTHENTICATED);
|
|
411
|
+
}
|
|
412
|
+
if (!provided) return undefined;
|
|
413
|
+
if ("headers" in provided && isRecord(provided.headers)) {
|
|
414
|
+
return provided.headers;
|
|
415
|
+
}
|
|
416
|
+
return provided as Record<string, string>;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
private async prefix(): Promise<string> {
|
|
420
|
+
if (this.resolvedBaseUrl !== null) return this.resolvedBaseUrl;
|
|
421
|
+
|
|
422
|
+
let prefix: string;
|
|
423
|
+
if (this.explicitBaseUrl !== undefined) {
|
|
424
|
+
prefix = this.explicitBaseUrl;
|
|
425
|
+
} else {
|
|
426
|
+
const config = await Config.get();
|
|
427
|
+
prefix = `${config.SERVER_URL}/users/login-codes`;
|
|
428
|
+
}
|
|
429
|
+
this.resolvedBaseUrl = prefix.trim().replace(/\/+$/, "");
|
|
430
|
+
return this.resolvedBaseUrl;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
private async send<T>(
|
|
434
|
+
method: "get" | "post",
|
|
435
|
+
path: string,
|
|
436
|
+
body: unknown,
|
|
437
|
+
signal: AbortSignal | undefined,
|
|
438
|
+
headers?: Record<string, string>,
|
|
439
|
+
): Promise<T> {
|
|
440
|
+
const url = `${await this.prefix()}${path}`;
|
|
441
|
+
const config: LoginCodeHttpConfig = { signal, timeout: this.timeout };
|
|
442
|
+
if (headers) config.headers = headers;
|
|
443
|
+
|
|
444
|
+
try {
|
|
445
|
+
const response =
|
|
446
|
+
method === "get"
|
|
447
|
+
? await this.http.get<unknown>(url, config)
|
|
448
|
+
: await this.http.post<unknown>(url, body, config);
|
|
449
|
+
return response.data as T;
|
|
450
|
+
} catch (error) {
|
|
451
|
+
throw toLoginCodeError(error);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
export function createLoginCodeService(
|
|
457
|
+
options: LoginCodeServiceOptions = {},
|
|
458
|
+
): LoginCodeService {
|
|
459
|
+
return new LoginCodeService(options);
|
|
460
|
+
}
|