@auth-link/web 0.0.0-stage → 0.0.2
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 +62 -0
- package/LICENSE +21 -0
- package/README.md +1264 -2
- package/THIRD_PARTY_NOTICES.md +29 -0
- package/dist/index.js +2572 -0
- package/dist/index.js.map +7 -0
- package/dist/react.js +2519 -0
- package/dist/react.js.map +7 -0
- package/dist/styles.css +126 -0
- package/dist/types/core.d.ts +40 -0
- package/dist/types/i18n.d.ts +7 -0
- package/dist/types/index.d.ts +6 -0
- package/dist/types/modal.d.ts +19 -0
- package/dist/types/react.d.ts +11 -0
- package/dist/types/types.d.ts +71 -0
- package/dist/types/view.d.ts +19 -0
- package/dist/types/vue.d.ts +12 -0
- package/dist/vue.js +2550 -0
- package/dist/vue.js.map +7 -0
- package/docs/README.en.md +397 -0
- package/docs/README.ja.md +397 -0
- package/docs/README.zh-CN.md +467 -0
- package/package.json +89 -4
package/README.md
CHANGED
|
@@ -1,3 +1,1265 @@
|
|
|
1
|
-
#
|
|
1
|
+
# AuthLink Web
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[English](#english) | [简体中文](#简体中文) | [日本語](#日本語)
|
|
4
|
+
|
|
5
|
+
## English
|
|
6
|
+
|
|
7
|
+
Responsive dialogs for **AuthLink phone binding and mobile confirmation**, with direct function calls and React / Vue components. Display binding QR codes, synchronized six-digit matching codes, countdowns and confirmation results in any web application. No particular site platform is required.
|
|
8
|
+
|
|
9
|
+
### Features
|
|
10
|
+
|
|
11
|
+
- Phone-binding QR codes generated locally in the browser.
|
|
12
|
+
- Matching numbers that update every 30 seconds, synchronized with the AuthLink app.
|
|
13
|
+
- Confirmation, rejection, expiry and error callbacks.
|
|
14
|
+
- React components and hook, Vue components and composable, and framework-independent tools.
|
|
15
|
+
- 13 interface languages, **Simplified Chinese by default**, with per-component language selection.
|
|
16
|
+
- TypeScript declarations, separate CSS and optional React/Vue peer dependencies.
|
|
17
|
+
|
|
18
|
+
This is a browser integration library. It works with your application backend, the AuthLink service and the mobile app. The service verifies the original phone’s hardware-backed proof after the user approves in the app. Screen-lock checks and system passkeys are not required. Installing the library alone does not create an authentication service.
|
|
19
|
+
|
|
20
|
+
### Install
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
npm install @auth-link/web
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Compatibility: React 18.2+ / 19, Vue 3.3+, TypeScript, ESM. Install only the framework you use. The package declares Node 22.13+ for tooling.
|
|
27
|
+
|
|
28
|
+
### Browser integration
|
|
29
|
+
|
|
30
|
+
1. Configure your backend's AuthLink tenant credentials.
|
|
31
|
+
2. Implement the two application backend endpoints below (same-origin or explicitly allowed cross-origin), authenticated to the current website user.
|
|
32
|
+
3. Create a request on a user action and pass its ticket to a component.
|
|
33
|
+
4. Your backend verifies and consumes the result before returning a confirmed response.
|
|
34
|
+
|
|
35
|
+
The browser can call this library directly. Tenant credentials and result consumption belong on your backend; never embed a tenant API key in frontend code. The supplied client defaults to same-origin and also supports explicitly allowed cross-origin backends. You can supply a custom `AuthLinkClient` to integrate another transport while preserving server-side credential handling and verification.
|
|
36
|
+
|
|
37
|
+
### Create a client (default same-origin session mode)
|
|
38
|
+
|
|
39
|
+
`readCsrfTokenFromYourCms` is application code, not an SDK export. It reads a CSRF token issued by your own backend for the current logged-in session; it must not generate one in the browser or return an AuthLink API key. The name does not require a CMS.
|
|
40
|
+
|
|
41
|
+
Reuse your framework's existing CSRF mechanism. Otherwise, generate a cryptographically random token on the server (for example, Node's `randomBytes(32).toString('base64url')`), persist it in the session, and render it into the authenticated page with HTML attribute escaping. `{{ csrfToken }}` below is a server-template variable, not a literal value. Do not publicly cache pages containing session tokens.
|
|
42
|
+
|
|
43
|
+
```html
|
|
44
|
+
<meta name="csrf-token" content="{{ csrfToken }}">
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The SDK reads the token for every request, sends it as `X-CSRF-Token`, and includes same-origin session cookies. Your backend must validate that header against the token in the same session on both creation and result routes, reject missing/mismatched tokens, and check the expected request origin. Sending a header alone does not provide CSRF protection. Obtain a fresh token after login/session changes; a SPA may supply a token returned by its own same-origin session bootstrap endpoint. If your framework expects another header name, set `csrfHeaderName` or provide a custom `AuthLinkClient`.
|
|
48
|
+
|
|
49
|
+
Create `authlink-client.ts`:
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
// authlink-client.ts
|
|
53
|
+
import { createAuthLinkClient } from '@auth-link/web';
|
|
54
|
+
import '@auth-link/web/styles.css';
|
|
55
|
+
|
|
56
|
+
// The application server renders this meta element using the current session's
|
|
57
|
+
// CSRF token. This function only reads that token; it does not generate one.
|
|
58
|
+
export function readCsrfTokenFromYourCms(): string {
|
|
59
|
+
const token = document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.content;
|
|
60
|
+
if (!token) throw new Error('Missing CSRF token; load the authenticated application page first.');
|
|
61
|
+
return token;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export const client = createAuthLinkClient({
|
|
65
|
+
baseUrl: '/api/authlink',
|
|
66
|
+
csrfToken: readCsrfTokenFromYourCms,
|
|
67
|
+
// Replace this example with the configured AuthLink service origin.
|
|
68
|
+
authLinkOrigin: 'https://auth.example.com',
|
|
69
|
+
});
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Replace `https://auth.example.com` with the configured AuthLink origin. Create requests only in user event handlers, as in the React example below.
|
|
73
|
+
|
|
74
|
+
### Separate frontend and backend origins (since 0.0.2)
|
|
75
|
+
|
|
76
|
+
The default is still same-origin `/api/authlink`. For direct cross-origin requests, configure an absolute `baseUrl` and exact `allowedBackendOrigins`, for example frontend `https://www.example.com` and application API `https://api.example.com`. Subdomains and different ports are different origins. Entries must be origins only, without paths, wildcards or embedded credentials, and must come from trusted configuration. HTTPS is required except for explicitly allowed HTTP loopback development origins (localhost, 127.0.0.1, [::1]).
|
|
77
|
+
|
|
78
|
+
The SDK validates the destination before evaluating credentials and refuses redirects. `authLinkOrigin` separately validates the AuthLink service origin encoded in the QR; it is not the application API allowlist.
|
|
79
|
+
|
|
80
|
+
#### Cross-origin session cookies
|
|
81
|
+
|
|
82
|
+
This complete initialization function uses an example `GET /api/session` endpoint that **your application implements**, returning `{ "csrfToken": "current-session-token" }` for the authenticated session with `Cache-Control: no-store` and CORS enabled. Replace that path with your existing session endpoint.
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
import { createAuthLinkClient } from '@auth-link/web';
|
|
86
|
+
|
|
87
|
+
/** /api/session is an example endpoint implemented by your application backend. */
|
|
88
|
+
export async function createSessionBackendClient(backendOrigin: string) {
|
|
89
|
+
const response = await fetch(`${backendOrigin}/api/session`, {
|
|
90
|
+
credentials: 'include', cache: 'no-store', redirect: 'error',
|
|
91
|
+
});
|
|
92
|
+
if (!response.ok) throw new Error('Session initialization failed');
|
|
93
|
+
const session: unknown = await response.json();
|
|
94
|
+
if (!session || typeof session !== 'object' || !('csrfToken' in session) ||
|
|
95
|
+
typeof session.csrfToken !== 'string' || !session.csrfToken) {
|
|
96
|
+
throw new Error('The session endpoint must return { csrfToken: string }');
|
|
97
|
+
}
|
|
98
|
+
let currentCsrfToken = session.csrfToken;
|
|
99
|
+
return {
|
|
100
|
+
client: createAuthLinkClient({
|
|
101
|
+
baseUrl: `${backendOrigin}/api/authlink`,
|
|
102
|
+
allowedBackendOrigins: [backendOrigin],
|
|
103
|
+
credentials: 'include',
|
|
104
|
+
csrfToken: () => currentCsrfToken,
|
|
105
|
+
}),
|
|
106
|
+
// Call after your application's session/token refresh; recreate on account changes.
|
|
107
|
+
updateCsrfToken(value: string) { currentCsrfToken = value; },
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
After login, call `await createSessionBackendClient('https://api.example.com')` and pass the returned `client` to the existing components. Call the returned `updateCsrfToken(newToken)` when your session refreshes its CSRF token. Close old dialogs and recreate session state on logout/account changes. Cross-origin cookies require `credentials: 'include'`, but their SameSite, Secure, domain/path and browser third-party cookie restrictions still apply. Cross-origin does not necessarily mean cross-site. Truly cross-site cookies typically require `SameSite=None; Secure`, and browser policy may still block them.
|
|
113
|
+
|
|
114
|
+
#### Cross-origin Bearer / JWT
|
|
115
|
+
|
|
116
|
+
Pass your website's existing mutable login state. Its login/refresh flow updates `auth.accessToken`; the callback reads it on every creation and poll.
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
import { createAuthLinkClient } from '@auth-link/web';
|
|
120
|
+
|
|
121
|
+
/** auth is your website's existing login state, updated by its login/refresh flow. */
|
|
122
|
+
export function createBearerBackendClient(backendOrigin: string, auth: { accessToken: string }) {
|
|
123
|
+
return createAuthLinkClient({
|
|
124
|
+
baseUrl: `${backendOrigin}/api/authlink`,
|
|
125
|
+
allowedBackendOrigins: [backendOrigin],
|
|
126
|
+
credentials: 'omit',
|
|
127
|
+
accessToken: () => auth.accessToken,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
This must be the website user's login token, never an AuthLink tenant API key. The SDK adds `Authorization: Bearer ...`. With `accessToken`, credentials default to `omit` and CSRF can be omitted for a backend that exclusively authenticates Bearer tokens without cookie fallback. Explicit `include` or `same-origin` credentials require a CSRF provider even with Bearer authentication.
|
|
133
|
+
|
|
134
|
+
#### Backend CORS
|
|
135
|
+
|
|
136
|
+
Handle `OPTIONS` preflight and return appropriate CORS headers on preflight, actual responses and errors, including the session bootstrap endpoint. For a frontend at `https://www.example.com`:
|
|
137
|
+
|
|
138
|
+
```http
|
|
139
|
+
Access-Control-Allow-Origin: https://www.example.com
|
|
140
|
+
Access-Control-Allow-Credentials: true
|
|
141
|
+
Access-Control-Allow-Methods: GET, POST, OPTIONS
|
|
142
|
+
Access-Control-Allow-Headers: Content-Type, X-CSRF-Token, Idempotency-Key, Authorization
|
|
143
|
+
Vary: Origin
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Credentialed CORS cannot use `Access-Control-Allow-Origin: *`. Match a server-side origin allowlist before returning the current allowed origin; do not reflect arbitrary origins. Preflight generally has no login credentials: validate its origin/method/headers, then authenticate the actual request and validate CSRF for cookies and request ownership. Add custom CSRF/extra headers to `Access-Control-Allow-Headers`. The SDK cannot enable backend CORS or read results using `no-cors`. See [MDN CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS).
|
|
147
|
+
|
|
148
|
+
#### Transport options
|
|
149
|
+
|
|
150
|
+
| Option | Behavior |
|
|
151
|
+
| --- | --- |
|
|
152
|
+
| `baseUrl` | Application API prefix, defaults to `/api/authlink`; absolute for cross-origin |
|
|
153
|
+
| `allowedBackendOrigins` | Additional exact application backend origins; same-origin remains allowed |
|
|
154
|
+
| `credentials` | Defaults to `same-origin`, or `omit` with `accessToken`; use `include` for cross-origin cookies |
|
|
155
|
+
| `csrfToken` | Per-request sync/async token callback, required for cookie/session mode |
|
|
156
|
+
| `csrfHeaderName` | Defaults to `X-CSRF-Token`, configurable for framework integration |
|
|
157
|
+
| `accessToken` | Per-request sync/async website login token callback, without the `Bearer ` prefix |
|
|
158
|
+
| `headers` | Extra `HeadersInit`, or sync/async callback returning it |
|
|
159
|
+
| `authLinkOrigin` | Trusted QR service origin, independent of the application API origin |
|
|
160
|
+
| `fetch` | Optional implementation; destination validation still applies |
|
|
161
|
+
|
|
162
|
+
Custom headers cannot override SDK-managed `Accept`, `Content-Type`, `Authorization`, `Idempotency-Key` or the configured CSRF header (`RESERVED_HEADER`). Use `accessToken` for Bearer auth and `csrfHeaderName` to adapt framework CSRF validation. Import `ClientOptions` from the root entry for configuration types.
|
|
163
|
+
|
|
164
|
+
Unlisted origins produce `BACKEND_ORIGIN_NOT_ALLOWED` (replacing `CMS_ORIGIN_REQUIRED`); invalid allowlist entries or URLs produce `INVALID_BACKEND_ORIGIN` / `INVALID_BASE_URL`. Missing login/CSRF tokens produce `ACCESS_TOKEN_REQUIRED` / `CSRF_REQUIRED`. Cancellation and the 10-second timeout also cover async credential providers. Browser CORS failures normally surface as `NETWORK_ERROR`; inspect browser developer tools for details.
|
|
165
|
+
|
|
166
|
+
### Open a dialog directly (React, Vue or plain JavaScript)
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
import { openAuthLinkBind, openAuthLinkConfirm, requestKey } from '@auth-link/web';
|
|
170
|
+
import { client } from './authlink-client';
|
|
171
|
+
import '@auth-link/web/styles.css';
|
|
172
|
+
|
|
173
|
+
// Call in your button handler, after your backend creates the request.
|
|
174
|
+
const ticket = await client.create('confirm', { idempotencyKey: requestKey() });
|
|
175
|
+
const modal = openAuthLinkConfirm({
|
|
176
|
+
ticket, client, locale: 'en',
|
|
177
|
+
onConfirmed: result => console.log('Confirmed:', result.requestId),
|
|
178
|
+
onRejected: result => console.log(result.code), // REJECTED; dialog already closed
|
|
179
|
+
onClose: () => console.log('Dialog closed'),
|
|
180
|
+
});
|
|
181
|
+
// Bind instead: openAuthLinkBind({ ticket: bindingTicket, client }).
|
|
182
|
+
// modal.close(); modal.setLocale('ja');
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
The dialog adapts to mobile widths, has a scrollable height, keyboard Escape and an accessible close button. Native `<dialog>` provides modal focus handling; a browser with `showModal()` is required. Closing aborts browser observation and restores focus/scroll. It does not reject, delete or undo the server request. Its original expiry still applies. Confirmation and rejection automatically close the dialog before delivering `onConfirmed` or `onRejected`; it does not emit a user-close callback. Always call `modal.destroy()` when the owning page/component unmounts; this cleans up without emitting `onClose`.
|
|
186
|
+
|
|
187
|
+
### React
|
|
188
|
+
|
|
189
|
+
`showBound(requestId)` is application UI code: it sets a message and clears the ticket to unmount the dialog. The example also defines all rejection, expiry and close handlers. Use `<AuthLinkPanel mode="bind" />` or `<AuthLinkPanel mode="confirm" />`.
|
|
190
|
+
|
|
191
|
+
```tsx
|
|
192
|
+
"use client";
|
|
193
|
+
import { useRef, useState } from 'react';
|
|
194
|
+
import { requestKey } from '@auth-link/web';
|
|
195
|
+
import type { Mode, Ticket } from '@auth-link/web';
|
|
196
|
+
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/react';
|
|
197
|
+
import { client } from './authlink-client';
|
|
198
|
+
|
|
199
|
+
export function AuthLinkPanel({ mode }: { mode: Mode }) {
|
|
200
|
+
const [ticket, setTicket] = useState<Ticket | null>(null);
|
|
201
|
+
const [busy, setBusy] = useState(false);
|
|
202
|
+
const [message, setMessage] = useState('');
|
|
203
|
+
const key = useRef<string | null>(null);
|
|
204
|
+
const creating = useRef(false);
|
|
205
|
+
function finish(message: string) {
|
|
206
|
+
setTicket(null);
|
|
207
|
+
setMessage(message);
|
|
208
|
+
}
|
|
209
|
+
function showBound(requestId: string) {
|
|
210
|
+
// UI feedback only. The backend has already verified and saved the binding.
|
|
211
|
+
finish(`Phone bound (request ${requestId})`);
|
|
212
|
+
}
|
|
213
|
+
function showConfirmed(requestId: string) {
|
|
214
|
+
finish(`Confirmed (request ${requestId})`);
|
|
215
|
+
}
|
|
216
|
+
const start = async () => {
|
|
217
|
+
if (creating.current || ticket) return;
|
|
218
|
+
creating.current = true;
|
|
219
|
+
setBusy(true);
|
|
220
|
+
setMessage('');
|
|
221
|
+
try {
|
|
222
|
+
key.current ??= requestKey();
|
|
223
|
+
setTicket(await client.create(mode, { idempotencyKey: key.current }));
|
|
224
|
+
key.current = null;
|
|
225
|
+
} catch { setMessage('Request failed; retry the same creation.'); }
|
|
226
|
+
finally { creating.current = false; setBusy(false); }
|
|
227
|
+
};
|
|
228
|
+
const Component = mode === 'bind' ? AuthLinkBind : AuthLinkConfirm;
|
|
229
|
+
return <>
|
|
230
|
+
{!ticket && <button type="button" disabled={busy} onClick={() => void start()}>Start verification</button>}
|
|
231
|
+
{ticket && <Component ticket={ticket} client={client}
|
|
232
|
+
onConfirmed={result => result.purpose === 'bind' ? showBound(result.requestId) : showConfirmed(result.requestId)}
|
|
233
|
+
onClose={() => finish('Closed')}
|
|
234
|
+
onRejected={() => finish('Request rejected on the phone')}
|
|
235
|
+
onExpired={() => finish('Request expired; start again')}
|
|
236
|
+
onError={error => setMessage(error.message)} />}
|
|
237
|
+
<p role="status">{message}</p>
|
|
238
|
+
</>;
|
|
239
|
+
}
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
The backend must verify, consume and persist the binding/confirmation before returning `confirmed`. `showBound` does not grant access or save a binding. You can instead show a toast, reload your own account-status API or navigate to a management page. Reload real binding state from the backend after a page refresh; never treat a callback, local state or localStorage as authorization. The example retains the same creation idempotency key after a failed request.
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
Mounting either component opens a dialog; unmount it in `onClose` (for example, clear the selected ticket). SSR renders no dialog and makes no requests. Omit `locale` for Simplified Chinese. Use `locale="zh-CN"` for Simplified Chinese or another code from the language table. Keep `client` and `ticket` stable between renders. The React entry preserves `"use client"`; SSR rendering does not create requests.
|
|
246
|
+
|
|
247
|
+
### Vue
|
|
248
|
+
|
|
249
|
+
```vue
|
|
250
|
+
<script setup lang="ts">
|
|
251
|
+
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/vue';
|
|
252
|
+
import type { Ticket, Confirmation } from '@auth-link/web';
|
|
253
|
+
import { client } from './authlink-client';
|
|
254
|
+
|
|
255
|
+
defineProps<{ ticket: Ticket }>();
|
|
256
|
+
function confirmed(result: Confirmation) {
|
|
257
|
+
console.log('Confirmed request:', result.requestId);
|
|
258
|
+
}
|
|
259
|
+
</script>
|
|
260
|
+
|
|
261
|
+
<template>
|
|
262
|
+
<AuthLinkBind v-if="ticket.purpose === 'bind'" :ticket="ticket" :client="client"
|
|
263
|
+
@confirmed="confirmed" />
|
|
264
|
+
<AuthLinkConfirm v-else :ticket="ticket" :client="client" locale="ja"
|
|
265
|
+
@confirmed="confirmed" />
|
|
266
|
+
</template>
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
Use `:locale="selectedLanguage"` to switch languages without creating a new verification request. Mounting opens the dialog. Use `@close` to clear the selected ticket. Vue exposes `confirmed`, `rejected`, `expired`, `error` and `close` events.
|
|
270
|
+
|
|
271
|
+
### Choose a layout
|
|
272
|
+
|
|
273
|
+
Set `variant` when opening a dialog or mounting a component. Omit it for **A**.
|
|
274
|
+
|
|
275
|
+
| Value | Desktop | Mobile |
|
|
276
|
+
| --- | --- | --- |
|
|
277
|
+
| `A` (default) | Minimal centered card with a thin code-refresh progress bar | Centered card |
|
|
278
|
+
| `B` | QR and matching code in two columns | Vertical layout |
|
|
279
|
+
| `C` | Compact card with footer cancellation | Bottom sheet with safe-area padding |
|
|
280
|
+
|
|
281
|
+
```ts
|
|
282
|
+
openAuthLinkBind({ ticket, client }); // A, Simplified Chinese by default
|
|
283
|
+
openAuthLinkConfirm({ ticket, client, variant: 'B' });
|
|
284
|
+
// modal.setVariant('C'); // Presentation only; preserves the request and polling.
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
```tsx
|
|
288
|
+
<AuthLinkBind ticket={ticket} client={client} variant="C" />
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
```vue
|
|
292
|
+
<AuthLinkConfirm :ticket="ticket" :client="client" variant="B" />
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
All layouts show a thin progress bar and a static “Code updates automatically every 30 seconds” caption. The footer normally says “Waiting for your phone”; only in the last 30 seconds does it switch to an amber “Request expiring soon · 00:29” warning. Code changes fade in briefly, respect reduced-motion preferences, and never extend the request expiry.
|
|
296
|
+
|
|
297
|
+
All variants use the same verification, expiry and callbacks. `variant` changes can be reactive in React and Vue without restarting observation. Invalid runtime values fall back to A. The footer Cancel control in B/C has the same behavior as the close icon: it closes observation, without rejecting the server request. Confirmation still dismisses the dialog automatically. A uses a subtle close icon; all close controls retain a 44px hit target and keyboard focus indication.
|
|
298
|
+
|
|
299
|
+
### Component options
|
|
300
|
+
|
|
301
|
+
| Option | Type | Meaning |
|
|
302
|
+
| --- | --- | --- |
|
|
303
|
+
| `ticket` | `Ticket`, required | Existing request returned by your backend |
|
|
304
|
+
| `client` | `AuthLinkClient`, required | Client that queries your backend |
|
|
305
|
+
| `locale` | `Locale` | Interface language; defaults to `zh-CN` |
|
|
306
|
+
| `variant` | `DialogVariant` | `A` (default), `B` or `C`; changes layout only |
|
|
307
|
+
| `showQr` | `boolean` | Optional QR on confirmation panels; binding panels always show it |
|
|
308
|
+
| `intervalMs` | `number` | Polling interval, 250–10000 ms; default 1500 ms |
|
|
309
|
+
| `onRefresh` | `() => void` | Create a new request from the expiry panel and replace the ticket |
|
|
310
|
+
|
|
311
|
+
| React callback / Vue event | Argument | Meaning |
|
|
312
|
+
| --- | --- | --- |
|
|
313
|
+
| `onConfirmed` / `confirmed` | `Confirmation` | Backend has verified and consumed the result |
|
|
314
|
+
| `onRejected` / `rejected` | `Rejection` | Phone rejected; dialog closes automatically |
|
|
315
|
+
| `onExpired` / `expired` | None | Request expired |
|
|
316
|
+
| `onClose` / `close` | None | Dialog closed; unmount the component / clear its ticket |
|
|
317
|
+
| `onError` / `error` | `Error` | Network, response validation or callback failure |
|
|
318
|
+
|
|
319
|
+
Rejection returns `{ status: 'rejected', code: 'REJECTED', requestId, purpose }`. `REJECTED` is an SDK business status, not an HTTP status code or an authorization receipt. The SDK closes the dialog without showing a rejection/retry panel or firing `onClose`. Handle any message or new request in your website's callback. In React/Vue, clear the selected ticket in `onRejected` / `@rejected` to unmount the component. Headless hooks retain `snapshot.status === 'rejected'` for custom UI.
|
|
320
|
+
|
|
321
|
+
`useAuthLink(options)` for React and `useAuthLink(() => options)` for Vue expose `snapshot` and `retry` for custom interfaces. Vue's snapshot is a shallow ref. Retry resumes the same request; `onRefresh` creates a new one through your code.
|
|
322
|
+
|
|
323
|
+
### Backend contract
|
|
324
|
+
|
|
325
|
+
The default prefix is `/api/authlink`. Both endpoints authenticate the website user using session cookies plus the configured CSRF header, or Bearer authentication. Creation also sends a stable `Idempotency-Key`. Derive the account from the validated session/token rather than a browser-supplied account ID.
|
|
326
|
+
|
|
327
|
+
```ts
|
|
328
|
+
import type { Ticket, Result } from '@auth-link/web';
|
|
329
|
+
|
|
330
|
+
// POST /api/authlink/requests
|
|
331
|
+
// Body: { purpose: 'bind' | 'confirm' }
|
|
332
|
+
// Response: Ticket
|
|
333
|
+
|
|
334
|
+
// POST /api/authlink/requests/{requestId}/result
|
|
335
|
+
// Body: {}
|
|
336
|
+
// Response: Result
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
```json
|
|
340
|
+
{
|
|
341
|
+
"status": "confirmed",
|
|
342
|
+
"requestId": "<request-id>",
|
|
343
|
+
"verificationId": "<verification-id>",
|
|
344
|
+
"purpose": "confirm",
|
|
345
|
+
"authenticationPolicy": "device-presence.v1",
|
|
346
|
+
"expiresAt": "<same-expiry-as-ticket>"
|
|
347
|
+
}
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
Creation returns the public ticket from AuthLink: `requestId`, `purpose`, `qr`, `pairingCode`, `expiresAt` and the current `displayCode`. The display frame contains `value`, `serverTime`, `validUntil`, `periodSeconds: 30`. A confirmation ticket requires a display frame.
|
|
351
|
+
|
|
352
|
+
The result endpoint verifies the authenticated user and request ownership (plus CSRF for cookie mode) and forwards pending states and the current display frame. States `new`, `pending`, `approved` and `consumed` alone do not trigger success. Before returning `confirmed`, your backend must consume the AuthLink result with its saved state and stable consume idempotency key, check the complete receipt and persist confirmation for the correct session. Persist idempotence using request/verification IDs.
|
|
353
|
+
|
|
354
|
+
### Languages
|
|
355
|
+
|
|
356
|
+
| Code | Language |
|
|
357
|
+
| --- | --- |
|
|
358
|
+
| `en` | English |
|
|
359
|
+
| `zh-CN` | 简体中文 (default) |
|
|
360
|
+
| `zh-TW` | 繁體中文 |
|
|
361
|
+
| `ja` | 日本語 |
|
|
362
|
+
| `bn` | বাংলা |
|
|
363
|
+
| `es` | Español |
|
|
364
|
+
| `fil` | Filipino |
|
|
365
|
+
| `hi` | हिन्दी |
|
|
366
|
+
| `id` | Bahasa Indonesia |
|
|
367
|
+
| `ms` | Bahasa Melayu |
|
|
368
|
+
| `pt` | Português |
|
|
369
|
+
| `th` | ไทย |
|
|
370
|
+
| `vi` | Tiếng Việt |
|
|
371
|
+
|
|
372
|
+
Missing or unsupported locale codes fall back to Simplified Chinese. The panel sets its root `lang` attribute. Import `supportedLocales` from the root entry to get the supported codes. Language selection changes display text only, never the verification request or matching numbers. Documentation is available in English, Chinese and Japanese through the links above.
|
|
373
|
+
|
|
374
|
+
### Styles and entry points
|
|
375
|
+
|
|
376
|
+
Explicitly import `@auth-link/web/styles.css`. Override `--authlink-foreground`, `--authlink-background`, `--authlink-accent` and `--authlink-muted` on `:root` or `.authlink-dialog`; dialogs are mounted under `document.body`. All component classes use the `authlink-` prefix.
|
|
377
|
+
|
|
378
|
+
React and Vue accept `className` for the dialog. Vue also accepts standard string, array or object `class` attributes, combined with `className`. Refresh buttons use the latest `onRefresh` callback supplied by the parent.
|
|
379
|
+
|
|
380
|
+
| Import | Contents |
|
|
381
|
+
| --- | --- |
|
|
382
|
+
| `@auth-link/web` | Client, request key, supported locales, types and core tools |
|
|
383
|
+
| `@auth-link/web/react` | React components and hook |
|
|
384
|
+
| `@auth-link/web/vue` | Vue components and composable |
|
|
385
|
+
| `@auth-link/web/styles.css` | Component styles |
|
|
386
|
+
|
|
387
|
+
### Security and timing
|
|
388
|
+
|
|
389
|
+
- Matching numbers are for visual comparison with the app, not standalone passwords or authorization proofs.
|
|
390
|
+
- The browser receives only public tickets and current display frames, never generation seeds, device keys or tenant secrets.
|
|
391
|
+
- A request lasts at most 120 seconds; rotating the code does not extend it. Backend and app must support AuthLink mobile protocol 7.
|
|
392
|
+
- Countdown uses server time and a monotonic clock. Expired numbers are hidden even if a network call stalls; a short update gap at rotation is expected.
|
|
393
|
+
- Component unmount/request changes abort polling. Confirmation is deduplicated per mounted instance; your backend still needs persistent idempotence.
|
|
394
|
+
- Frontend callbacks update UI. Protected APIs must rely on trusted backend records, never a JavaScript callback or a browser-supplied success flag.
|
|
395
|
+
- QR generation is local; backend SVG is not injected and no third-party QR service receives the ticket. Allow `img-src 'self' data:` in your CSP.
|
|
396
|
+
|
|
397
|
+
### License
|
|
398
|
+
|
|
399
|
+
MIT. See `LICENSE` for the full license text and `THIRD_PARTY_NOTICES.md` for bundled third-party attribution.
|
|
400
|
+
|
|
401
|
+
---
|
|
402
|
+
|
|
403
|
+
## 简体中文
|
|
404
|
+
|
|
405
|
+
**AuthLink 官方前端组件包**,帮助网站接入手机绑定与 App 确认流程,支持 React 18/19、Vue 3.3+、TypeScript 和 ESM。
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
### 功能
|
|
409
|
+
|
|
410
|
+
- **扫码绑定**:网站显示二维码,用户使用 AuthLink App 扫码并确认绑定。
|
|
411
|
+
- **手机确认**:电脑与 App 显示同步变化的六位数字,每 30 秒更新,用户核对后在 App 内批准。
|
|
412
|
+
- **结果通知**:提供确认成功、拒绝、过期和错误事件,方便网站更新界面。
|
|
413
|
+
- **框架支持**:React 组件与 hook、Vue 组件与 composable,以及无框架客户端。
|
|
414
|
+
- **多语言与主题**:支持下表中的 13 种语言,默认简体中文;独立 CSS 和可覆盖的主题变量。
|
|
415
|
+
- **生命周期管理**:请求切换或组件卸载时取消轮询,数字过期后自动隐藏。
|
|
416
|
+
|
|
417
|
+
此包是 AuthLink 的网页接入层,需要配套应用后台、AuthLink 服务和手机 App。完整 AuthLink 流程校验原手机硬件密钥证明及 App 内批准,不要求系统通行密钥、指纹或锁屏;安装此包本身不会建立鉴权服务。
|
|
418
|
+
|
|
419
|
+
### 接入步骤
|
|
420
|
+
|
|
421
|
+
1. 在应用后台完成站点租户配置,并实现本文的创建请求、查询结果两个业务后台接口(同源或显式配置的跨域后台)。
|
|
422
|
+
2. 安装包、导入样式,创建指向应用后台的客户端。
|
|
423
|
+
3. 用户点击绑定或验证时创建请求,将返回的 ticket 交给 React/Vue 组件。
|
|
424
|
+
4. 用户在 App 确认后,应用后台验证并消费结果,组件收到可信确认事件。
|
|
425
|
+
|
|
426
|
+
租户密钥只保存在应用服务端。用户是否能够继续调用受保护接口,也必须由应用后台判断。
|
|
427
|
+
|
|
428
|
+
### 流程
|
|
429
|
+
|
|
430
|
+
应用后台根据当前登录用户创建 `bind` 或 `confirm` 请求,前端拿到 ticket 后交给组件。组件只轮询应用后台。应用后台在验证归属、state、双重认证策略并消费一次性结果后,才返回 `confirmed`。
|
|
431
|
+
|
|
432
|
+
定时数字用于电脑与手机核对;用户仍在 AuthLink App 内完成 原手机硬件密钥校验和 App 内批准。它不是用户输入网站的 TOTP 登录密码,不能单独授权。请求最长 120 秒;数字变化不延长请求有效期。前端不生成数字、不接收生成 seed,不在数字更新时新建请求。
|
|
433
|
+
|
|
434
|
+
需要配套更新后的 Go 服务和客户端协议 7。服务端与 App 必须使用当前单一协议,不能只升级网页。
|
|
435
|
+
|
|
436
|
+
### 安装
|
|
437
|
+
|
|
438
|
+
在应用项目中安装:
|
|
439
|
+
|
|
440
|
+
```sh
|
|
441
|
+
npm install @auth-link/web
|
|
442
|
+
```
|
|
443
|
+
|
|
444
|
+
### 创建应用客户端(默认同源 Cookie 模式)
|
|
445
|
+
|
|
446
|
+
`readCsrfTokenFromYourCms` 是接入方函数,不是包里的导出;名称不要求与你的网站框架一致,也不要求使用 CMS。它只读取**你的网站后台提供的 CSRF token**,用于保护携带登录 cookie 的请求,不是 AuthLink 租户 API key、登录 cookie 或手机核对码。
|
|
447
|
+
|
|
448
|
+
下面采用页面 meta 标签的方式。后台需要先准备 token:
|
|
449
|
+
|
|
450
|
+
1. 优先复用网站框架现有的 CSRF 机制;没有现成机制时,在服务端为当前登录 session 生成并保存密码学安全随机 token,例如 Node 的 `randomBytes(32).toString('base64url')`。不要在浏览器随机生成一个值,也不要使用所有用户共用的固定字符串。
|
|
451
|
+
2. 服务端使用当前 session 的 token 渲染下面的标签,正确转义 HTML 属性;`{{ csrfToken }}` 表示服务器模板变量,不是可直接照抄的 token。包含会话 token 的页面不能被公开缓存。
|
|
452
|
+
3. 创建和查询接口都读取 `X-CSRF-Token`,与同一登录 session 保存的 token 校验;缺失、不匹配或请求来源不符合网站要求时拒绝请求。仅让前端发送这个头,并不会自动启用后台校验。
|
|
453
|
+
4. 登录、退出或会话/token 更新后,让页面重新取得当前 token。SPA 也可以由网站实现同源会话初始化接口返回 token,再通过 `csrfToken` 回调提供;这不是 SDK 自带接口。
|
|
454
|
+
|
|
455
|
+
```html
|
|
456
|
+
<!-- 由你的网站后台渲染到当前用户的页面 head 中 -->
|
|
457
|
+
<meta name="csrf-token" content="{{ csrfToken }}">
|
|
458
|
+
```
|
|
459
|
+
|
|
460
|
+
新建 `authlink-client.ts`:
|
|
461
|
+
|
|
462
|
+
```ts
|
|
463
|
+
// authlink-client.ts
|
|
464
|
+
import { createAuthLinkClient } from '@auth-link/web';
|
|
465
|
+
import '@auth-link/web/styles.css';
|
|
466
|
+
|
|
467
|
+
// The application server renders this meta element using the current session's
|
|
468
|
+
// CSRF token. This function only reads that token; it does not generate one.
|
|
469
|
+
export function readCsrfTokenFromYourCms(): string {
|
|
470
|
+
const token = document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.content;
|
|
471
|
+
if (!token) throw new Error('Missing CSRF token; load the authenticated application page first.');
|
|
472
|
+
return token;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
export const client = createAuthLinkClient({
|
|
476
|
+
baseUrl: '/api/authlink',
|
|
477
|
+
csrfToken: readCsrfTokenFromYourCms,
|
|
478
|
+
// Replace this example with the configured AuthLink service origin.
|
|
479
|
+
authLinkOrigin: 'https://auth.example.com',
|
|
480
|
+
});
|
|
481
|
+
```
|
|
482
|
+
|
|
483
|
+
把 `https://auth.example.com` 换成实际 AuthLink 服务来源。SDK 会在每次请求时调用读取函数,自动把值放入 `X-CSRF-Token`,并携带同源登录 cookie;前端不需要读取 HttpOnly 登录 cookie。若网站框架默认使用其他 CSRF 头名,可用 `csrfHeaderName` 配成后台期望的头名,或者实现自定义 `AuthLinkClient`。
|
|
484
|
+
|
|
485
|
+
`create` 只传用途,网站账号由后台登录 session 决定。客户端通常只初始化一次;用户点击按钮时才创建请求。完整调用见下方 React 示例,不要把 `client.create()` 放在模块加载、React effect 或 Vue watch 中。
|
|
486
|
+
|
|
487
|
+
### 前后端分离与跨域后台(0.0.2 起)
|
|
488
|
+
|
|
489
|
+
默认仍使用同源 `/api/authlink`。直接访问另一个后台来源时,同时配置完整 `baseUrl` 和 `allowedBackendOrigins`,例如网页在 `https://www.example.com`,业务后台在 `https://api.example.com`。来源是协议、主机和端口的组合;同一主域名下不同子域名也属于跨域。
|
|
490
|
+
|
|
491
|
+
`allowedBackendOrigins` 是前端明确授权的**业务后台来源**,不能带路径、通配符、用户名或密码,不能来自用户输入。生产环境使用 HTTPS;HTTP 仅允许 localhost / 127.0.0.1 / [::1] 开发环境,端口必须匹配。SDK 会先校验目标再读取凭据,并拒绝 HTTP 重定向。`authLinkOrigin` 则用于校验二维码中的 AuthLink 服务来源,两者作用不同,可按需要同时配置。
|
|
492
|
+
|
|
493
|
+
#### 跨域 Cookie / session
|
|
494
|
+
|
|
495
|
+
下面给出完整的初始化函数。`GET /api/session` 是接入网站自己实现的示例会话接口,不是包或 AuthLink 服务自带的接口;它应根据现有登录 cookie 返回 `{ "csrfToken": "当前会话的真实CSRF token" }`,设置 `Cache-Control: no-store` 并配置下文的 CORS。部署时将路径换成网站实际的会话初始化接口。
|
|
496
|
+
|
|
497
|
+
```ts
|
|
498
|
+
import { createAuthLinkClient } from '@auth-link/web';
|
|
499
|
+
|
|
500
|
+
/** /api/session is an example endpoint implemented by your application backend. */
|
|
501
|
+
export async function createSessionBackendClient(backendOrigin: string) {
|
|
502
|
+
const response = await fetch(`${backendOrigin}/api/session`, {
|
|
503
|
+
credentials: 'include', cache: 'no-store', redirect: 'error',
|
|
504
|
+
});
|
|
505
|
+
if (!response.ok) throw new Error('Session initialization failed');
|
|
506
|
+
const session: unknown = await response.json();
|
|
507
|
+
if (!session || typeof session !== 'object' || !('csrfToken' in session) ||
|
|
508
|
+
typeof session.csrfToken !== 'string' || !session.csrfToken) {
|
|
509
|
+
throw new Error('The session endpoint must return { csrfToken: string }');
|
|
510
|
+
}
|
|
511
|
+
let currentCsrfToken = session.csrfToken;
|
|
512
|
+
return {
|
|
513
|
+
client: createAuthLinkClient({
|
|
514
|
+
baseUrl: `${backendOrigin}/api/authlink`,
|
|
515
|
+
allowedBackendOrigins: [backendOrigin],
|
|
516
|
+
credentials: 'include',
|
|
517
|
+
csrfToken: () => currentCsrfToken,
|
|
518
|
+
}),
|
|
519
|
+
// Call after your application's session/token refresh; recreate on account changes.
|
|
520
|
+
updateCsrfToken(value: string) { currentCsrfToken = value; },
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
```
|
|
524
|
+
|
|
525
|
+
登录后调用 `await createSessionBackendClient('https://api.example.com')`,把返回的 `client` 交给现有 React/Vue 组件。网站刷新 CSRF token 时调用返回的 `updateCsrfToken(newToken)`;退出或切换账号时关闭旧弹窗,清理旧状态并重新初始化。`credentials: 'include'` 才会让跨域请求携带后台 cookie,但仍受 cookie 的 SameSite、Secure、Domain/Path 及浏览器第三方 Cookie 策略约束;跨域不一定跨站。真正跨站的 cookie 通常需要 `SameSite=None; Secure`,浏览器仍可能阻止第三方 Cookie。不能把 `include` 当成绕过 Cookie 策略的开关。
|
|
526
|
+
|
|
527
|
+
#### 跨域 Bearer token / JWT
|
|
528
|
+
|
|
529
|
+
传入网站自己的登录状态对象;网站完成登录或刷新后更新这个对象的 `accessToken`。回调会在每次创建和轮询时重新读取最新 token,无需重建弹窗。
|
|
530
|
+
|
|
531
|
+
```ts
|
|
532
|
+
import { createAuthLinkClient } from '@auth-link/web';
|
|
533
|
+
|
|
534
|
+
/** auth is your website's existing login state, updated by its login/refresh flow. */
|
|
535
|
+
export function createBearerBackendClient(backendOrigin: string, auth: { accessToken: string }) {
|
|
536
|
+
return createAuthLinkClient({
|
|
537
|
+
baseUrl: `${backendOrigin}/api/authlink`,
|
|
538
|
+
allowedBackendOrigins: [backendOrigin],
|
|
539
|
+
credentials: 'omit',
|
|
540
|
+
accessToken: () => auth.accessToken,
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
```
|
|
544
|
+
|
|
545
|
+
`accessToken` 必须是接入网站的用户登录 token,不能是 AuthLink 租户 API key。SDK 自动添加 `Authorization: Bearer ...`。纯 Bearer 模式默认 `credentials: 'omit'`,可不传 `csrfToken`;后台应仅按 Bearer token 认证,不回退到 Cookie 登录。若显式设置 `credentials: 'include'` 或 `'same-origin'` 混用 Cookie,仍须提供并校验 `csrfToken`。
|
|
546
|
+
|
|
547
|
+
#### 后台 CORS 配置
|
|
548
|
+
|
|
549
|
+
后台需处理浏览器发出的 `OPTIONS` 预检,并在预检、实际响应和错误响应中返回相应 CORS 头。会话初始化接口也需要这些设置。以下假设前端来源是 `https://www.example.com`:
|
|
550
|
+
|
|
551
|
+
```http
|
|
552
|
+
Access-Control-Allow-Origin: https://www.example.com
|
|
553
|
+
Access-Control-Allow-Credentials: true
|
|
554
|
+
Access-Control-Allow-Methods: GET, POST, OPTIONS
|
|
555
|
+
Access-Control-Allow-Headers: Content-Type, X-CSRF-Token, Idempotency-Key, Authorization
|
|
556
|
+
Vary: Origin
|
|
557
|
+
```
|
|
558
|
+
|
|
559
|
+
携带 Cookie 时不能把 `Access-Control-Allow-Origin` 配为 `*`;多个允许来源应匹配白名单后返回当前来源,不能无条件反射任意 Origin。预检通常不携带登录凭据,因此先验证 Origin、请求方法和请求头,再对实际请求验证登录身份、CSRF(Cookie 模式)和归属。若改了 CSRF 头名或添加自定义头,也要加入 `Access-Control-Allow-Headers`。SDK 不能替后台开启 CORS,也不能用 `no-cors` 读取验证结果。见 [MDN CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS)。
|
|
560
|
+
|
|
561
|
+
#### 请求客户端配置
|
|
562
|
+
|
|
563
|
+
| 配置 | 说明 |
|
|
564
|
+
| --- | --- |
|
|
565
|
+
| `baseUrl` | 业务后台前缀,默认 `/api/authlink`;跨域时填写完整地址 |
|
|
566
|
+
| `allowedBackendOrigins` | 额外允许的精确后台来源数组,默认只允许当前网页同源 |
|
|
567
|
+
| `credentials` | Cookie 模式默认 `same-origin`;提供 `accessToken` 时默认 `omit`;跨域 Cookie 显式设置 `include` |
|
|
568
|
+
| `csrfToken` | 每次请求读取 CSRF token 的同步或异步函数;Cookie 模式必填 |
|
|
569
|
+
| `csrfHeaderName` | CSRF 请求头名,默认 `X-CSRF-Token`,例如可设为 `X-XSRF-TOKEN` |
|
|
570
|
+
| `accessToken` | 每次请求读取网站 Bearer token 的同步或异步函数;不要包含 `Bearer ` 前缀 |
|
|
571
|
+
| `headers` | 额外的 `HeadersInit` 或返回它的同步/异步函数,可传工作区等自定义头 |
|
|
572
|
+
| `authLinkOrigin` | 核对二维码中的 AuthLink 服务来源,与业务后台来源独立 |
|
|
573
|
+
| `fetch` | 可选 fetch 实现;仍受目标来源和协议校验约束 |
|
|
574
|
+
|
|
575
|
+
SDK 管理 `Accept`、`Content-Type`、`Authorization`、`Idempotency-Key` 和配置的 CSRF 头,`headers` 不能覆盖这些字段,否则报 `RESERVED_HEADER`。用 `accessToken` 设置 Bearer token,用 `csrfHeaderName` 适配后台框架。`ClientOptions` 可从根入口导入为 TypeScript 类型。
|
|
576
|
+
|
|
577
|
+
未授权来源报 `BACKEND_ORIGIN_NOT_ALLOWED`(替代旧版的 `CMS_ORIGIN_REQUIRED`),非法来源/地址分别报 `INVALID_BACKEND_ORIGIN` / `INVALID_BASE_URL`;缺少当前登录 token 报 `ACCESS_TOKEN_REQUIRED`,缺少必要 CSRF 报 `CSRF_REQUIRED`。凭据读取也受请求取消和 10 秒超时控制。网络层的 CORS 错误由浏览器拦截,SDK 通常只能报告 `NETWORK_ERROR`,具体原因需查看浏览器开发者工具。
|
|
578
|
+
|
|
579
|
+
### 直接调用弹窗(React、Vue 或原生 JavaScript)
|
|
580
|
+
|
|
581
|
+
```ts
|
|
582
|
+
import { openAuthLinkBind, openAuthLinkConfirm, requestKey } from '@auth-link/web';
|
|
583
|
+
import { client } from './authlink-client';
|
|
584
|
+
import '@auth-link/web/styles.css';
|
|
585
|
+
|
|
586
|
+
// 在按钮事件中创建请求,再打开弹窗;client 为上文 authlink-client.ts 导出的同源客户端。
|
|
587
|
+
const ticket = await client.create('confirm', { idempotencyKey: requestKey() });
|
|
588
|
+
const modal = openAuthLinkConfirm({
|
|
589
|
+
ticket, client, locale: 'zh-CN',
|
|
590
|
+
onConfirmed: result => console.log(result.requestId),
|
|
591
|
+
onRejected: result => console.log(result.code), // REJECTED,此时弹窗已关闭
|
|
592
|
+
onClose: () => console.log('已关闭'),
|
|
593
|
+
});
|
|
594
|
+
// 绑定使用 openAuthLinkBind({ ticket: bindingTicket, client })。
|
|
595
|
+
// modal.close(); modal.setLocale('ja');
|
|
596
|
+
```
|
|
597
|
+
|
|
598
|
+
React / Vue 的 AuthLinkBind、AuthLinkConfirm 挂载后也直接打开弹窗,不再内嵌在页面。React 用 onClose、Vue 用 @close 清空 ticket 并卸载组件。服务端渲染不创建弹窗或请求。支持手机窄屏、内容滚动、关闭按钮及 Escape;要求浏览器支持原生 dialog.showModal()。弹窗挂到 document.body,主题变量请配置在 :root 或 .authlink-dialog。
|
|
599
|
+
|
|
600
|
+
关闭只停止前端查询,不拒绝或撤销服务端请求;请求仍按原有效期结束。确认成功或拒绝后弹窗自动关闭,分别回调 onConfirmed 或 onRejected,不触发用户关闭回调。直接调用时,页面卸载须执行 modal.destroy() 清理,它不触发用户关闭回调。切换语言用 modal.setLocale(),不会重建鉴权请求。
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
### React
|
|
604
|
+
|
|
605
|
+
下面的 `showBound` 也是接入方函数,负责更新页面提示和清空 `ticket`,从而卸载弹窗;它不向后台提交“绑定成功”,也不保存绑定。绑定及确认记录必须在后台查询结果接口验证、消费并保存后,才返回 `confirmed`。
|
|
606
|
+
|
|
607
|
+
这个示例包含按钮、请求创建、结果提示和弹窗清理,不再依赖未定义的 `showBound`、`showRejected` 等函数。使用 `<AuthLinkPanel mode="bind" />` 绑定,使用 `<AuthLinkPanel mode="confirm" />` 请求手机确认。
|
|
608
|
+
|
|
609
|
+
```tsx
|
|
610
|
+
"use client";
|
|
611
|
+
import { useRef, useState } from 'react';
|
|
612
|
+
import { requestKey } from '@auth-link/web';
|
|
613
|
+
import type { Mode, Ticket } from '@auth-link/web';
|
|
614
|
+
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/react';
|
|
615
|
+
import { client } from './authlink-client';
|
|
616
|
+
|
|
617
|
+
export function AuthLinkPanel({ mode }: { mode: Mode }) {
|
|
618
|
+
const [ticket, setTicket] = useState<Ticket | null>(null);
|
|
619
|
+
const [busy, setBusy] = useState(false);
|
|
620
|
+
const [message, setMessage] = useState('');
|
|
621
|
+
const key = useRef<string | null>(null);
|
|
622
|
+
const creating = useRef(false);
|
|
623
|
+
function finish(message: string) {
|
|
624
|
+
setTicket(null);
|
|
625
|
+
setMessage(message);
|
|
626
|
+
}
|
|
627
|
+
function showBound(requestId: string) {
|
|
628
|
+
// UI feedback only. The backend has already verified and saved the binding.
|
|
629
|
+
finish(`手机绑定成功(请求 ${requestId})`);
|
|
630
|
+
}
|
|
631
|
+
function showConfirmed(requestId: string) {
|
|
632
|
+
finish(`手机确认成功(请求 ${requestId})`);
|
|
633
|
+
}
|
|
634
|
+
const start = async () => {
|
|
635
|
+
if (creating.current || ticket) return;
|
|
636
|
+
creating.current = true;
|
|
637
|
+
setBusy(true);
|
|
638
|
+
setMessage('');
|
|
639
|
+
try {
|
|
640
|
+
key.current ??= requestKey();
|
|
641
|
+
setTicket(await client.create(mode, { idempotencyKey: key.current }));
|
|
642
|
+
key.current = null;
|
|
643
|
+
} catch { setMessage('请求未完成,可重试同一次创建。'); }
|
|
644
|
+
finally { creating.current = false; setBusy(false); }
|
|
645
|
+
};
|
|
646
|
+
const Component = mode === 'bind' ? AuthLinkBind : AuthLinkConfirm;
|
|
647
|
+
return <>
|
|
648
|
+
{!ticket && <button type="button" disabled={busy} onClick={() => void start()}>开始验证</button>}
|
|
649
|
+
{ticket && <Component ticket={ticket} client={client}
|
|
650
|
+
onConfirmed={result => result.purpose === 'bind' ? showBound(result.requestId) : showConfirmed(result.requestId)}
|
|
651
|
+
onClose={() => finish('已关闭')}
|
|
652
|
+
onRejected={() => finish('手机已拒绝本次请求')}
|
|
653
|
+
onExpired={() => finish('请求已过期,请重新发起')}
|
|
654
|
+
onError={error => setMessage(error.message)} />}
|
|
655
|
+
<p role="status">{message}</p>
|
|
656
|
+
</>;
|
|
657
|
+
}
|
|
658
|
+
```
|
|
659
|
+
|
|
660
|
+
`requestId` 用于展示或追踪本次请求,不是授权凭据。`showBound` 也可以按网站需求显示 toast、重新查询已有的账号状态接口或导航到绑定管理页。刷新页面后,应重新从后台读取真实绑定状态,不能只依赖 React state 或 localStorage。其他业务接口仍需在后台检查权限。
|
|
661
|
+
|
|
662
|
+
创建失败时示例保留同一个幂等键;再次点击会重试同一次创建。创建成功后清空幂等键,新的用户操作才创建新请求。关闭、成功、拒绝和过期都会清空 ticket;网络错误保留弹窗,供其重试当前请求。
|
|
663
|
+
|
|
664
|
+
确认组件默认只显示动态数字;`showQr` 可额外显示扫码入口。绑定组件始终显示二维码。`onRefresh` 可提供重新创建请求的函数;仅过期后显示该按钮。组件自身的“重试”只恢复当前请求,不创建第二个请求。
|
|
665
|
+
|
|
666
|
+
未指定 `locale` 时使用简体中文;不支持的语言代码也回退到简体中文。组件根元素设置对应的 `lang`,语言切换不会重新创建鉴权请求。
|
|
667
|
+
|
|
668
|
+
React 入口保留 `"use client"`,可用于 Next.js 客户端组件。导入包和 SSR 渲染不会创建请求。将 client 与 ticket 保持为稳定对象,例如模块级 client 和 React state 中的 ticket。卸载/切换 ticket 会取消旧轮询;StrictMode 不会创建额外请求。
|
|
669
|
+
|
|
670
|
+
### Vue
|
|
671
|
+
|
|
672
|
+
```vue
|
|
673
|
+
<script setup lang="ts">
|
|
674
|
+
import { ref, shallowRef } from 'vue';
|
|
675
|
+
import { requestKey } from '@auth-link/web';
|
|
676
|
+
import type { Confirmation, Mode, Ticket } from '@auth-link/web';
|
|
677
|
+
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/vue';
|
|
678
|
+
import { client } from './authlink-client';
|
|
679
|
+
const props = defineProps<{ mode: Mode }>();
|
|
680
|
+
const ticket = shallowRef<Ticket | null>(null);
|
|
681
|
+
const busy = ref(false);
|
|
682
|
+
const message = ref('');
|
|
683
|
+
let key: string | null = null;
|
|
684
|
+
function finish(text: string) { ticket.value = null; message.value = text; }
|
|
685
|
+
function confirmed(result: Confirmation) {
|
|
686
|
+
finish(`${result.purpose === 'bind' ? '已绑定' : '已确认'}(请求 ${result.requestId})`);
|
|
687
|
+
}
|
|
688
|
+
async function start() {
|
|
689
|
+
if (busy.value) return;
|
|
690
|
+
busy.value = true;
|
|
691
|
+
key ??= requestKey();
|
|
692
|
+
try {
|
|
693
|
+
ticket.value = await client.create(props.mode, { idempotencyKey: key });
|
|
694
|
+
key = null;
|
|
695
|
+
} catch { message.value = '请求未完成,可重试同一次创建。'; }
|
|
696
|
+
finally { busy.value = false; }
|
|
697
|
+
}
|
|
698
|
+
</script>
|
|
699
|
+
|
|
700
|
+
<template>
|
|
701
|
+
<button v-if="!ticket" type="button" :disabled="busy" @click="start">开始验证</button>
|
|
702
|
+
<AuthLinkBind v-else-if="mode === 'bind'" :ticket="ticket" :client="client"
|
|
703
|
+
@confirmed="confirmed" @close="finish('已关闭')" @rejected="finish('手机已拒绝本次请求')"
|
|
704
|
+
@expired="finish('请求已过期,请重新发起')" @error="message = '网络异常,请重试。'" />
|
|
705
|
+
<AuthLinkConfirm v-else :ticket="ticket" :client="client"
|
|
706
|
+
@confirmed="confirmed" @close="finish('已关闭')" @rejected="finish('手机已拒绝本次请求')"
|
|
707
|
+
@expired="finish('请求已过期,请重新发起')" @error="message = '网络异常,请重试。'" />
|
|
708
|
+
<p role="status">{{ message }}</p>
|
|
709
|
+
</template>
|
|
710
|
+
```
|
|
711
|
+
|
|
712
|
+
拒绝时返回 `{ status: 'rejected', code: 'REJECTED', requestId, purpose }`。`REJECTED` 是 SDK 业务状态码,不是 HTTP 状态码或授权凭证。组件自动关闭,不再显示“已拒绝 / 重新发起”面板,也不触发 `onClose`;提示和重新发起由接入网站在回调中决定。React / Vue 请在 `onRejected` / `@rejected` 中清空 ticket、卸载组件。无 UI 的 hook 仍保留 `snapshot.status === 'rejected'`,供自定义界面使用。
|
|
713
|
+
|
|
714
|
+
此示例在过期后清空 ticket,用户可再次点击按钮发起请求。如果需要在过期弹窗内提供重新发起按钮,可自行传入 `onRefresh`,在回调中创建新请求并更新 ticket。`useAuthLink(() => options)` composable 与 React 的 `useAuthLink(options)` hook 可用于自定义界面,返回 `snapshot` 和 `retry`;Vue 的 snapshot 是浅 ref。
|
|
715
|
+
|
|
716
|
+
### 选择弹窗样式
|
|
717
|
+
|
|
718
|
+
初始化时通过 `variant` 选择样式,**不传时默认 A**。
|
|
719
|
+
|
|
720
|
+
| 参数值 | 电脑端 | 手机端 |
|
|
721
|
+
| --- | --- | --- |
|
|
722
|
+
| `A`(默认) | 极简居中卡片、细线数字更新进度条 | 居中卡片 |
|
|
723
|
+
| `B` | 二维码和核对码左右分栏 | 自动纵向排列 |
|
|
724
|
+
| `C` | 紧凑卡片、底部取消入口 | 底部弹层,适配安全区域 |
|
|
725
|
+
|
|
726
|
+
```ts
|
|
727
|
+
openAuthLinkBind({ ticket, client }); // 默认 A、简体中文
|
|
728
|
+
openAuthLinkConfirm({ ticket, client, variant: 'B' });
|
|
729
|
+
// modal.setVariant('C'); // 只更新显示,不重建请求、不重启查询
|
|
730
|
+
```
|
|
731
|
+
|
|
732
|
+
```tsx
|
|
733
|
+
<AuthLinkBind ticket={ticket} client={client} variant="C" />
|
|
734
|
+
```
|
|
735
|
+
|
|
736
|
+
```vue
|
|
737
|
+
<AuthLinkConfirm :ticket="ticket" :client="client" variant="B" />
|
|
738
|
+
```
|
|
739
|
+
|
|
740
|
+
三套样式统一使用细进度条和固定文案“核对码每 30 秒自动更新”,不显示数字更新秒数。底部通常显示“等待手机确认”;仅最后 30 秒改为柔和橙色“请求即将过期 · 00:29”。新核对码轻微淡入,遵守系统减少动态效果设置;数字刷新不延长请求有效期。
|
|
741
|
+
|
|
742
|
+
三套样式使用相同的鉴权、过期和回调逻辑。React / Vue 可响应式切换 `variant`,不会重新发起请求;无效的运行时值回退到 A。B / C 的底部“取消”和右上角关闭行为一致,仅停止前端观察,不会替用户拒绝服务端请求。确认成功仍自动关闭。关闭图标保留 44px 点击区域和键盘焦点提示。
|
|
743
|
+
|
|
744
|
+
### 组件参数与事件
|
|
745
|
+
|
|
746
|
+
`AuthLinkBind` 用于绑定二维码,`AuthLinkConfirm` 用于手机确认。两者使用相同的主要参数:
|
|
747
|
+
|
|
748
|
+
| 参数 | 类型 | 说明 |
|
|
749
|
+
| --- | --- | --- |
|
|
750
|
+
| `ticket` | `Ticket`,必填 |应用后台创建的当前请求;组件不会自行创建请求 |
|
|
751
|
+
| `client` | `AuthLinkClient`,必填 | 查询应用后台结果的客户端 |
|
|
752
|
+
| `locale` | `Locale`,见下表 | 界面语言,默认 `zh-CN` |
|
|
753
|
+
| `variant` | `DialogVariant` | `A`(默认)、`B` 或 `C`;只改变布局 |
|
|
754
|
+
| `showQr` | `boolean` | 确认组件是否额外显示二维码;绑定组件始终显示 |
|
|
755
|
+
| `intervalMs` | `number` | 结果轮询间隔,默认 1500 毫秒 |
|
|
756
|
+
| `onRefresh` | `() => void` | 过期后,由网站重新创建请求并更新 ticket |
|
|
757
|
+
|
|
758
|
+
| React 回调 / Vue 事件 | 参数 | 触发时机 |
|
|
759
|
+
| --- | --- | --- |
|
|
760
|
+
| `onConfirmed` / `confirmed` | `Confirmation` |应用后台完成结果验证和消费后 |
|
|
761
|
+
| `onRejected` / `rejected` | `Rejection` | 手机拒绝请求,弹窗自动关闭 |
|
|
762
|
+
| `onExpired` / `expired` | 无 | 请求已过期 |
|
|
763
|
+
| `onError` / `error` | `Error` | 网络错误、响应校验失败或成功回调执行失败等 |
|
|
764
|
+
|
|
765
|
+
业务处理以 `requestId` / `verificationId` 做持久化幂等。前端成功事件用于展示状态,不能作为后台接口放行凭据。
|
|
766
|
+
|
|
767
|
+
### 导入入口
|
|
768
|
+
|
|
769
|
+
| 入口 | 用途 |
|
|
770
|
+
| --- | --- |
|
|
771
|
+
| `@auth-link/web` | `createAuthLinkClient`、`requestKey`、公开类型及无框架工具 |
|
|
772
|
+
| `@auth-link/web/react` | React 组件和 `useAuthLink` |
|
|
773
|
+
| `@auth-link/web/vue` | Vue 组件和 `useAuthLink` |
|
|
774
|
+
| `@auth-link/web/styles.css` | 组件样式,需显式导入 |
|
|
775
|
+
|
|
776
|
+
### 应用后台接口约定
|
|
777
|
+
|
|
778
|
+
默认前缀 `/api/authlink`;下面两个接口由接入方实现,**不是直接把浏览器请求转发到租户密钥 API**。
|
|
779
|
+
|
|
780
|
+
#### `POST /requests`
|
|
781
|
+
|
|
782
|
+
浏览器按所选模式携带网站登录凭据:Cookie 模式发送 session cookie 和配置的 CSRF 头,Bearer 模式发送 `Authorization`。创建还发送稳定的 `Idempotency-Key`,body:
|
|
783
|
+
|
|
784
|
+
```json
|
|
785
|
+
{"purpose":"bind"}
|
|
786
|
+
```
|
|
787
|
+
|
|
788
|
+
后台从经过验证的 session 或 Bearer token 取得用户 ID,创建并持久保存 state、创建/消费幂等键、用户/session 关联,然后调用 AuthLink 服务端创建请求。返回其公开 ticket:
|
|
789
|
+
|
|
790
|
+
```ts
|
|
791
|
+
type Ticket = {
|
|
792
|
+
requestId: string;
|
|
793
|
+
purpose: 'bind' | 'confirm';
|
|
794
|
+
qr: string; // AuthLink 返回的 QR JSON,不是 HTML
|
|
795
|
+
pairingCode: string;
|
|
796
|
+
expiresAt: string;
|
|
797
|
+
displayCode: {
|
|
798
|
+
value: string; // 六位数字,保留前导零
|
|
799
|
+
serverTime: string; validUntil: string;
|
|
800
|
+
periodSeconds: 30;
|
|
801
|
+
};
|
|
802
|
+
};
|
|
803
|
+
```
|
|
804
|
+
|
|
805
|
+
#### `POST /requests/{requestId}/result`
|
|
806
|
+
|
|
807
|
+
同样验证登录身份(Cookie 模式还需 CSRF)和请求归属。后台调用 AuthLink 状态接口,将 `displayCode` 原样返回,不能缓存跨过 `validUntil`。新代码由后台实时获取,不是前端自行生成。
|
|
808
|
+
|
|
809
|
+
尚未完成时返回 `{requestId,status,displayCode?}`;状态可为 new / pending / approved / consumed / rejected / expired。`approved` 不能触发成功事件。
|
|
810
|
+
|
|
811
|
+
收到 approved / consumed 后,后台使用保存的稳定消费幂等键调用 `/consume`,核对完整结果,在自己数据库事务中记录此次 session 的确认,再返回已验证的回执。组件确认所需最小字段:
|
|
812
|
+
|
|
813
|
+
```json
|
|
814
|
+
{
|
|
815
|
+
"status":"confirmed",
|
|
816
|
+
"requestId":"43字符请求ID",
|
|
817
|
+
"verificationId":"43字符结果ID",
|
|
818
|
+
"purpose":"confirm",
|
|
819
|
+
"authenticationPolicy":"device-presence.v1",
|
|
820
|
+
"expiresAt":"与创建请求完全一致的期限"
|
|
821
|
+
}
|
|
822
|
+
```
|
|
823
|
+
|
|
824
|
+
服务端必须在同一事务内记录已验证的确认结果,并校验请求归属。网页事件只用于更新界面;受保护接口必须依赖后台的可信确认记录,不能依赖 JS 回调或浏览器传来的 confirmed。
|
|
825
|
+
|
|
826
|
+
### 数字、时钟与安全
|
|
827
|
+
|
|
828
|
+
- 每个请求独立派生数字生成 seed;seed 只通过 claim 发给手机,并纳入设备签名上下文。网页只得到当前数字、服务端时间和本步期限。
|
|
829
|
+
- 倒计时使用服务端时间锚点和单调时钟;本机系统时钟错误不直接导致倒计时漂移。网络延迟仍有影响,跨步时可能短暂显示“正在更新数字”,稳定后再核对。
|
|
830
|
+
- 旧数字一过本步期限就隐藏,即使网络请求仍未返回。整个请求过期、拒绝或失败会隐藏数字和二维码。
|
|
831
|
+
- 组件按请求检查成功结果、用途、双重认证策略和有效期。取消、卸载和切换请求后,旧响应不能触发成功回调。
|
|
832
|
+
- 每个组件实例对同一请求只发一次成功事件;刷新或重新挂载不替代网站持久化幂等。
|
|
833
|
+
- 包不接收网站业务授权内容,不提供 apiKey 配置,不执行支付/授权等业务操作。
|
|
834
|
+
- 二维码在浏览器内生成,忽略后台 qrSvg,不使用 innerHTML;不上传给第三方图片服务。应用 CSP 需允许 `img-src 'self' data:`。
|
|
835
|
+
|
|
836
|
+
### 样式与语言
|
|
837
|
+
|
|
838
|
+
CSS 单独导入,所有类使用 `authlink-` 前缀。弹窗挂载到 `document.body`,可在 `:root` 或 `.authlink-dialog` 覆盖 `--authlink-foreground`、`--authlink-background`、`--authlink-accent`、`--authlink-muted`。面板语言见下表,默认简体中文。
|
|
839
|
+
|
|
840
|
+
React / Vue 均支持 `className`;Vue 还支持字符串、数组和对象形式的 `class`,与 `className` 合并。“重新发起”按钮使用父组件最新传入的 `onRefresh` 回调。
|
|
841
|
+
|
|
842
|
+
|
|
843
|
+
| Code | Language |
|
|
844
|
+
| --- | --- |
|
|
845
|
+
| `en` | English |
|
|
846
|
+
| `zh-CN` | 简体中文 (default) |
|
|
847
|
+
| `zh-TW` | 繁體中文 |
|
|
848
|
+
| `ja` | 日本語 |
|
|
849
|
+
| `bn` | বাংলা |
|
|
850
|
+
| `es` | Español |
|
|
851
|
+
| `fil` | Filipino |
|
|
852
|
+
| `hi` | हिन्दी |
|
|
853
|
+
| `id` | Bahasa Indonesia |
|
|
854
|
+
| `ms` | Bahasa Melayu |
|
|
855
|
+
| `pt` | Português |
|
|
856
|
+
| `th` | ไทย |
|
|
857
|
+
| `vi` | Tiếng Việt |
|
|
858
|
+
|
|
859
|
+
可以从根入口导入 `supportedLocales` 获取支持列表。文档默认英文,另有中文与日文版本。
|
|
860
|
+
|
|
861
|
+
### 兼容性
|
|
862
|
+
|
|
863
|
+
React 18.2+ / 19、Vue 3.3+、TypeScript、ESM。React 和 Vue 是可选 peer,只安装所用框架。构建工具环境需 Node 22.13+。
|
|
864
|
+
|
|
865
|
+
### 许可证
|
|
866
|
+
|
|
867
|
+
MIT。完整许可文本见 `LICENSE`,打包包含的第三方库归属说明见 `THIRD_PARTY_NOTICES.md`。
|
|
868
|
+
|
|
869
|
+
---
|
|
870
|
+
|
|
871
|
+
## 日本語
|
|
872
|
+
|
|
873
|
+
**AuthLink のスマートフォン登録とアプリでの確認**を Web サイトに組み込む React / Vue コンポーネントです。登録用 QR コード、同期する 6 桁の照合コード、カウントダウン、確認結果を表示します。特定のサイト基盤には依存しません。
|
|
874
|
+
|
|
875
|
+
### 主な機能
|
|
876
|
+
|
|
877
|
+
- ブラウザー内で生成するスマートフォン登録用 QR コード。
|
|
878
|
+
- アプリと同期し、30 秒ごとに更新される照合コード。
|
|
879
|
+
- 承認・拒否・期限切れ・エラーのイベント。
|
|
880
|
+
- React コンポーネントと hook、Vue コンポーネントと composable、フレームワーク非依存の API。
|
|
881
|
+
- **簡体字中国語を既定とする 13 言語**。コンポーネントごとに指定可能。
|
|
882
|
+
- TypeScript、独立した CSS、任意の React / Vue peer dependency。
|
|
883
|
+
|
|
884
|
+
本パッケージはブラウザー用の接続ライブラリです。サイトのバックエンド、AuthLink サービス、モバイルアプリと併用します。AuthLink はアプリ内の承認と元の端末のハードウェア証明を検証します。システムのパスキー、指紋認証、画面ロックは要求しません。
|
|
885
|
+
|
|
886
|
+
### インストール
|
|
887
|
+
|
|
888
|
+
```sh
|
|
889
|
+
npm install @auth-link/web
|
|
890
|
+
```
|
|
891
|
+
|
|
892
|
+
対応環境:React 18.2+ / 19、Vue 3.3+、TypeScript、ESM。利用するフレームワークだけをインストールしてください。ツール環境には Node 22.13+ が必要です。
|
|
893
|
+
|
|
894
|
+
### 接続の流れ
|
|
895
|
+
|
|
896
|
+
1. サイトのバックエンドに AuthLink のテナント資格情報を設定します。
|
|
897
|
+
2. 下記の業務バックエンド(同一オリジンまたは明示的に許可した別オリジン)の作成・結果取得 API を実装します。
|
|
898
|
+
3. ユーザー操作でリクエストを作成し、取得した ticket をコンポーネントに渡します。
|
|
899
|
+
4. バックエンドが結果を検証・消費した後に確認完了を返します。
|
|
900
|
+
|
|
901
|
+
ブラウザーからこのライブラリを呼び出せますが、テナント API キーと結果の消費処理は必ずサーバー側に置きます。標準クライアントは既定の同一オリジンと、明示的に許可した別オリジンに対応します。独自の通信方式では `AuthLinkClient` を実装できますが、資格情報と検証をブラウザーに移さないでください。
|
|
902
|
+
|
|
903
|
+
### クライアント作成(既定の同一オリジン Cookie モード)
|
|
904
|
+
|
|
905
|
+
`readCsrfTokenFromYourCms` は SDK のエクスポートではなく、接続先サイトで実装する関数です。現在のログインセッションに対してバックエンドが発行した CSRF token を読み取ります。CMS は必須ではありません。ブラウザーで値を生成したり、AuthLink の API キーを返したりしないでください。
|
|
906
|
+
|
|
907
|
+
既存フレームワークの CSRF 機構を優先してください。独自に実装する場合は、サーバーで暗号学的乱数(Node の `randomBytes(32).toString('base64url')` など)を生成し、セッションに保存して HTML 属性をエスケープしたうえでページに埋め込みます。下記の `{{ csrfToken }}` はサーバーテンプレートの変数です。このページを公開キャッシュしないでください。
|
|
908
|
+
|
|
909
|
+
```html
|
|
910
|
+
<meta name="csrf-token" content="{{ csrfToken }}">
|
|
911
|
+
```
|
|
912
|
+
|
|
913
|
+
SDK は各リクエストで token を読み取り、`X-CSRF-Token` と同一オリジンのセッション cookie を送信します。作成 API と結果 API の両方で、バックエンドが同じセッションの token と照合し、欠落・不一致や不正なリクエスト元を拒否する必要があります。ログインやセッション変更後は最新 token を取得してください。SPA ではサイト独自の同一オリジン初期化 API から取得する方法も使えます。別のヘッダー名を使うフレームワークでは`csrfHeaderName` または独自 `AuthLinkClient` で適合します。
|
|
914
|
+
|
|
915
|
+
`authlink-client.ts` を作成します:
|
|
916
|
+
|
|
917
|
+
```ts
|
|
918
|
+
// authlink-client.ts
|
|
919
|
+
import { createAuthLinkClient } from '@auth-link/web';
|
|
920
|
+
import '@auth-link/web/styles.css';
|
|
921
|
+
|
|
922
|
+
// The application server renders this meta element using the current session's
|
|
923
|
+
// CSRF token. This function only reads that token; it does not generate one.
|
|
924
|
+
export function readCsrfTokenFromYourCms(): string {
|
|
925
|
+
const token = document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.content;
|
|
926
|
+
if (!token) throw new Error('Missing CSRF token; load the authenticated application page first.');
|
|
927
|
+
return token;
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
export const client = createAuthLinkClient({
|
|
931
|
+
baseUrl: '/api/authlink',
|
|
932
|
+
csrfToken: readCsrfTokenFromYourCms,
|
|
933
|
+
// Replace this example with the configured AuthLink service origin.
|
|
934
|
+
authLinkOrigin: 'https://auth.example.com',
|
|
935
|
+
});
|
|
936
|
+
```
|
|
937
|
+
|
|
938
|
+
`https://auth.example.com` は実際の AuthLink オリジンに置き換えてください。リクエストは下記の React 例のようにユーザー操作で作成します。
|
|
939
|
+
|
|
940
|
+
### フロントエンドとバックエンドの別オリジン対応(0.0.2 以降)
|
|
941
|
+
|
|
942
|
+
既定は同一オリジンの `/api/authlink` です。別オリジンの業務 API に直接接続するには完全な `baseUrl` と `allowedBackendOrigins` を指定します。例:フロントエンド `https://www.example.com`、バックエンド `https://api.example.com`。サブドメインやポートが異なる場合も別オリジンです。許可リストにはパス、ワイルドカード、ユーザー名・パスワードを含めず、信頼する固定設定を使います。HTTPS が必須で、開発用 HTTP loopback(localhost / 127.0.0.1 / [::1])のみ例外です。
|
|
943
|
+
|
|
944
|
+
SDK は認証情報を読む前に接続先を検証し、リダイレクトを拒否します。`authLinkOrigin` は QR 内の AuthLink サービスオリジンの検証用で、業務 API の許可リストとは別です。
|
|
945
|
+
|
|
946
|
+
#### 別オリジンの Cookie / session
|
|
947
|
+
|
|
948
|
+
下記の `GET /api/session` はサイトで実装する例示 API で、SDK が提供する API ではありません。ログイン session の `{ "csrfToken": "現在のtoken" }` を返し、`Cache-Control: no-store` と CORS を設定します。既存サイトの API パスに適合してください。
|
|
949
|
+
|
|
950
|
+
```ts
|
|
951
|
+
import { createAuthLinkClient } from '@auth-link/web';
|
|
952
|
+
|
|
953
|
+
/** /api/session is an example endpoint implemented by your application backend. */
|
|
954
|
+
export async function createSessionBackendClient(backendOrigin: string) {
|
|
955
|
+
const response = await fetch(`${backendOrigin}/api/session`, {
|
|
956
|
+
credentials: 'include', cache: 'no-store', redirect: 'error',
|
|
957
|
+
});
|
|
958
|
+
if (!response.ok) throw new Error('Session initialization failed');
|
|
959
|
+
const session: unknown = await response.json();
|
|
960
|
+
if (!session || typeof session !== 'object' || !('csrfToken' in session) ||
|
|
961
|
+
typeof session.csrfToken !== 'string' || !session.csrfToken) {
|
|
962
|
+
throw new Error('The session endpoint must return { csrfToken: string }');
|
|
963
|
+
}
|
|
964
|
+
let currentCsrfToken = session.csrfToken;
|
|
965
|
+
return {
|
|
966
|
+
client: createAuthLinkClient({
|
|
967
|
+
baseUrl: `${backendOrigin}/api/authlink`,
|
|
968
|
+
allowedBackendOrigins: [backendOrigin],
|
|
969
|
+
credentials: 'include',
|
|
970
|
+
csrfToken: () => currentCsrfToken,
|
|
971
|
+
}),
|
|
972
|
+
// Call after your application's session/token refresh; recreate on account changes.
|
|
973
|
+
updateCsrfToken(value: string) { currentCsrfToken = value; },
|
|
974
|
+
};
|
|
975
|
+
}
|
|
976
|
+
```
|
|
977
|
+
|
|
978
|
+
ログイン後に `await createSessionBackendClient('https://api.example.com')` を呼び、返された `client` を既存コンポーネントに渡します。CSRF token 更新時は `updateCsrfToken(newToken)` を呼びます。ログアウトやアカウント切替時は古いダイアログを閉じ、状態を再初期化します。別オリジン Cookie には `credentials: 'include'` が必要ですが、SameSite、Secure、domain/path、ブラウザーの第三者 Cookie 制限も適用されます。別オリジンと cross-site は同じではありません。cross-site Cookie には通常 `SameSite=None; Secure` が必要で、ブラウザーによっては引き続き拒否されます。
|
|
979
|
+
|
|
980
|
+
#### Bearer token / JWT
|
|
981
|
+
|
|
982
|
+
サイトの既存ログイン状態を渡してください。ログイン・更新処理で `auth.accessToken` を更新すると、SDK は作成・ポーリングのたびに最新値を読み取ります。
|
|
983
|
+
|
|
984
|
+
```ts
|
|
985
|
+
import { createAuthLinkClient } from '@auth-link/web';
|
|
986
|
+
|
|
987
|
+
/** auth is your website's existing login state, updated by its login/refresh flow. */
|
|
988
|
+
export function createBearerBackendClient(backendOrigin: string, auth: { accessToken: string }) {
|
|
989
|
+
return createAuthLinkClient({
|
|
990
|
+
baseUrl: `${backendOrigin}/api/authlink`,
|
|
991
|
+
allowedBackendOrigins: [backendOrigin],
|
|
992
|
+
credentials: 'omit',
|
|
993
|
+
accessToken: () => auth.accessToken,
|
|
994
|
+
});
|
|
995
|
+
}
|
|
996
|
+
```
|
|
997
|
+
|
|
998
|
+
これはサイト利用者のログイン token であり、AuthLink のテナント API キーではありません。SDK が `Authorization: Bearer ...` を付加します。`accessToken` 指定時は既定で `credentials: 'omit'` となり、Cookie にフォールバックせず Bearer のみで認証するバックエンドでは CSRF を省略できます。`include` / `same-origin` を明示して Cookie を併用する場合は CSRF の提供・検証も必要です。
|
|
999
|
+
|
|
1000
|
+
#### バックエンドの CORS
|
|
1001
|
+
|
|
1002
|
+
`OPTIONS` プリフライトを処理し、実リクエスト・エラー応答・session 初期化 API にも必要な CORS ヘッダーを返します。フロントエンドが `https://www.example.com` の例:
|
|
1003
|
+
|
|
1004
|
+
```http
|
|
1005
|
+
Access-Control-Allow-Origin: https://www.example.com
|
|
1006
|
+
Access-Control-Allow-Credentials: true
|
|
1007
|
+
Access-Control-Allow-Methods: GET, POST, OPTIONS
|
|
1008
|
+
Access-Control-Allow-Headers: Content-Type, X-CSRF-Token, Idempotency-Key, Authorization
|
|
1009
|
+
Vary: Origin
|
|
1010
|
+
```
|
|
1011
|
+
|
|
1012
|
+
Cookie を使う場合 `Access-Control-Allow-Origin: *` は使用できません。バックエンドの許可リストと一致する Origin のみ返し、任意の値を反射しないでください。プリフライトには通常ログイン認証情報がないため、まず Origin・メソッド・ヘッダーを検証し、実リクエストで本人確認・CSRF(Cookie モード)・所有者を検証します。独自ヘッダーや CSRF ヘッダー名は `Access-Control-Allow-Headers` に追加します。SDK はサーバーの CORS 設定を代行できず、`no-cors` で結果を読めません。[MDN CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) を参照してください。
|
|
1013
|
+
|
|
1014
|
+
#### クライアント設定
|
|
1015
|
+
|
|
1016
|
+
| 設定 | 説明 |
|
|
1017
|
+
| --- | --- |
|
|
1018
|
+
| `baseUrl` | 業務 API の接頭辞、既定 `/api/authlink`;別オリジン時は完全 URL |
|
|
1019
|
+
| `allowedBackendOrigins` | 追加許可する正確な業務 API オリジンの配列 |
|
|
1020
|
+
| `credentials` | 既定 `same-origin`、`accessToken` 指定時 `omit`;別オリジン Cookie は `include` |
|
|
1021
|
+
| `csrfToken` | リクエストごとの同期/非同期取得関数;Cookie モードは必須 |
|
|
1022
|
+
| `csrfHeaderName` | 既定 `X-CSRF-Token`、フレームワークに合わせて変更可能 |
|
|
1023
|
+
| `accessToken` | サイトのログイン token 取得関数;`Bearer ` 接頭辞は付けない |
|
|
1024
|
+
| `headers` | 追加 `HeadersInit`、またはそれを返す同期/非同期関数 |
|
|
1025
|
+
| `authLinkOrigin` | QR 内の信頼するサービスオリジン。業務 API オリジンとは別 |
|
|
1026
|
+
| `fetch` | 任意の fetch 実装;接続先検証は維持 |
|
|
1027
|
+
|
|
1028
|
+
追加ヘッダーは SDK 管理の `Accept`、`Content-Type`、`Authorization`、`Idempotency-Key`、設定済み CSRF ヘッダーを上書きできません(`RESERVED_HEADER`)。`accessToken` と `csrfHeaderName` を使用してください。設定型 `ClientOptions` はルートエントリーからインポートできます。
|
|
1029
|
+
|
|
1030
|
+
未許可オリジンは `BACKEND_ORIGIN_NOT_ALLOWED`(旧 `CMS_ORIGIN_REQUIRED` に代わる)、不正な許可設定/URL は `INVALID_BACKEND_ORIGIN` / `INVALID_BASE_URL`、token 不足は `ACCESS_TOKEN_REQUIRED` / `CSRF_REQUIRED` となります。非同期の認証情報取得にも取消しと 10 秒タイムアウトが適用されます。CORS の詳細な失敗理由は開発者ツールで確認してください。SDK では通常 `NETWORK_ERROR` になります。
|
|
1031
|
+
|
|
1032
|
+
### 関数でダイアログを開く(React / Vue / JavaScript)
|
|
1033
|
+
|
|
1034
|
+
```ts
|
|
1035
|
+
import { openAuthLinkBind, openAuthLinkConfirm, requestKey } from '@auth-link/web';
|
|
1036
|
+
import { client } from './authlink-client';
|
|
1037
|
+
import '@auth-link/web/styles.css';
|
|
1038
|
+
|
|
1039
|
+
const ticket = await client.create('confirm', { idempotencyKey: requestKey() });
|
|
1040
|
+
const modal = openAuthLinkConfirm({
|
|
1041
|
+
ticket, client, locale: 'ja',
|
|
1042
|
+
onConfirmed: result => console.log(result.requestId),
|
|
1043
|
+
onClose: () => console.log('Closed'),
|
|
1044
|
+
});
|
|
1045
|
+
// 登録: openAuthLinkBind({ ticket: bindingTicket, client })
|
|
1046
|
+
// modal.close(); modal.setLocale('en');
|
|
1047
|
+
```
|
|
1048
|
+
|
|
1049
|
+
React / Vue コンポーネントもマウント時にダイアログを開きます。React の onClose、Vue の @close で ticket を消去してアンマウントしてください。SSR はダイアログも通信も生成しません。スマートフォンの画面幅、スクロール、閉じるボタン、Escape に対応し、ネイティブ dialog.showModal() が必要です。body 直下に表示するため、テーマ変数は :root または .authlink-dialog に設定します。
|
|
1050
|
+
|
|
1051
|
+
閉じてもサーバーのリクエストを拒否・取消しません。元の有効期限は維持されます。承認・拒否時は自動で閉じ、onConfirmed または onRejected を通知します。ユーザー操作の onClose は通知しません。関数で開いた場合はページ破棄時に modal.destroy() を呼んで通信と UI を解除してください。destroy() は onClose を通知しません。modal.setLocale() はリクエストを作り直さずに言語を切り替えます。
|
|
1052
|
+
|
|
1053
|
+
|
|
1054
|
+
### React
|
|
1055
|
+
|
|
1056
|
+
`showBound(requestId)` はサイトの表示更新用関数です。メッセージを更新し、ticket を消去してダイアログをアンマウントします。下記には拒否・期限切れ・閉じる処理も含まれます。`<AuthLinkPanel mode="bind" />` または `<AuthLinkPanel mode="confirm" />` で使います。
|
|
1057
|
+
|
|
1058
|
+
```tsx
|
|
1059
|
+
"use client";
|
|
1060
|
+
import { useRef, useState } from 'react';
|
|
1061
|
+
import { requestKey } from '@auth-link/web';
|
|
1062
|
+
import type { Mode, Ticket } from '@auth-link/web';
|
|
1063
|
+
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/react';
|
|
1064
|
+
import { client } from './authlink-client';
|
|
1065
|
+
|
|
1066
|
+
export function AuthLinkPanel({ mode }: { mode: Mode }) {
|
|
1067
|
+
const [ticket, setTicket] = useState<Ticket | null>(null);
|
|
1068
|
+
const [busy, setBusy] = useState(false);
|
|
1069
|
+
const [message, setMessage] = useState('');
|
|
1070
|
+
const key = useRef<string | null>(null);
|
|
1071
|
+
const creating = useRef(false);
|
|
1072
|
+
function finish(message: string) {
|
|
1073
|
+
setTicket(null);
|
|
1074
|
+
setMessage(message);
|
|
1075
|
+
}
|
|
1076
|
+
function showBound(requestId: string) {
|
|
1077
|
+
// UI feedback only. The backend has already verified and saved the binding.
|
|
1078
|
+
finish(`Phone bound (request ${requestId})`);
|
|
1079
|
+
}
|
|
1080
|
+
function showConfirmed(requestId: string) {
|
|
1081
|
+
finish(`Confirmed (request ${requestId})`);
|
|
1082
|
+
}
|
|
1083
|
+
const start = async () => {
|
|
1084
|
+
if (creating.current || ticket) return;
|
|
1085
|
+
creating.current = true;
|
|
1086
|
+
setBusy(true);
|
|
1087
|
+
setMessage('');
|
|
1088
|
+
try {
|
|
1089
|
+
key.current ??= requestKey();
|
|
1090
|
+
setTicket(await client.create(mode, { idempotencyKey: key.current }));
|
|
1091
|
+
key.current = null;
|
|
1092
|
+
} catch { setMessage('Request failed; retry the same creation.'); }
|
|
1093
|
+
finally { creating.current = false; setBusy(false); }
|
|
1094
|
+
};
|
|
1095
|
+
const Component = mode === 'bind' ? AuthLinkBind : AuthLinkConfirm;
|
|
1096
|
+
return <>
|
|
1097
|
+
{!ticket && <button type="button" disabled={busy} onClick={() => void start()}>Start verification</button>}
|
|
1098
|
+
{ticket && <Component ticket={ticket} client={client}
|
|
1099
|
+
onConfirmed={result => result.purpose === 'bind' ? showBound(result.requestId) : showConfirmed(result.requestId)}
|
|
1100
|
+
onClose={() => finish('Closed')}
|
|
1101
|
+
onRejected={() => finish('Request rejected on the phone')}
|
|
1102
|
+
onExpired={() => finish('Request expired; start again')}
|
|
1103
|
+
onError={error => setMessage(error.message)} />}
|
|
1104
|
+
<p role="status">{message}</p>
|
|
1105
|
+
</>;
|
|
1106
|
+
}
|
|
1107
|
+
```
|
|
1108
|
+
|
|
1109
|
+
バックエンドは結果を検証・消費・保存してから `confirmed` を返します。`showBound` は権限付与や紐付け保存を行いません。通知、サイトのアカウント状態 API の再取得、管理ページへの移動などに置き換えられます。ページ再読み込み後はサーバーから状態を取得し、コールバックや localStorage を認可に使わないでください。作成失敗時には同じ冪等キーを再利用します。
|
|
1110
|
+
|
|
1111
|
+
|
|
1112
|
+
`locale` を省略すると簡体字中国語です。日本語は `locale="ja"`、簡体字中国語は `locale="zh-CN"` を指定します。client と ticket はレンダー間で安定したオブジェクトにしてください。React エントリーは `"use client"` を保持し、SSR ではリクエストを作成しません。
|
|
1113
|
+
|
|
1114
|
+
### Vue
|
|
1115
|
+
|
|
1116
|
+
```vue
|
|
1117
|
+
<script setup lang="ts">
|
|
1118
|
+
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/vue';
|
|
1119
|
+
import type { Ticket, Confirmation } from '@auth-link/web';
|
|
1120
|
+
import { client } from './authlink-client';
|
|
1121
|
+
|
|
1122
|
+
defineProps<{ ticket: Ticket }>();
|
|
1123
|
+
function confirmed(result: Confirmation) {
|
|
1124
|
+
console.log('Confirmed request:', result.requestId);
|
|
1125
|
+
}
|
|
1126
|
+
</script>
|
|
1127
|
+
|
|
1128
|
+
<template>
|
|
1129
|
+
<AuthLinkBind v-if="ticket.purpose === 'bind'" :ticket="ticket" :client="client"
|
|
1130
|
+
@confirmed="confirmed" />
|
|
1131
|
+
<AuthLinkConfirm v-else :ticket="ticket" :client="client" locale="ja"
|
|
1132
|
+
@confirmed="confirmed" />
|
|
1133
|
+
</template>
|
|
1134
|
+
```
|
|
1135
|
+
|
|
1136
|
+
`:locale="selectedLanguage"` で表示言語を切り替えられます。言語切り替えによって新しい認証リクエストは作成されません。
|
|
1137
|
+
|
|
1138
|
+
### レイアウトの選択
|
|
1139
|
+
|
|
1140
|
+
初期化時の `variant` で選択します。省略時は **A** です。
|
|
1141
|
+
|
|
1142
|
+
| 値 | デスクトップ | モバイル |
|
|
1143
|
+
| --- | --- | --- |
|
|
1144
|
+
| `A`(既定) | ミニマルなカードと細いコード更新バー | 中央のカード |
|
|
1145
|
+
| `B` | QR と照合コードの二列表示 | 縦並び |
|
|
1146
|
+
| `C` | コンパクトなカードとキャンセル操作 | セーフエリア対応のボトムシート |
|
|
1147
|
+
|
|
1148
|
+
```ts
|
|
1149
|
+
openAuthLinkBind({ ticket, client }); // A、既定言語は簡体字中国語
|
|
1150
|
+
openAuthLinkConfirm({ ticket, client, variant: 'B' });
|
|
1151
|
+
// modal.setVariant('C');
|
|
1152
|
+
```
|
|
1153
|
+
|
|
1154
|
+
```tsx
|
|
1155
|
+
<AuthLinkBind ticket={ticket} client={client} variant="C" />
|
|
1156
|
+
```
|
|
1157
|
+
|
|
1158
|
+
```vue
|
|
1159
|
+
<AuthLinkConfirm :ticket="ticket" :client="client" variant="B" />
|
|
1160
|
+
```
|
|
1161
|
+
|
|
1162
|
+
すべてのレイアウトで細い進捗バーと「照合コードは30秒ごとに自動更新」を表示します。通常は「スマートフォンの確認待ち」を表示し、残り30秒になったときだけオレンジ色の期限警告と 00:29 形式に切り替わります。コード変更時の短いフェードはモーション低減設定に従い、リクエスト期限は延長されません。
|
|
1163
|
+
|
|
1164
|
+
React / Vue では表示中にも変更でき、リクエストやポーリングは再作成されません。未対応の値は A に戻ります。B / C のキャンセル操作は閉じるアイコンと同じく表示の監視を停止し、サーバーのリクエストは拒否しません。確認成功時は自動で閉じます。閉じる操作のタッチ領域は 44px で、キーボードのフォーカス表示も維持します。
|
|
1165
|
+
|
|
1166
|
+
### コンポーネントの設定
|
|
1167
|
+
|
|
1168
|
+
| 設定 | 型 | 説明 |
|
|
1169
|
+
| --- | --- | --- |
|
|
1170
|
+
| `ticket` | `Ticket`、必須 | バックエンドで作成したリクエスト |
|
|
1171
|
+
| `client` | `AuthLinkClient`、必須 | バックエンドの結果を取得するクライアント |
|
|
1172
|
+
| `locale` | `Locale` | 既定は `zh-CN` |
|
|
1173
|
+
| `variant` | `DialogVariant` | `A`(既定)、`B`、`C` |
|
|
1174
|
+
| `showQr` | `boolean` | 確認画面にも QR を表示。登録画面では常に表示 |
|
|
1175
|
+
| `intervalMs` | `number` | 250~10000 ミリ秒。既定は 1500 ミリ秒 |
|
|
1176
|
+
| `onRefresh` | `() => void` | 期限切れ後、新規作成して ticket を更新する処理 |
|
|
1177
|
+
|
|
1178
|
+
| React コールバック / Vue イベント | 引数 | 意味 |
|
|
1179
|
+
| --- | --- | --- |
|
|
1180
|
+
| `onConfirmed` / `confirmed` | `Confirmation` | バックエンドによる検証と消費が完了 |
|
|
1181
|
+
| `onRejected` / `rejected` | `Rejection` | 拒否時はダイアログを自動で閉じる |
|
|
1182
|
+
| `onExpired` / `expired` | なし | 有効期限切れ |
|
|
1183
|
+
| `onError` / `error` | `Error` | 通信・応答検証・コールバックのエラー |
|
|
1184
|
+
|
|
1185
|
+
拒否時は `{ status: 'rejected', code: 'REJECTED', requestId, purpose }` を返します。`REJECTED` は SDK の業務ステータスで、HTTP ステータスや承認証明ではありません。拒否・再試行画面は表示せず、`onClose` も通知しません。メッセージや新規作成はサイト側で処理してください。React / Vue では `onRejected` / `@rejected` で ticket を解除してコンポーネントを破棄します。ヘッドレス hook の `snapshot.status` は `rejected` のままです。
|
|
1186
|
+
|
|
1187
|
+
独自 UI には React の `useAuthLink(options)`、Vue の `useAuthLink(() => options)` を利用できます。返される値は `snapshot` と `retry` です。Vue の snapshot は shallow ref です。retry は既存リクエストを再開し、onRefresh はサイト側のコードで新規作成します。
|
|
1188
|
+
|
|
1189
|
+
### バックエンド API
|
|
1190
|
+
|
|
1191
|
+
既定の接頭辞は `/api/authlink` です。両 API で Cookie + 設定した CSRF ヘッダー、または Bearer token による本人確認とリクエスト所有者を検証してください。作成時は `Idempotency-Key` も送信されます。サイトのユーザー ID は検証済みセッション/token から決定します。
|
|
1192
|
+
|
|
1193
|
+
```ts
|
|
1194
|
+
import type { Ticket, Result } from '@auth-link/web';
|
|
1195
|
+
|
|
1196
|
+
// POST /api/authlink/requests
|
|
1197
|
+
// Body: { purpose: 'bind' | 'confirm' }
|
|
1198
|
+
// Response: Ticket
|
|
1199
|
+
|
|
1200
|
+
// POST /api/authlink/requests/{requestId}/result
|
|
1201
|
+
// Body: {}
|
|
1202
|
+
// Response: Result
|
|
1203
|
+
```
|
|
1204
|
+
|
|
1205
|
+
```json
|
|
1206
|
+
{
|
|
1207
|
+
"status": "confirmed",
|
|
1208
|
+
"requestId": "<request-id>",
|
|
1209
|
+
"verificationId": "<verification-id>",
|
|
1210
|
+
"purpose": "confirm",
|
|
1211
|
+
"authenticationPolicy": "device-presence.v1",
|
|
1212
|
+
"expiresAt": "<same-expiry-as-ticket>"
|
|
1213
|
+
}
|
|
1214
|
+
```
|
|
1215
|
+
|
|
1216
|
+
作成 API は AuthLink の公開 ticket(`requestId`、`purpose`、`qr`、`pairingCode`、`expiresAt`、現在の `displayCode`)を返します。displayCode は `value`、`serverTime`、`validUntil`、`periodSeconds: 30` を持ちます。確認用 ticket には displayCode が必要です。
|
|
1217
|
+
|
|
1218
|
+
結果 API は未完了状態と最新の表示コードを返します。`new` / `pending` / `approved` / `consumed` だけでは成功イベントは発火しません。`confirmed` を返す前に、バックエンドは保存した state と消費用冪等キーで AuthLink の結果を消費し、完全な受領情報を検証して正しいセッションに記録します。requestId / verificationId による永続的な冪等処理が必要です。
|
|
1219
|
+
|
|
1220
|
+
### 対応言語
|
|
1221
|
+
|
|
1222
|
+
| Code | Language |
|
|
1223
|
+
| --- | --- |
|
|
1224
|
+
| `en` | English |
|
|
1225
|
+
| `zh-CN` | 简体中文 (default) |
|
|
1226
|
+
| `zh-TW` | 繁體中文 |
|
|
1227
|
+
| `ja` | 日本語 |
|
|
1228
|
+
| `bn` | বাংলা |
|
|
1229
|
+
| `es` | Español |
|
|
1230
|
+
| `fil` | Filipino |
|
|
1231
|
+
| `hi` | हिन्दी |
|
|
1232
|
+
| `id` | Bahasa Indonesia |
|
|
1233
|
+
| `ms` | Bahasa Melayu |
|
|
1234
|
+
| `pt` | Português |
|
|
1235
|
+
| `th` | ไทย |
|
|
1236
|
+
| `vi` | Tiếng Việt |
|
|
1237
|
+
|
|
1238
|
+
未指定・未対応の言語コードは簡体字中国語にフォールバックします。ルート要素には `lang` が設定されます。ルートエントリーの `supportedLocales` で一覧を取得できます。言語変更は表示文言だけに作用し、数字やリクエストは変更しません。ドキュメントは英語・中国語・日本語で提供します。
|
|
1239
|
+
|
|
1240
|
+
### スタイルとエントリー
|
|
1241
|
+
|
|
1242
|
+
`@auth-link/web/styles.css` を明示的に読み込みます。ダイアログは `document.body` に追加されるため、`:root` または `.authlink-dialog` で `--authlink-foreground`、`--authlink-background`、`--authlink-accent`、`--authlink-muted` を上書きします。クラス名の接頭辞は `authlink-` です。
|
|
1243
|
+
|
|
1244
|
+
React / Vue はダイアログの `className` に対応します。Vue は文字列・配列・オブジェクト形式の `class` も受け取り、`className` と結合します。再作成ボタンは親が渡した最新の `onRefresh` を呼び出します。
|
|
1245
|
+
|
|
1246
|
+
| エントリー | 内容 |
|
|
1247
|
+
| --- | --- |
|
|
1248
|
+
| `@auth-link/web` | クライアント、冪等キー、対応言語、型、基本 API |
|
|
1249
|
+
| `@auth-link/web/react` | React コンポーネントと hook |
|
|
1250
|
+
| `@auth-link/web/vue` | Vue コンポーネントと composable |
|
|
1251
|
+
| `@auth-link/web/styles.css` | スタイル |
|
|
1252
|
+
|
|
1253
|
+
### セキュリティと有効期限
|
|
1254
|
+
|
|
1255
|
+
- 数字はアプリとの目視照合用です。数字だけで認証や承認はできません。
|
|
1256
|
+
- ブラウザーに生成 seed、端末秘密鍵、テナント秘密情報を渡しません。
|
|
1257
|
+
- リクエストは最大 120 秒。コード更新で期限は延長されません。サービスとアプリはモバイルプロトコル 7 に対応する必要があります。
|
|
1258
|
+
- サーバー時刻と単調増加時計で残り時間を計算し、通信が止まっても期限切れの数字は隠します。更新境界で短い待ち時間が生じる場合があります。
|
|
1259
|
+
- アンマウントや ticket 変更で監視を中止します。インスタンス内のイベント重複防止とは別に、バックエンドで永続的な冪等処理が必要です。
|
|
1260
|
+
- フロントエンドのイベントは UI 更新用です。保護 API はバックエンドの信頼できる記録で判断します。
|
|
1261
|
+
- QR はローカル生成し、バックエンドの SVG を挿入しません。CSP は `img-src 'self' data:` を許可してください。
|
|
1262
|
+
|
|
1263
|
+
### ライセンス
|
|
1264
|
+
|
|
1265
|
+
MIT。ライセンス全文は `LICENSE`、同梱ライブラリの帰属表示は `THIRD_PARTY_NOTICES.md` を参照してください。
|