@auth-link/web 0.0.4 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/README.md +90 -1958
- package/dist/index.js +469 -155
- package/dist/index.js.map +3 -3
- package/dist/react.js +473 -152
- package/dist/react.js.map +3 -3
- package/dist/styles.css +6 -0
- package/dist/types/core.d.ts +2 -0
- package/dist/types/i18n.d.ts +1 -1
- package/dist/types/index.d.ts +2 -0
- package/dist/types/modal.d.ts +2 -0
- package/dist/types/passcode.d.ts +29 -0
- package/dist/types/react.d.ts +4 -0
- package/dist/types/types.d.ts +2 -1
- package/dist/types/view.d.ts +4 -0
- package/dist/types/vue.d.ts +4 -0
- package/dist/vue.js +485 -152
- package/dist/vue.js.map +3 -3
- package/docs/README.en.md +32 -375
- package/docs/README.ja.md +32 -375
- package/docs/README.zh-CN.md +32 -445
- package/examples/react-client.tsx +24 -0
- package/examples/vue-client.vue +31 -0
- package/package.json +6 -3
- package/docs/go-vue.en.md +0 -256
- package/docs/go-vue.ja.md +0 -256
- package/docs/go-vue.zh-CN.md +0 -260
- package/examples/vue-cms.vue +0 -109
package/README.md
CHANGED
|
@@ -4,2055 +4,187 @@
|
|
|
4
4
|
|
|
5
5
|
## English
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
### Direct rotating-code verification
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
The app directly displays a six-digit rotating code. No per-action approval, authorization requestId, businessId or polling is required. First-time enrollment still scans a QR and verifies the phone; entering its current code on the website completes binding.
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
The flow is site login → Go `/api/session` returns authenticated/csrf → configure the cross-origin client with `csrfToken: () => session.csrf` → create bind/confirm → Go consumes, validates and commits the receipt → Vue dismisses the dialog → a separate business API checks the saved receipt and publishes. `baseUrl` targets Go; `authLinkOrigin` identifies AuthLink. Tenant keys stay in Go. Use your own fetch plus `validateTicket` for post/version fields; SDK create() sends purpose only.
|
|
14
|
-
|
|
15
|
-
### Features
|
|
16
|
-
|
|
17
|
-
- Phone-binding QR codes generated locally in the browser.
|
|
18
|
-
- Matching numbers that update every 30 seconds, synchronized with the AuthLink app.
|
|
19
|
-
- Confirmation, rejection, expiry and error callbacks.
|
|
20
|
-
- React components and hook, Vue components and composable, and framework-independent tools.
|
|
21
|
-
- 13 interface languages, **Simplified Chinese by default**, with per-component language selection.
|
|
22
|
-
- TypeScript declarations, separate CSS and optional React/Vue peer dependencies.
|
|
23
|
-
|
|
24
|
-
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.
|
|
25
|
-
|
|
26
|
-
### Install
|
|
11
|
+
The CMS backend must reserve one immutable pending action per session before opening the prompt. Another tab cannot replace it. Obtain the user from the server session and check CSRF and business permissions. Verify the passcode on the server and atomically commit verificationId with the saved operation before returning success. onVerified only updates the UI.
|
|
27
12
|
|
|
28
13
|
```sh
|
|
29
|
-
npm install @auth-link/web
|
|
14
|
+
npm install @auth-link/web@^1.1.0
|
|
30
15
|
```
|
|
31
16
|
|
|
32
|
-
Compatibility: React 18.2+ / 19, Vue 3.3+, TypeScript, ESM. Install only the framework you use. The package declares Node 22.13+ for tooling.
|
|
33
|
-
|
|
34
|
-
### Browser integration
|
|
35
|
-
|
|
36
|
-
1. Configure your backend's AuthLink tenant credentials.
|
|
37
|
-
2. Implement the two application backend endpoints below (same-origin or explicitly allowed cross-origin), authenticated to the current website user.
|
|
38
|
-
3. Create a request on a user action and pass its ticket to a component.
|
|
39
|
-
4. Your backend verifies and consumes the result before returning a confirmed response.
|
|
40
|
-
|
|
41
|
-
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.
|
|
42
|
-
|
|
43
|
-
### Create a client (default same-origin session mode)
|
|
44
|
-
|
|
45
|
-
`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.
|
|
46
|
-
|
|
47
|
-
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.
|
|
48
|
-
|
|
49
|
-
```html
|
|
50
|
-
<meta name="csrf-token" content="{{ csrfToken }}">
|
|
51
|
-
```
|
|
52
|
-
|
|
53
|
-
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`.
|
|
54
|
-
|
|
55
|
-
Create `authlink-client.ts`:
|
|
56
|
-
|
|
57
17
|
```ts
|
|
58
|
-
|
|
59
|
-
import { createAuthLinkClient } from '@auth-link/web';
|
|
18
|
+
import { openPasscode, createPasscodeClient } from '@auth-link/web';
|
|
60
19
|
import '@auth-link/web/styles.css';
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
return token;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
export const client = createAuthLinkClient({
|
|
71
|
-
baseUrl: '/api/authlink',
|
|
72
|
-
csrfToken: readCsrfTokenFromYourCms,
|
|
73
|
-
// AuthLink production API origin.
|
|
74
|
-
authLinkOrigin: 'https://api.getauthlink.com',
|
|
20
|
+
const client = createPasscodeClient({ baseUrl: '/api', csrfToken: () => csrfToken });
|
|
21
|
+
const modal = openPasscode({
|
|
22
|
+
client, expiresAt: pending.expiresAt, locale: 'zh-CN', variant: 'B',
|
|
23
|
+
// First-time enrollment only:
|
|
24
|
+
// bindingQr: pending.bindingQr, authLinkOrigin: 'https://api.getauthlink.com',
|
|
25
|
+
onVerified: result => updateUI(result.verificationId),
|
|
75
26
|
});
|
|
27
|
+
// modal.setLocale('en'); modal.setVariant('C'); modal.destroy();
|
|
76
28
|
```
|
|
77
29
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
### Separate frontend and backend origins (since 0.0.2)
|
|
30
|
+
The default client posts only {passcode} to POST /api/auth with current CMS credentials and CSRF. To submit a form at the same time, supply your own client.verify callback and send {form,passcode} to your CMS. The CMS checks the form against its saved snapshot; never send tenant keys or passcode seeds to the browser.
|
|
81
31
|
|
|
82
|
-
|
|
32
|
+
### Options and callbacks
|
|
83
33
|
|
|
84
|
-
|
|
34
|
+
Required: client.verify(passcode, signal) and expiresAt (the pending CMS action deadline). Optional: locale, variant A/B/C, bindingQr and authLinkOrigin for first enrollment only, onVerified, onError, onClose, onExpired. Success contains status, verificationId, authenticationPolicy and expiresAt; it has no requestId or businessId.
|
|
85
35
|
|
|
86
|
-
|
|
36
|
+
Cookie authentication requires CSRF. Bearer authentication uses accessToken with credentials=omit. For a cross-origin CMS explicitly set allowedBackendOrigins. Bare HTTPS origins are required outside loopback development.
|
|
87
37
|
|
|
88
|
-
|
|
38
|
+
### React and Vue
|
|
89
39
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
```ts
|
|
93
|
-
import { createAuthLinkClient } from '@auth-link/web';
|
|
94
|
-
|
|
95
|
-
/** /api/session is an example endpoint implemented by your application backend. */
|
|
96
|
-
export async function createSessionBackendClient(backendOrigin: string) {
|
|
97
|
-
const response = await fetch(`${backendOrigin}/api/session`, {
|
|
98
|
-
credentials: 'include', cache: 'no-store', redirect: 'error',
|
|
99
|
-
});
|
|
100
|
-
if (!response.ok) throw new Error('Session initialization failed');
|
|
101
|
-
const session: unknown = await response.json();
|
|
102
|
-
if (!session || typeof session !== 'object' || !('csrfToken' in session) ||
|
|
103
|
-
typeof session.csrfToken !== 'string' || !session.csrfToken) {
|
|
104
|
-
throw new Error('The session endpoint must return { csrfToken: string }');
|
|
105
|
-
}
|
|
106
|
-
let currentCsrfToken = session.csrfToken;
|
|
107
|
-
return {
|
|
108
|
-
client: createAuthLinkClient({
|
|
109
|
-
baseUrl: `${backendOrigin}/api/authlink`,
|
|
110
|
-
allowedBackendOrigins: [backendOrigin],
|
|
111
|
-
credentials: 'include',
|
|
112
|
-
csrfToken: () => currentCsrfToken,
|
|
113
|
-
}),
|
|
114
|
-
// Call after your application's session/token refresh; recreate on account changes.
|
|
115
|
-
updateCsrfToken(value: string) { currentCsrfToken = value; },
|
|
116
|
-
};
|
|
117
|
-
}
|
|
118
|
-
```
|
|
119
|
-
|
|
120
|
-
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.
|
|
121
|
-
|
|
122
|
-
#### Cross-origin Bearer / JWT
|
|
123
|
-
|
|
124
|
-
Pass your website's existing mutable login state. Its login/refresh flow updates `auth.accessToken`; the callback reads it on every creation and poll.
|
|
125
|
-
|
|
126
|
-
```ts
|
|
127
|
-
import { createAuthLinkClient } from '@auth-link/web';
|
|
128
|
-
|
|
129
|
-
/** auth is your website's existing login state, updated by its login/refresh flow. */
|
|
130
|
-
export function createBearerBackendClient(backendOrigin: string, auth: { accessToken: string }) {
|
|
131
|
-
return createAuthLinkClient({
|
|
132
|
-
baseUrl: `${backendOrigin}/api/authlink`,
|
|
133
|
-
allowedBackendOrigins: [backendOrigin],
|
|
134
|
-
credentials: 'omit',
|
|
135
|
-
accessToken: () => auth.accessToken,
|
|
136
|
-
});
|
|
137
|
-
}
|
|
138
|
-
```
|
|
139
|
-
|
|
140
|
-
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.
|
|
141
|
-
|
|
142
|
-
#### Backend CORS
|
|
143
|
-
|
|
144
|
-
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`:
|
|
145
|
-
|
|
146
|
-
```http
|
|
147
|
-
Access-Control-Allow-Origin: https://www.example.com
|
|
148
|
-
Access-Control-Allow-Credentials: true
|
|
149
|
-
Access-Control-Allow-Methods: GET, POST, OPTIONS
|
|
150
|
-
Access-Control-Allow-Headers: Content-Type, X-CSRF-Token, Idempotency-Key, Authorization
|
|
151
|
-
Vary: Origin
|
|
152
|
-
```
|
|
153
|
-
|
|
154
|
-
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).
|
|
155
|
-
|
|
156
|
-
#### Transport options
|
|
157
|
-
|
|
158
|
-
| Option | Behavior |
|
|
159
|
-
| --- | --- |
|
|
160
|
-
| `baseUrl` | Application API prefix, defaults to `/api/authlink`; absolute for cross-origin |
|
|
161
|
-
| `allowedBackendOrigins` | Additional exact application backend origins; same-origin remains allowed |
|
|
162
|
-
| `credentials` | Defaults to `same-origin`, or `omit` with `accessToken`; use `include` for cross-origin cookies |
|
|
163
|
-
| `csrfToken` | Per-request sync/async token callback, required for cookie/session mode |
|
|
164
|
-
| `csrfHeaderName` | Defaults to `X-CSRF-Token`, configurable for framework integration |
|
|
165
|
-
| `accessToken` | Per-request sync/async website login token callback, without the `Bearer ` prefix |
|
|
166
|
-
| `headers` | Extra `HeadersInit`, or sync/async callback returning it |
|
|
167
|
-
| `authLinkOrigin` | Trusted QR service origin, independent of the application API origin |
|
|
168
|
-
| `fetch` | Optional implementation; destination validation still applies |
|
|
169
|
-
|
|
170
|
-
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.
|
|
171
|
-
|
|
172
|
-
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.
|
|
173
|
-
|
|
174
|
-
### Open a dialog directly (React, Vue or plain JavaScript)
|
|
175
|
-
|
|
176
|
-
```ts
|
|
177
|
-
import { openAuthLinkBind, openAuthLinkConfirm, requestKey } from '@auth-link/web';
|
|
178
|
-
import { client } from './authlink-client';
|
|
179
|
-
import '@auth-link/web/styles.css';
|
|
180
|
-
|
|
181
|
-
// Call in your button handler, after your backend creates the request.
|
|
182
|
-
const ticket = await client.create('confirm', { idempotencyKey: requestKey() });
|
|
183
|
-
const modal = openAuthLinkConfirm({
|
|
184
|
-
ticket, client, locale: 'en',
|
|
185
|
-
onConfirmed: result => console.log('Confirmed:', result.requestId),
|
|
186
|
-
onRejected: result => console.log(result.code), // REJECTED; dialog already closed
|
|
187
|
-
onClose: () => console.log('Dialog closed'),
|
|
188
|
-
});
|
|
189
|
-
// Bind instead: openAuthLinkBind({ ticket: bindingTicket, client }).
|
|
190
|
-
// modal.close(); modal.setLocale('ja');
|
|
191
|
-
```
|
|
192
|
-
|
|
193
|
-
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`.
|
|
194
|
-
|
|
195
|
-
### React
|
|
196
|
-
|
|
197
|
-
`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" />`.
|
|
40
|
+
The React component takes the same options. Vue emits verified, error, close and expired. Keep client references stable. Thirteen languages remain supported; Simplified Chinese is the default. A is minimal, B is split, C is compact.
|
|
198
41
|
|
|
199
42
|
```tsx
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/react';
|
|
205
|
-
import { client } from './authlink-client';
|
|
206
|
-
|
|
207
|
-
export function AuthLinkPanel({ mode }: { mode: Mode }) {
|
|
208
|
-
const [ticket, setTicket] = useState<Ticket | null>(null);
|
|
209
|
-
const [busy, setBusy] = useState(false);
|
|
210
|
-
const [message, setMessage] = useState('');
|
|
211
|
-
const key = useRef<string | null>(null);
|
|
212
|
-
const creating = useRef(false);
|
|
213
|
-
function finish(message: string) {
|
|
214
|
-
setTicket(null);
|
|
215
|
-
setMessage(message);
|
|
216
|
-
}
|
|
217
|
-
function showBound(requestId: string) {
|
|
218
|
-
// UI feedback only. The backend has already verified and saved the binding.
|
|
219
|
-
finish(`Phone bound (request ${requestId})`);
|
|
220
|
-
}
|
|
221
|
-
function showConfirmed(requestId: string) {
|
|
222
|
-
finish(`Confirmed (request ${requestId})`);
|
|
223
|
-
}
|
|
224
|
-
const start = async () => {
|
|
225
|
-
if (creating.current || ticket) return;
|
|
226
|
-
creating.current = true;
|
|
227
|
-
setBusy(true);
|
|
228
|
-
setMessage('');
|
|
229
|
-
try {
|
|
230
|
-
key.current ??= requestKey();
|
|
231
|
-
setTicket(await client.create(mode, { idempotencyKey: key.current }));
|
|
232
|
-
key.current = null;
|
|
233
|
-
} catch { setMessage('Request failed; retry the same creation.'); }
|
|
234
|
-
finally { creating.current = false; setBusy(false); }
|
|
235
|
-
};
|
|
236
|
-
const Component = mode === 'bind' ? AuthLinkBind : AuthLinkConfirm;
|
|
237
|
-
return <>
|
|
238
|
-
{!ticket && <button type="button" disabled={busy} onClick={() => void start()}>Start verification</button>}
|
|
239
|
-
{ticket && <Component ticket={ticket} client={client}
|
|
240
|
-
onConfirmed={result => result.purpose === 'bind' ? showBound(result.requestId) : showConfirmed(result.requestId)}
|
|
241
|
-
onClose={() => finish('Closed')}
|
|
242
|
-
onRejected={() => finish('Request rejected on the phone')}
|
|
243
|
-
onExpired={() => finish('Request expired; start again')}
|
|
244
|
-
onError={error => setMessage(error.message)} />}
|
|
245
|
-
<p role="status">{message}</p>
|
|
246
|
-
</>;
|
|
247
|
-
}
|
|
43
|
+
import { AuthLinkPasscode } from '@auth-link/web/react';
|
|
44
|
+
// Keep client stable (for example with useMemo).
|
|
45
|
+
<AuthLinkPasscode client={client} expiresAt={pending.expiresAt}
|
|
46
|
+
locale="zh-CN" variant="B" onVerified={updateUI} />
|
|
248
47
|
```
|
|
249
|
-
|
|
250
|
-
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.
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
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.
|
|
254
|
-
|
|
255
|
-
### Vue
|
|
256
|
-
|
|
257
48
|
```vue
|
|
258
|
-
<script setup
|
|
259
|
-
import {
|
|
260
|
-
import type { Ticket, Confirmation } from '@auth-link/web';
|
|
261
|
-
import { client } from './authlink-client';
|
|
262
|
-
|
|
263
|
-
defineProps<{ ticket: Ticket }>();
|
|
264
|
-
function confirmed(result: Confirmation) {
|
|
265
|
-
console.log('Confirmed request:', result.requestId);
|
|
266
|
-
}
|
|
49
|
+
<script setup>
|
|
50
|
+
import { AuthLinkPasscode } from '@auth-link/web/vue';
|
|
267
51
|
</script>
|
|
268
|
-
|
|
269
52
|
<template>
|
|
270
|
-
<
|
|
271
|
-
@
|
|
272
|
-
<AuthLinkConfirm v-else :ticket="ticket" :client="client" locale="ja"
|
|
273
|
-
@confirmed="confirmed" />
|
|
53
|
+
<AuthLinkPasscode :client="client" :expires-at="pending.expiresAt"
|
|
54
|
+
locale="zh-CN" variant="B" @verified="updateUI" />
|
|
274
55
|
</template>
|
|
275
56
|
```
|
|
276
57
|
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
### Choose a layout
|
|
280
|
-
|
|
281
|
-
Set `variant` when opening a dialog or mounting a component. Omit it for **A**.
|
|
282
|
-
|
|
283
|
-
| Value | Desktop | Mobile |
|
|
284
|
-
| --- | --- | --- |
|
|
285
|
-
| `A` (default) | Minimal centered card with a thin code-refresh progress bar | Centered card |
|
|
286
|
-
| `B` | QR and matching code in two columns | Vertical layout |
|
|
287
|
-
| `C` | Compact card with footer cancellation | Bottom sheet with safe-area padding |
|
|
288
|
-
|
|
289
|
-
```ts
|
|
290
|
-
openAuthLinkBind({ ticket, client }); // A, Simplified Chinese by default
|
|
291
|
-
openAuthLinkConfirm({ ticket, client, variant: 'B' });
|
|
292
|
-
// modal.setVariant('C'); // Presentation only; preserves the request and polling.
|
|
293
|
-
```
|
|
294
|
-
|
|
295
|
-
```tsx
|
|
296
|
-
<AuthLinkBind ticket={ticket} client={client} variant="C" />
|
|
297
|
-
```
|
|
298
|
-
|
|
299
|
-
```vue
|
|
300
|
-
<AuthLinkConfirm :ticket="ticket" :client="client" variant="B" />
|
|
301
|
-
```
|
|
302
|
-
|
|
303
|
-
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.
|
|
304
|
-
|
|
305
|
-
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.
|
|
306
|
-
|
|
307
|
-
### Component options
|
|
308
|
-
|
|
309
|
-
| Option | Type | Meaning |
|
|
310
|
-
| --- | --- | --- |
|
|
311
|
-
| `ticket` | `Ticket`, required | Existing request returned by your backend |
|
|
312
|
-
| `client` | `AuthLinkClient`, required | Client that queries your backend |
|
|
313
|
-
| `locale` | `Locale` | Interface language; defaults to `zh-CN` |
|
|
314
|
-
| `variant` | `DialogVariant` | `A` (default), `B` or `C`; changes layout only |
|
|
315
|
-
| `showQr` | `boolean` | Optional QR on confirmation panels; binding panels always show it |
|
|
316
|
-
| `intervalMs` | `number` | Polling interval, 250–10000 ms; default 1500 ms |
|
|
317
|
-
| `onRefresh` | `() => void` | Create a new request from the expiry panel and replace the ticket |
|
|
318
|
-
|
|
319
|
-
| React callback / Vue event | Argument | Meaning |
|
|
320
|
-
| --- | --- | --- |
|
|
321
|
-
| `onConfirmed` / `confirmed` | `Confirmation` | Backend has verified and consumed the result |
|
|
322
|
-
| `onRejected` / `rejected` | `Rejection` | Phone rejected; dialog closes automatically |
|
|
323
|
-
| `onExpired` / `expired` | None | Request expired |
|
|
324
|
-
| `onClose` / `close` | None | Dialog closed; unmount the component / clear its ticket |
|
|
325
|
-
| `onError` / `error` | `Error` | Network, response validation or callback failure |
|
|
326
|
-
|
|
327
|
-
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.
|
|
328
|
-
|
|
329
|
-
`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.
|
|
330
|
-
|
|
331
|
-
### Backend contract
|
|
332
|
-
|
|
333
|
-
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.
|
|
334
|
-
|
|
335
|
-
```ts
|
|
336
|
-
import type { Ticket, Result } from '@auth-link/web';
|
|
337
|
-
|
|
338
|
-
// POST /api/authlink/requests
|
|
339
|
-
// Body: { purpose: 'bind' | 'confirm' }
|
|
340
|
-
// Response: Ticket
|
|
341
|
-
|
|
342
|
-
// POST /api/authlink/requests/{requestId}/result
|
|
343
|
-
// Body: {}
|
|
344
|
-
// Response: Result
|
|
345
|
-
```
|
|
346
|
-
|
|
347
|
-
```json
|
|
348
|
-
{
|
|
349
|
-
"status": "confirmed",
|
|
350
|
-
"requestId": "<request-id>",
|
|
351
|
-
"verificationId": "<verification-id>",
|
|
352
|
-
"purpose": "confirm",
|
|
353
|
-
"authenticationPolicy": "device-presence.v1",
|
|
354
|
-
"expiresAt": "<same-expiry-as-ticket>"
|
|
355
|
-
}
|
|
356
|
-
```
|
|
357
|
-
|
|
358
|
-
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.
|
|
359
|
-
|
|
360
|
-
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.
|
|
361
|
-
|
|
362
|
-
### Languages
|
|
58
|
+
### Errors and cleanup
|
|
363
59
|
|
|
364
|
-
|
|
365
|
-
| --- | --- |
|
|
366
|
-
| `en` | English |
|
|
367
|
-
| `zh-CN` | 简体中文 (default) |
|
|
368
|
-
| `zh-TW` | 繁體中文 |
|
|
369
|
-
| `ja` | 日本語 |
|
|
370
|
-
| `bn` | বাংলা |
|
|
371
|
-
| `es` | Español |
|
|
372
|
-
| `fil` | Filipino |
|
|
373
|
-
| `hi` | हिन्दी |
|
|
374
|
-
| `id` | Bahasa Indonesia |
|
|
375
|
-
| `ms` | Bahasa Melayu |
|
|
376
|
-
| `pt` | Português |
|
|
377
|
-
| `th` | ไทย |
|
|
378
|
-
| `vi` | Tiếng Việt |
|
|
60
|
+
A used code cannot authorize a second action, even in another session. After sign-in or first enrollment, wait for the next code. PASSCODE_INVALID/PASSCODE_USED/PASSCODE_LOCKED are validation errors, not success. Retain the same backend idempotency key and original code when a result is unknown; retries must not repeat the business action.
|
|
379
61
|
|
|
380
|
-
|
|
62
|
+
destroy() aborts browser work and clears timers without a close callback. close() also calls onClose. Closing a dialog does not roll back server work: your CMS must manage cancellation and its pending slot. Waiting and local expiry never poll.
|
|
381
63
|
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
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.
|
|
385
|
-
|
|
386
|
-
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.
|
|
387
|
-
|
|
388
|
-
| Import | Contents |
|
|
389
|
-
| --- | --- |
|
|
390
|
-
| `@auth-link/web` | Client, request key, supported locales, types and core tools |
|
|
391
|
-
| `@auth-link/web/react` | React components and hook |
|
|
392
|
-
| `@auth-link/web/vue` | Vue components and composable |
|
|
393
|
-
| `@auth-link/web/styles.css` | Component styles |
|
|
394
|
-
|
|
395
|
-
### Security and timing
|
|
396
|
-
|
|
397
|
-
- Matching numbers are for visual comparison with the app, not standalone passwords or authorization proofs.
|
|
398
|
-
- The browser receives only public tickets and current display frames, never generation seeds, device keys or tenant secrets.
|
|
399
|
-
- A request lasts at most 120 seconds; rotating the code does not extend it. Backend and app must support AuthLink mobile protocol 7.
|
|
400
|
-
- 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.
|
|
401
|
-
- Component unmount/request changes abort polling. Confirmation is deduplicated per mounted instance; your backend still needs persistent idempotence.
|
|
402
|
-
- Frontend callbacks update UI. Protected APIs must rely on trusted backend records, never a JavaScript callback or a browser-supplied success flag.
|
|
403
|
-
- 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.
|
|
404
|
-
|
|
405
|
-
### License
|
|
406
|
-
|
|
407
|
-
MIT. See `LICENSE` for the full license text and `THIRD_PARTY_NOTICES.md` for bundled third-party attribution.
|
|
408
|
-
|
|
409
|
-
### Go Vue CMS: en
|
|
410
|
-
|
|
411
|
-
This walkthrough follows a working Go CMS and Vue 3 integration. Example origins replace local deployment details; no test users, passwords or tenant credentials are required by these examples. Your website implements login, persistence and business routes. The web package displays and observes requests; the Go SDK calls AuthLink and validates receipts.
|
|
412
|
-
|
|
413
|
-
#### 1. Install and separate the three origins
|
|
414
|
-
|
|
415
|
-
| Role | Example origin | Configuration |
|
|
416
|
-
| --- | --- | --- |
|
|
417
|
-
| Vue | `https://cms.example.com` | `apiOrigin` is the Go backend below |
|
|
418
|
-
| Go CMS API | `https://cms-api.example.com` | `baseUrl=https://cms-api.example.com/api/authlink` |
|
|
419
|
-
| AuthLink API | `https://api.getauthlink.com` | Go SDK `Origin`; browser `authLinkOrigin` |
|
|
420
|
-
|
|
421
|
-
The AuthLink API uses production origin `https://api.getauthlink.com`; the Vue and Go CMS origins remain examples for your own website, not the AuthLink marketing site.
|
|
422
|
-
|
|
423
|
-
Register the Vue site's origin for the tenant. The Go SDK `Origin` and the API origin in an exported credential JSON identify the AuthLink API. Browser `baseUrl` targets your Go application API. Keep TenantID/APIKey in private backend configuration; public runtime configuration contains origins only.
|
|
424
|
-
|
|
425
|
-
```sh
|
|
426
|
-
npm install @auth-link/web@latest vue
|
|
427
|
-
# In your Go backend module, after unpacking the supplied Go SDK:
|
|
428
|
-
go mod edit -replace=authlink.local/sdk=./third_party/authlink-go
|
|
429
|
-
go mod edit -require=authlink.local/sdk@v0.0.0
|
|
430
|
-
go mod tidy
|
|
431
|
-
```
|
|
432
|
-
|
|
433
|
-
The Go SDK is supplied as source or a Go SDK archive from your AuthLink website, not a public Go module or an npm backend. Preserve its own go.mod and import `authlink "authlink.local/sdk"`. Initialize it with trusted `authlink.Config{Origin: authOrigin, TenantID: tenantID, APIKey: apiKey}` through `authlink.New`.
|
|
434
|
-
|
|
435
|
-
#### 2. Log in to the website and load its session
|
|
436
|
-
|
|
437
|
-
Your login route (the reference CMS uses `POST /api/login`) issues a Secure, HttpOnly session cookie. Fetch Go's `GET /api/session` with `credentials:'include'`; require `authenticated:true` and the current `csrf` value before opening requests. Otherwise return to your own login flow.
|
|
438
|
-
|
|
439
|
-
Here the JSON property is **csrf**, while the SDK option is **csrfToken**: use `csrfToken: () => session.value?.csrf ?? ''`. A backend is free to name the response property differently. Go generates and saves the token for that session and validates X-CSRF-Token on creation AND result polling. Never substitute a tenant key or matching number.
|
|
440
|
-
|
|
441
|
-
Two HTTPS subdomains under the same site are cross-origin but same-site. The reference API sets a host-only cookie with `SameSite=Strict; Secure; HttpOnly; Path=/`, without Domain. Requests still target the API host. For a truly cross-site setup, account for browser cookie policy as well as CORS.
|
|
442
|
-
|
|
443
|
-
#### 3. Configure Go CORS and application routes
|
|
444
|
-
|
|
445
|
-
```http
|
|
446
|
-
Access-Control-Allow-Origin: https://cms.example.com
|
|
447
|
-
Access-Control-Allow-Credentials: true
|
|
448
|
-
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS
|
|
449
|
-
Access-Control-Allow-Headers: Content-Type, X-CSRF-Token, Idempotency-Key
|
|
450
|
-
Vary: Origin
|
|
451
|
-
Cache-Control: no-store
|
|
452
|
-
```
|
|
453
|
-
|
|
454
|
-
Return these headers only for an exact allowed Vue origin, including allowed-origin error responses. Validate the origin/method/headers of OPTIONS and return 204 before requiring login or CSRF; authenticate and check CSRF/ownership on actual requests. Do not reflect arbitrary origins or use `*`. PUT is for CMS draft editing; narrow it to the routes you implement.
|
|
455
|
-
|
|
456
|
-
| Application route | Input | Output |
|
|
457
|
-
| --- | --- | --- |
|
|
458
|
-
| `GET /api/session` | — | `{authenticated:true, csrf:"…", subject:"…", username:"…"}`; logged out: `{authenticated:false}` |
|
|
459
|
-
| `POST /api/authlink/requests` | `{purpose:"bind"}` or `{purpose:"confirm",postId,version}`; `Idempotency-Key` | Public `Ticket` |
|
|
460
|
-
| `POST /api/authlink/requests/{id}/result` | `{}`; current session + CSRF | Pending status/displayCode or verified `confirmed` receipt |
|
|
461
|
-
| `POST /api/posts/{id}/publish` | `{requestId,version}`; current session + CSRF | `{ok:true}` after checking the saved confirmation and intent |
|
|
462
|
-
|
|
463
|
-
Your Go application implements all four routes. postId/version and the publication route are application-specific conventions, not AuthLink fields.
|
|
464
|
-
|
|
465
|
-
#### 4. Persist before creation; commit verification before confirmed
|
|
466
|
-
|
|
467
|
-
```text
|
|
468
|
-
Vue → Go /api/session → current session + csrf
|
|
469
|
-
Vue → Go /api/authlink/requests → Go SDK CreateRequest → public ticket
|
|
470
|
-
Vue dialog → Go /api/authlink/requests/{id}/result → Status + Consume
|
|
471
|
-
Go commits verified receipt → Vue confirmed event
|
|
472
|
-
Vue → Go /api/posts/{id}/publish → validate saved intent/receipt → publish
|
|
473
|
-
```
|
|
474
|
-
|
|
475
|
-
Derive the stable user ID from the authenticated session. Before an upstream call, validate purpose/idempotency and optional post ownership/version; independently generate state and a consume key, then persist CreateInput, the browser creation key, session/user and publication intent. A network retry loads the same record and keys. Enforce unique (session, creation key) and reject reuse for a different purpose/post/version.
|
|
476
|
-
|
|
477
|
-
Save the returned ticket, requestId and original expiresAt; omit optional qrSvg before returning public data. The result route locks the request owned by the current session and reuses any saved receipt. Call Status, then Consume only for approved/consumed using Expected reconstructed from saved data. Persist the verified public receipt, session confirmation and audit transactionally with unique requestId/verificationId constraints; commit before returning confirmed. Pending results preserve displayCode without caching beyond its validity.
|
|
478
|
-
|
|
479
|
-
This is the SDK-call layer, **not a complete HTTP server**. Your application must implement the database/transaction and ownership steps described above and in the comments.
|
|
480
|
-
|
|
481
|
-
```go
|
|
482
|
-
package cmsauth
|
|
483
|
-
|
|
484
|
-
import (
|
|
485
|
-
"context"
|
|
486
|
-
authlink "authlink.local/sdk"
|
|
487
|
-
)
|
|
488
|
-
|
|
489
|
-
// Load this record from your database for the authenticated user/session.
|
|
490
|
-
// Save Input (including State), CreateKey and ConsumeKey BEFORE calling Create.
|
|
491
|
-
// Intent (post ID/version), ownership and unique constraints belong in your DB.
|
|
492
|
-
type StoredRequest struct {
|
|
493
|
-
Input authlink.CreateInput
|
|
494
|
-
CreateKey string
|
|
495
|
-
ConsumeKey string
|
|
496
|
-
Ticket authlink.Ticket
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
// On network retries, load the SAME record; do not regenerate State or keys.
|
|
500
|
-
func Create(ctx context.Context, sdk *authlink.Client, saved StoredRequest) (authlink.Ticket, error) {
|
|
501
|
-
return sdk.CreateRequest(ctx, saved.Input, saved.CreateKey)
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
type PublicConfirmation struct {
|
|
505
|
-
Status string `json:"status"`
|
|
506
|
-
RequestID string `json:"requestId"`
|
|
507
|
-
VerificationID string `json:"verificationId"`
|
|
508
|
-
Purpose string `json:"purpose"`
|
|
509
|
-
ExpiresAt string `json:"expiresAt"`
|
|
510
|
-
AuthenticationPolicy string `json:"authenticationPolicy"`
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
// Caller checks session/CSRF/ownership, locks the saved record and first returns
|
|
514
|
-
// any already-saved receipt. For a new confirmed result, caller must persist
|
|
515
|
-
// the receipt and confirmation in a DB transaction BEFORE returning HTTP 200.
|
|
516
|
-
func Poll(ctx context.Context, sdk *authlink.Client, saved StoredRequest) (any, error) {
|
|
517
|
-
status, err := sdk.Status(ctx, saved.Ticket.RequestID)
|
|
518
|
-
if err != nil { return nil, err }
|
|
519
|
-
if status.Status != "approved" && status.Status != "consumed" { return status, nil }
|
|
520
|
-
result, err := sdk.Consume(ctx, authlink.Expected{
|
|
521
|
-
RequestID: saved.Ticket.RequestID,
|
|
522
|
-
ExternalUserID: saved.Input.ExternalUserID,
|
|
523
|
-
Purpose: saved.Input.Purpose,
|
|
524
|
-
State: saved.Input.State,
|
|
525
|
-
ExpiresAt: saved.Ticket.ExpiresAt,
|
|
526
|
-
}, saved.ConsumeKey)
|
|
527
|
-
if err != nil { return nil, err }
|
|
528
|
-
return PublicConfirmation{
|
|
529
|
-
Status: "confirmed", RequestID: result.RequestID,
|
|
530
|
-
VerificationID: result.VerificationID, Purpose: result.Purpose,
|
|
531
|
-
ExpiresAt: saved.Ticket.ExpiresAt, AuthenticationPolicy: result.AuthenticationPolicy,
|
|
532
|
-
}, nil
|
|
533
|
-
}
|
|
534
|
-
```
|
|
535
|
-
|
|
536
|
-
#### 5. Vue lifecycle and business-bound requests
|
|
537
|
-
|
|
538
|
-
The complete file is also shipped as `examples/vue-cms.vue`. Mount after site login with trusted apiOrigin/authLinkOrigin and an optional saved draft `post={id,version}`. Key the parent component by the current authenticated session identity. Unmount on logout, login rotation or account change; clear old tickets, creation keys and pending publication before mounting a new instance.
|
|
539
|
-
|
|
540
|
-
```vue
|
|
541
|
-
<script setup lang="ts">
|
|
542
|
-
import { markRaw, onMounted, onUnmounted, ref, shallowRef } from 'vue';
|
|
543
|
-
import { createAuthLinkClient, requestKey, validateTicket } from '@auth-link/web';
|
|
544
|
-
import type { Confirmation, Mode, Ticket } from '@auth-link/web';
|
|
545
|
-
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/vue';
|
|
546
|
-
import '@auth-link/web/styles.css';
|
|
547
|
-
|
|
548
|
-
type Post = { id: string; version: number };
|
|
549
|
-
type Publication = Post & { requestId: string };
|
|
550
|
-
// Supply trusted deployment configuration. Mount after site login and remount
|
|
551
|
-
// with :key="session.subject" after login, logout or account/session changes.
|
|
552
|
-
const props = defineProps<{ apiOrigin: string; authLinkOrigin: string; post?: Post }>();
|
|
553
|
-
const session = ref<{ authenticated: boolean; csrf?: string } | null>(null);
|
|
554
|
-
const ticket = shallowRef<Ticket | null>(null);
|
|
555
|
-
const publication = shallowRef<Post | null>(null);
|
|
556
|
-
const retryPublish = shallowRef<Publication | null>(null);
|
|
557
|
-
const busy = ref(false), message = ref('');
|
|
558
|
-
let creation: { signature: string; key: string } | null = null;
|
|
559
|
-
const lifetime = new AbortController();
|
|
560
|
-
const client = markRaw(createAuthLinkClient({
|
|
561
|
-
baseUrl: `${props.apiOrigin}/api/authlink`,
|
|
562
|
-
allowedBackendOrigins: [props.apiOrigin],
|
|
563
|
-
credentials: 'include',
|
|
564
|
-
csrfToken: () => session.value?.csrf ?? '',
|
|
565
|
-
authLinkOrigin: props.authLinkOrigin,
|
|
566
|
-
}));
|
|
567
|
-
|
|
568
|
-
async function api(path: string, body?: unknown, headers: Record<string, string> = {}) {
|
|
569
|
-
const response = await fetch(`${props.apiOrigin}${path}`, {
|
|
570
|
-
method: body === undefined ? 'GET' : 'POST',
|
|
571
|
-
credentials: 'include', cache: 'no-store', redirect: 'error',
|
|
572
|
-
signal: lifetime.signal,
|
|
573
|
-
headers: body === undefined ? {} : {
|
|
574
|
-
'Content-Type': 'application/json', 'X-CSRF-Token': session.value?.csrf ?? '', ...headers,
|
|
575
|
-
},
|
|
576
|
-
body: body === undefined ? undefined : JSON.stringify(body),
|
|
577
|
-
});
|
|
578
|
-
const value = await response.json();
|
|
579
|
-
if (response.status === 401) {
|
|
580
|
-
session.value = null; closeTicket(); retryPublish.value = null; creation = null;
|
|
581
|
-
}
|
|
582
|
-
if (!response.ok) throw new Error(value.code ?? 'REQUEST_FAILED');
|
|
583
|
-
return value;
|
|
584
|
-
}
|
|
585
|
-
function closeTicket() { ticket.value = null; publication.value = null; }
|
|
586
|
-
function showError(error: Error) { message.value = error.message; }
|
|
587
|
-
function finish(text: string) { closeTicket(); message.value = text; }
|
|
588
|
-
|
|
589
|
-
async function start(purpose: Mode, post?: Post) {
|
|
590
|
-
if (busy.value || ticket.value || !session.value?.authenticated) return;
|
|
591
|
-
busy.value = true; message.value = ''; retryPublish.value = null;
|
|
592
|
-
const intent = post ? { id: post.id, version: post.version } : null;
|
|
593
|
-
const signature = JSON.stringify({ purpose, postId: intent?.id, version: intent?.version });
|
|
594
|
-
try {
|
|
595
|
-
if (creation?.signature !== signature) creation = { signature, key: requestKey() };
|
|
596
|
-
// SDK create() sends only {purpose}. Business fields use your own API.
|
|
597
|
-
const value = intent
|
|
598
|
-
? validateTicket(await api('/api/authlink/requests', {
|
|
599
|
-
purpose, postId: intent.id, version: intent.version,
|
|
600
|
-
}, { 'Idempotency-Key': creation.key }), purpose, props.authLinkOrigin)
|
|
601
|
-
: await client.create(purpose, { idempotencyKey: creation.key, signal: lifetime.signal });
|
|
602
|
-
if (lifetime.signal.aborted) return;
|
|
603
|
-
publication.value = intent; ticket.value = value; creation = null;
|
|
604
|
-
} catch (error) {
|
|
605
|
-
if (!lifetime.signal.aborted) showError(error as Error);
|
|
606
|
-
// Retain creation.key for a retry of the SAME purpose/post/version.
|
|
607
|
-
} finally { busy.value = false; }
|
|
608
|
-
}
|
|
609
|
-
async function publish() {
|
|
610
|
-
const intent = retryPublish.value;
|
|
611
|
-
if (!intent || busy.value) return;
|
|
612
|
-
busy.value = true;
|
|
613
|
-
try {
|
|
614
|
-
await api(`/api/posts/${intent.id}/publish`, { version: intent.version, requestId: intent.requestId });
|
|
615
|
-
retryPublish.value = null; message.value = 'Published. Reload your posts from the backend.';
|
|
616
|
-
} catch (error) { if (!lifetime.signal.aborted) showError(error as Error); }
|
|
617
|
-
finally { busy.value = false; }
|
|
618
|
-
}
|
|
619
|
-
async function confirmed(result: Confirmation) {
|
|
620
|
-
const intent = publication.value;
|
|
621
|
-
closeTicket();
|
|
622
|
-
if (intent) { retryPublish.value = { ...intent, requestId: result.requestId }; await publish(); }
|
|
623
|
-
else message.value = 'Verified. Reload account status from the backend.';
|
|
624
|
-
}
|
|
625
|
-
onMounted(async () => {
|
|
626
|
-
try {
|
|
627
|
-
const value = await api('/api/session');
|
|
628
|
-
if (value.authenticated !== true || typeof value.csrf !== 'string' || !value.csrf) {
|
|
629
|
-
throw new Error('LOGIN_REQUIRED');
|
|
630
|
-
}
|
|
631
|
-
session.value = value;
|
|
632
|
-
} catch (error) { if (!lifetime.signal.aborted) showError(error as Error); }
|
|
633
|
-
});
|
|
634
|
-
onUnmounted(() => { lifetime.abort(); closeTicket(); creation = null; retryPublish.value = null; });
|
|
635
|
-
</script>
|
|
636
|
-
|
|
637
|
-
<template>
|
|
638
|
-
<button :disabled="busy || !!ticket || !session?.authenticated" @click="start('bind')">Bind phone</button>
|
|
639
|
-
<button :disabled="busy || !!ticket || !session?.authenticated" @click="start('confirm')">Confirm</button>
|
|
640
|
-
<button v-if="post" :disabled="busy || !!ticket || !session?.authenticated" @click="start('confirm', post)">Confirm publication</button>
|
|
641
|
-
<button v-if="retryPublish" :disabled="busy || !!ticket" @click="publish">Retry the same publication</button>
|
|
642
|
-
<AuthLinkBind v-if="ticket?.purpose === 'bind'" :ticket="ticket" :client="client" variant="B"
|
|
643
|
-
@confirmed="confirmed" @close="finish('Closed')" @rejected="finish('Rejected')"
|
|
644
|
-
@expired="finish('Expired; start a new request')" @error="showError" />
|
|
645
|
-
<AuthLinkConfirm v-else-if="ticket?.purpose === 'confirm'" :ticket="ticket" :client="client" variant="B"
|
|
646
|
-
@confirmed="confirmed" @close="finish('Closed')" @rejected="finish('Rejected')"
|
|
647
|
-
@expired="finish('Expired; start a new request')" @error="showError" />
|
|
648
|
-
<p role="status">{{ message }}</p>
|
|
649
|
-
</template>
|
|
650
|
-
```
|
|
651
|
-
|
|
652
|
-
`client.create(purpose, {idempotencyKey})` sends purpose only. To bind confirmation to a post/version, use your own fetch with those business fields, validate the result with `validateTicket(response, 'confirm', authLinkOrigin)`, and reuse the official client for observation. Keep the same creation key after an uncertain failure, and change it when purpose/post/version changes. Keep tickets in shallowRef and clients in markRaw.
|
|
653
|
-
|
|
654
|
-
Mounting a dialog observes an existing request; never create from mounted/watch. Clear the ticket on close/rejection/expiry. Leave the dialog mounted on network errors to retry that request. On confirmation, dismiss it and call the independent publish route; preserve the same requestId/post/version if that call fails. Reload actual account/post state from the backend. The sample omits your login form, post list and application error translations.
|
|
655
|
-
|
|
656
|
-
#### 6. Recheck confirmation in the publish transaction
|
|
657
|
-
|
|
658
|
-
The browser confirmed event is not authorization. Go must load the verified receipt for the current session and check purpose=confirm, intent=publish, post ownership, the same postId/version, draft state and expiry on first application. Update the post and mark the intent applied atomically. A retry of that same applied operation returns success without duplicate publication/audit. Another post or edited version requires a new confirmation. Do not add action, transactionHash or document content to the AuthLink receipt.
|
|
659
|
-
|
|
660
|
-
#### Acceptance sequence
|
|
661
|
-
|
|
662
|
-
Site login → session bootstrap → backend AccountStatus (the reference CMS exposes it through overview) → bind if unbound → phone approval → consume and refresh account status → save draft → confirm that post/version → phone approval → commit receipt → publish → verify duplicate retry, wrong version, rejection and expiry. Real phone approval remains a separate acceptance step; compilation and mock HTTP checks do not replace it.
|
|
64
|
+
The older openAuthLink / Ticket / Consume workflow remains available for the earlier protocol; new apps use openPasscode / AuthLinkPasscode and the backend Authenticate/authenticate method. No old-binding migration is provided.
|
|
663
65
|
|
|
664
66
|
---
|
|
665
67
|
|
|
666
68
|
## 简体中文
|
|
667
69
|
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
### Go + Vue 完整接入
|
|
671
|
-
|
|
672
|
-
按实际 CMS 流程接入,推荐先读 [Go + Vue:从登录、绑定到确认发布](#go-vue-cms-zh-cn),完整组件见 `examples/vue-cms.vue`。
|
|
673
|
-
|
|
674
|
-
顺序是:网站登录 → Go `/api/session` 返回 `authenticated` 与 `csrf` → Vue 通过 `csrfToken: () => session.csrf` 配置跨域客户端 → 创建 bind/confirm → Go 验证并消费结果后落库 → Vue 清理弹窗 → 独立业务接口再校验已保存回执并发布。`baseUrl` 是 Go 业务 API,`authLinkOrigin` 是 AuthLink API;租户密钥始终留在 Go 后台。带文章 ID/版本的确认通过网站自己的 fetch 创建并用 `validateTicket` 校验,SDK 的 `create` 只发送 purpose。
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
### 功能
|
|
678
|
-
|
|
679
|
-
- **扫码绑定**:网站显示二维码,用户使用 AuthLink App 扫码并确认绑定。
|
|
680
|
-
- **手机确认**:电脑与 App 显示同步变化的六位数字,每 30 秒更新,用户核对后在 App 内批准。
|
|
681
|
-
- **结果通知**:提供确认成功、拒绝、过期和错误事件,方便网站更新界面。
|
|
682
|
-
- **框架支持**:React 组件与 hook、Vue 组件与 composable,以及无框架客户端。
|
|
683
|
-
- **多语言与主题**:支持下表中的 13 种语言,默认简体中文;独立 CSS 和可覆盖的主题变量。
|
|
684
|
-
- **生命周期管理**:请求切换或组件卸载时取消轮询,数字过期后自动隐藏。
|
|
685
|
-
|
|
686
|
-
此包是 AuthLink 的网页接入层,需要配套应用后台、AuthLink 服务和手机 App。完整 AuthLink 流程校验原手机硬件密钥证明及 App 内批准,不要求系统通行密钥、指纹或锁屏;安装此包本身不会建立鉴权服务。
|
|
687
|
-
|
|
688
|
-
### 接入步骤
|
|
689
|
-
|
|
690
|
-
1. 在应用后台完成站点租户配置,并实现本文的创建请求、查询结果两个业务后台接口(同源或显式配置的跨域后台)。
|
|
691
|
-
2. 安装包、导入样式,创建指向应用后台的客户端。
|
|
692
|
-
3. 用户点击绑定或验证时创建请求,将返回的 ticket 交给 React/Vue 组件。
|
|
693
|
-
4. 用户在 App 确认后,应用后台验证并消费结果,组件收到可信确认事件。
|
|
694
|
-
|
|
695
|
-
租户密钥只保存在应用服务端。用户是否能够继续调用受保护接口,也必须由应用后台判断。
|
|
696
|
-
|
|
697
|
-
### 流程
|
|
698
|
-
|
|
699
|
-
应用后台根据当前登录用户创建 `bind` 或 `confirm` 请求,前端拿到 ticket 后交给组件。组件只轮询应用后台。应用后台在验证归属、state、双重认证策略并消费一次性结果后,才返回 `confirmed`。
|
|
700
|
-
|
|
701
|
-
定时数字用于电脑与手机核对;用户仍在 AuthLink App 内完成 原手机硬件密钥校验和 App 内批准。它不是用户输入网站的 TOTP 登录密码,不能单独授权。请求最长 120 秒;数字变化不延长请求有效期。前端不生成数字、不接收生成 seed,不在数字更新时新建请求。
|
|
702
|
-
|
|
703
|
-
需要配套更新后的 Go 服务和客户端协议 7。服务端与 App 必须使用当前单一协议,不能只升级网页。
|
|
70
|
+
### 直接验证动态码
|
|
704
71
|
|
|
705
|
-
|
|
72
|
+
App 直接显示六位动态码。日常验证不需要逐次批准、授权 requestId、businessId 或轮询。首次绑定仍需扫码验证设备,在网站输入 App 当前动态码后才完成绑定。
|
|
706
73
|
|
|
707
|
-
|
|
74
|
+
打开弹窗前,CMS 后台必须为会话原子保留唯一且不可变的待办。其他标签页不能覆盖它。用户来自服务端会话,后台检查 CSRF、业务权限和原表单,验证动态码后将 verificationId 与原操作原子提交,再返回成功。onVerified 只更新界面。
|
|
708
75
|
|
|
709
76
|
```sh
|
|
710
|
-
npm install @auth-link/web
|
|
77
|
+
npm install @auth-link/web@^1.1.0
|
|
711
78
|
```
|
|
712
79
|
|
|
713
|
-
### 创建应用客户端(默认同源 Cookie 模式)
|
|
714
|
-
|
|
715
|
-
`readCsrfTokenFromYourCms` 是接入方函数,不是包里的导出;名称不要求与你的网站框架一致,也不要求使用 CMS。它只读取**你的网站后台提供的 CSRF token**,用于保护携带登录 cookie 的请求,不是 AuthLink 租户 API key、登录 cookie 或手机核对码。
|
|
716
|
-
|
|
717
|
-
下面采用页面 meta 标签的方式。后台需要先准备 token:
|
|
718
|
-
|
|
719
|
-
1. 优先复用网站框架现有的 CSRF 机制;没有现成机制时,在服务端为当前登录 session 生成并保存密码学安全随机 token,例如 Node 的 `randomBytes(32).toString('base64url')`。不要在浏览器随机生成一个值,也不要使用所有用户共用的固定字符串。
|
|
720
|
-
2. 服务端使用当前 session 的 token 渲染下面的标签,正确转义 HTML 属性;`{{ csrfToken }}` 表示服务器模板变量,不是可直接照抄的 token。包含会话 token 的页面不能被公开缓存。
|
|
721
|
-
3. 创建和查询接口都读取 `X-CSRF-Token`,与同一登录 session 保存的 token 校验;缺失、不匹配或请求来源不符合网站要求时拒绝请求。仅让前端发送这个头,并不会自动启用后台校验。
|
|
722
|
-
4. 登录、退出或会话/token 更新后,让页面重新取得当前 token。SPA 也可以由网站实现同源会话初始化接口返回 token,再通过 `csrfToken` 回调提供;这不是 SDK 自带接口。
|
|
723
|
-
|
|
724
|
-
```html
|
|
725
|
-
<!-- 由你的网站后台渲染到当前用户的页面 head 中 -->
|
|
726
|
-
<meta name="csrf-token" content="{{ csrfToken }}">
|
|
727
|
-
```
|
|
728
|
-
|
|
729
|
-
新建 `authlink-client.ts`:
|
|
730
|
-
|
|
731
80
|
```ts
|
|
732
|
-
|
|
733
|
-
import { createAuthLinkClient } from '@auth-link/web';
|
|
81
|
+
import { openPasscode, createPasscodeClient } from '@auth-link/web';
|
|
734
82
|
import '@auth-link/web/styles.css';
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
return token;
|
|
742
|
-
}
|
|
743
|
-
|
|
744
|
-
export const client = createAuthLinkClient({
|
|
745
|
-
baseUrl: '/api/authlink',
|
|
746
|
-
csrfToken: readCsrfTokenFromYourCms,
|
|
747
|
-
// AuthLink production API origin.
|
|
748
|
-
authLinkOrigin: 'https://api.getauthlink.com',
|
|
83
|
+
const client = createPasscodeClient({ baseUrl: '/api', csrfToken: () => csrfToken });
|
|
84
|
+
const modal = openPasscode({
|
|
85
|
+
client, expiresAt: pending.expiresAt, locale: 'zh-CN', variant: 'B',
|
|
86
|
+
// First-time enrollment only:
|
|
87
|
+
// bindingQr: pending.bindingQr, authLinkOrigin: 'https://api.getauthlink.com',
|
|
88
|
+
onVerified: result => updateUI(result.verificationId),
|
|
749
89
|
});
|
|
90
|
+
// modal.setLocale('en'); modal.setVariant('C'); modal.destroy();
|
|
750
91
|
```
|
|
751
92
|
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
`create` 只传用途,网站账号由后台登录 session 决定。客户端通常只初始化一次;用户点击按钮时才创建请求。完整调用见下方 React 示例,不要把 `client.create()` 放在模块加载、React effect 或 Vue watch 中。
|
|
755
|
-
|
|
756
|
-
### 前后端分离与跨域后台(0.0.2 起)
|
|
93
|
+
默认客户端向 CMS 的 POST /api/auth 提交 {passcode},携带当前会话与 CSRF。要随表单提交,可自行实现 client.verify,向 CMS 发送 {form,passcode};后台核对原保存快照。租户密钥与动态码密钥不能进入浏览器。
|
|
757
94
|
|
|
758
|
-
|
|
95
|
+
### 选项与回调
|
|
759
96
|
|
|
760
|
-
|
|
97
|
+
必填:client.verify(passcode, signal)、expiresAt(CMS 待办截止时间)。可选:locale、variant A/B/C、仅首次绑定使用的 bindingQr 与 authLinkOrigin、onVerified、onError、onClose、onExpired。成功结果含 status、verificationId、authenticationPolicy、expiresAt,不含 requestId 或 businessId。
|
|
761
98
|
|
|
762
|
-
|
|
99
|
+
Cookie 模式必须配置 CSRF。Bearer 模式配置 accessToken 且 credentials=omit。跨域 CMS 必须显式配置 allowedBackendOrigins;回环开发之外使用 HTTPS。
|
|
763
100
|
|
|
764
|
-
|
|
101
|
+
### React 与 Vue
|
|
765
102
|
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
```ts
|
|
769
|
-
import { createAuthLinkClient } from '@auth-link/web';
|
|
770
|
-
|
|
771
|
-
/** /api/session is an example endpoint implemented by your application backend. */
|
|
772
|
-
export async function createSessionBackendClient(backendOrigin: string) {
|
|
773
|
-
const response = await fetch(`${backendOrigin}/api/session`, {
|
|
774
|
-
credentials: 'include', cache: 'no-store', redirect: 'error',
|
|
775
|
-
});
|
|
776
|
-
if (!response.ok) throw new Error('Session initialization failed');
|
|
777
|
-
const session: unknown = await response.json();
|
|
778
|
-
if (!session || typeof session !== 'object' || !('csrfToken' in session) ||
|
|
779
|
-
typeof session.csrfToken !== 'string' || !session.csrfToken) {
|
|
780
|
-
throw new Error('The session endpoint must return { csrfToken: string }');
|
|
781
|
-
}
|
|
782
|
-
let currentCsrfToken = session.csrfToken;
|
|
783
|
-
return {
|
|
784
|
-
client: createAuthLinkClient({
|
|
785
|
-
baseUrl: `${backendOrigin}/api/authlink`,
|
|
786
|
-
allowedBackendOrigins: [backendOrigin],
|
|
787
|
-
credentials: 'include',
|
|
788
|
-
csrfToken: () => currentCsrfToken,
|
|
789
|
-
}),
|
|
790
|
-
// Call after your application's session/token refresh; recreate on account changes.
|
|
791
|
-
updateCsrfToken(value: string) { currentCsrfToken = value; },
|
|
792
|
-
};
|
|
793
|
-
}
|
|
794
|
-
```
|
|
795
|
-
|
|
796
|
-
登录后调用 `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 策略的开关。
|
|
797
|
-
|
|
798
|
-
#### 跨域 Bearer token / JWT
|
|
799
|
-
|
|
800
|
-
传入网站自己的登录状态对象;网站完成登录或刷新后更新这个对象的 `accessToken`。回调会在每次创建和轮询时重新读取最新 token,无需重建弹窗。
|
|
801
|
-
|
|
802
|
-
```ts
|
|
803
|
-
import { createAuthLinkClient } from '@auth-link/web';
|
|
804
|
-
|
|
805
|
-
/** auth is your website's existing login state, updated by its login/refresh flow. */
|
|
806
|
-
export function createBearerBackendClient(backendOrigin: string, auth: { accessToken: string }) {
|
|
807
|
-
return createAuthLinkClient({
|
|
808
|
-
baseUrl: `${backendOrigin}/api/authlink`,
|
|
809
|
-
allowedBackendOrigins: [backendOrigin],
|
|
810
|
-
credentials: 'omit',
|
|
811
|
-
accessToken: () => auth.accessToken,
|
|
812
|
-
});
|
|
813
|
-
}
|
|
814
|
-
```
|
|
815
|
-
|
|
816
|
-
`accessToken` 必须是接入网站的用户登录 token,不能是 AuthLink 租户 API key。SDK 自动添加 `Authorization: Bearer ...`。纯 Bearer 模式默认 `credentials: 'omit'`,可不传 `csrfToken`;后台应仅按 Bearer token 认证,不回退到 Cookie 登录。若显式设置 `credentials: 'include'` 或 `'same-origin'` 混用 Cookie,仍须提供并校验 `csrfToken`。
|
|
817
|
-
|
|
818
|
-
#### 后台 CORS 配置
|
|
819
|
-
|
|
820
|
-
后台需处理浏览器发出的 `OPTIONS` 预检,并在预检、实际响应和错误响应中返回相应 CORS 头。会话初始化接口也需要这些设置。以下假设前端来源是 `https://www.example.com`:
|
|
821
|
-
|
|
822
|
-
```http
|
|
823
|
-
Access-Control-Allow-Origin: https://www.example.com
|
|
824
|
-
Access-Control-Allow-Credentials: true
|
|
825
|
-
Access-Control-Allow-Methods: GET, POST, OPTIONS
|
|
826
|
-
Access-Control-Allow-Headers: Content-Type, X-CSRF-Token, Idempotency-Key, Authorization
|
|
827
|
-
Vary: Origin
|
|
828
|
-
```
|
|
829
|
-
|
|
830
|
-
携带 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)。
|
|
831
|
-
|
|
832
|
-
#### 请求客户端配置
|
|
833
|
-
|
|
834
|
-
| 配置 | 说明 |
|
|
835
|
-
| --- | --- |
|
|
836
|
-
| `baseUrl` | 业务后台前缀,默认 `/api/authlink`;跨域时填写完整地址 |
|
|
837
|
-
| `allowedBackendOrigins` | 额外允许的精确后台来源数组,默认只允许当前网页同源 |
|
|
838
|
-
| `credentials` | Cookie 模式默认 `same-origin`;提供 `accessToken` 时默认 `omit`;跨域 Cookie 显式设置 `include` |
|
|
839
|
-
| `csrfToken` | 每次请求读取 CSRF token 的同步或异步函数;Cookie 模式必填 |
|
|
840
|
-
| `csrfHeaderName` | CSRF 请求头名,默认 `X-CSRF-Token`,例如可设为 `X-XSRF-TOKEN` |
|
|
841
|
-
| `accessToken` | 每次请求读取网站 Bearer token 的同步或异步函数;不要包含 `Bearer ` 前缀 |
|
|
842
|
-
| `headers` | 额外的 `HeadersInit` 或返回它的同步/异步函数,可传工作区等自定义头 |
|
|
843
|
-
| `authLinkOrigin` | 核对二维码中的 AuthLink 服务来源,与业务后台来源独立 |
|
|
844
|
-
| `fetch` | 可选 fetch 实现;仍受目标来源和协议校验约束 |
|
|
845
|
-
|
|
846
|
-
SDK 管理 `Accept`、`Content-Type`、`Authorization`、`Idempotency-Key` 和配置的 CSRF 头,`headers` 不能覆盖这些字段,否则报 `RESERVED_HEADER`。用 `accessToken` 设置 Bearer token,用 `csrfHeaderName` 适配后台框架。`ClientOptions` 可从根入口导入为 TypeScript 类型。
|
|
847
|
-
|
|
848
|
-
未授权来源报 `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`,具体原因需查看浏览器开发者工具。
|
|
849
|
-
|
|
850
|
-
### 直接调用弹窗(React、Vue 或原生 JavaScript)
|
|
851
|
-
|
|
852
|
-
```ts
|
|
853
|
-
import { openAuthLinkBind, openAuthLinkConfirm, requestKey } from '@auth-link/web';
|
|
854
|
-
import { client } from './authlink-client';
|
|
855
|
-
import '@auth-link/web/styles.css';
|
|
856
|
-
|
|
857
|
-
// 在按钮事件中创建请求,再打开弹窗;client 为上文 authlink-client.ts 导出的同源客户端。
|
|
858
|
-
const ticket = await client.create('confirm', { idempotencyKey: requestKey() });
|
|
859
|
-
const modal = openAuthLinkConfirm({
|
|
860
|
-
ticket, client, locale: 'zh-CN',
|
|
861
|
-
onConfirmed: result => console.log(result.requestId),
|
|
862
|
-
onRejected: result => console.log(result.code), // REJECTED,此时弹窗已关闭
|
|
863
|
-
onClose: () => console.log('已关闭'),
|
|
864
|
-
});
|
|
865
|
-
// 绑定使用 openAuthLinkBind({ ticket: bindingTicket, client })。
|
|
866
|
-
// modal.close(); modal.setLocale('ja');
|
|
867
|
-
```
|
|
868
|
-
|
|
869
|
-
React / Vue 的 AuthLinkBind、AuthLinkConfirm 挂载后也直接打开弹窗,不再内嵌在页面。React 用 onClose、Vue 用 @close 清空 ticket 并卸载组件。服务端渲染不创建弹窗或请求。支持手机窄屏、内容滚动、关闭按钮及 Escape;要求浏览器支持原生 dialog.showModal()。弹窗挂到 document.body,主题变量请配置在 :root 或 .authlink-dialog。
|
|
870
|
-
|
|
871
|
-
关闭只停止前端查询,不拒绝或撤销服务端请求;请求仍按原有效期结束。确认成功或拒绝后弹窗自动关闭,分别回调 onConfirmed 或 onRejected,不触发用户关闭回调。直接调用时,页面卸载须执行 modal.destroy() 清理,它不触发用户关闭回调。切换语言用 modal.setLocale(),不会重建鉴权请求。
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
### React
|
|
875
|
-
|
|
876
|
-
下面的 `showBound` 也是接入方函数,负责更新页面提示和清空 `ticket`,从而卸载弹窗;它不向后台提交“绑定成功”,也不保存绑定。绑定及确认记录必须在后台查询结果接口验证、消费并保存后,才返回 `confirmed`。
|
|
877
|
-
|
|
878
|
-
这个示例包含按钮、请求创建、结果提示和弹窗清理,不再依赖未定义的 `showBound`、`showRejected` 等函数。使用 `<AuthLinkPanel mode="bind" />` 绑定,使用 `<AuthLinkPanel mode="confirm" />` 请求手机确认。
|
|
103
|
+
React 组件使用相同选项,Vue 发出 verified、error、close、expired 事件。client 引用需保持稳定。支持 13 种语言,默认简体中文;A 极简、B 分栏、C 紧凑。
|
|
879
104
|
|
|
880
105
|
```tsx
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/react';
|
|
886
|
-
import { client } from './authlink-client';
|
|
887
|
-
|
|
888
|
-
export function AuthLinkPanel({ mode }: { mode: Mode }) {
|
|
889
|
-
const [ticket, setTicket] = useState<Ticket | null>(null);
|
|
890
|
-
const [busy, setBusy] = useState(false);
|
|
891
|
-
const [message, setMessage] = useState('');
|
|
892
|
-
const key = useRef<string | null>(null);
|
|
893
|
-
const creating = useRef(false);
|
|
894
|
-
function finish(message: string) {
|
|
895
|
-
setTicket(null);
|
|
896
|
-
setMessage(message);
|
|
897
|
-
}
|
|
898
|
-
function showBound(requestId: string) {
|
|
899
|
-
// UI feedback only. The backend has already verified and saved the binding.
|
|
900
|
-
finish(`手机绑定成功(请求 ${requestId})`);
|
|
901
|
-
}
|
|
902
|
-
function showConfirmed(requestId: string) {
|
|
903
|
-
finish(`手机确认成功(请求 ${requestId})`);
|
|
904
|
-
}
|
|
905
|
-
const start = async () => {
|
|
906
|
-
if (creating.current || ticket) return;
|
|
907
|
-
creating.current = true;
|
|
908
|
-
setBusy(true);
|
|
909
|
-
setMessage('');
|
|
910
|
-
try {
|
|
911
|
-
key.current ??= requestKey();
|
|
912
|
-
setTicket(await client.create(mode, { idempotencyKey: key.current }));
|
|
913
|
-
key.current = null;
|
|
914
|
-
} catch { setMessage('请求未完成,可重试同一次创建。'); }
|
|
915
|
-
finally { creating.current = false; setBusy(false); }
|
|
916
|
-
};
|
|
917
|
-
const Component = mode === 'bind' ? AuthLinkBind : AuthLinkConfirm;
|
|
918
|
-
return <>
|
|
919
|
-
{!ticket && <button type="button" disabled={busy} onClick={() => void start()}>开始验证</button>}
|
|
920
|
-
{ticket && <Component ticket={ticket} client={client}
|
|
921
|
-
onConfirmed={result => result.purpose === 'bind' ? showBound(result.requestId) : showConfirmed(result.requestId)}
|
|
922
|
-
onClose={() => finish('已关闭')}
|
|
923
|
-
onRejected={() => finish('手机已拒绝本次请求')}
|
|
924
|
-
onExpired={() => finish('请求已过期,请重新发起')}
|
|
925
|
-
onError={error => setMessage(error.message)} />}
|
|
926
|
-
<p role="status">{message}</p>
|
|
927
|
-
</>;
|
|
928
|
-
}
|
|
106
|
+
import { AuthLinkPasscode } from '@auth-link/web/react';
|
|
107
|
+
// Keep client stable (for example with useMemo).
|
|
108
|
+
<AuthLinkPasscode client={client} expiresAt={pending.expiresAt}
|
|
109
|
+
locale="zh-CN" variant="B" onVerified={updateUI} />
|
|
929
110
|
```
|
|
930
|
-
|
|
931
|
-
`requestId` 用于展示或追踪本次请求,不是授权凭据。`showBound` 也可以按网站需求显示 toast、重新查询已有的账号状态接口或导航到绑定管理页。刷新页面后,应重新从后台读取真实绑定状态,不能只依赖 React state 或 localStorage。其他业务接口仍需在后台检查权限。
|
|
932
|
-
|
|
933
|
-
创建失败时示例保留同一个幂等键;再次点击会重试同一次创建。创建成功后清空幂等键,新的用户操作才创建新请求。关闭、成功、拒绝和过期都会清空 ticket;网络错误保留弹窗,供其重试当前请求。
|
|
934
|
-
|
|
935
|
-
确认组件默认只显示动态数字;`showQr` 可额外显示扫码入口。绑定组件始终显示二维码。`onRefresh` 可提供重新创建请求的函数;仅过期后显示该按钮。组件自身的“重试”只恢复当前请求,不创建第二个请求。
|
|
936
|
-
|
|
937
|
-
未指定 `locale` 时使用简体中文;不支持的语言代码也回退到简体中文。组件根元素设置对应的 `lang`,语言切换不会重新创建鉴权请求。
|
|
938
|
-
|
|
939
|
-
React 入口保留 `"use client"`,可用于 Next.js 客户端组件。导入包和 SSR 渲染不会创建请求。将 client 与 ticket 保持为稳定对象,例如模块级 client 和 React state 中的 ticket。卸载/切换 ticket 会取消旧轮询;StrictMode 不会创建额外请求。
|
|
940
|
-
|
|
941
|
-
### Vue
|
|
942
|
-
|
|
943
111
|
```vue
|
|
944
|
-
<script setup
|
|
945
|
-
import {
|
|
946
|
-
import { requestKey } from '@auth-link/web';
|
|
947
|
-
import type { Confirmation, Mode, Ticket } from '@auth-link/web';
|
|
948
|
-
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/vue';
|
|
949
|
-
import { client } from './authlink-client';
|
|
950
|
-
const props = defineProps<{ mode: Mode }>();
|
|
951
|
-
const ticket = shallowRef<Ticket | null>(null);
|
|
952
|
-
const busy = ref(false);
|
|
953
|
-
const message = ref('');
|
|
954
|
-
let key: string | null = null;
|
|
955
|
-
function finish(text: string) { ticket.value = null; message.value = text; }
|
|
956
|
-
function confirmed(result: Confirmation) {
|
|
957
|
-
finish(`${result.purpose === 'bind' ? '已绑定' : '已确认'}(请求 ${result.requestId})`);
|
|
958
|
-
}
|
|
959
|
-
async function start() {
|
|
960
|
-
if (busy.value) return;
|
|
961
|
-
busy.value = true;
|
|
962
|
-
key ??= requestKey();
|
|
963
|
-
try {
|
|
964
|
-
ticket.value = await client.create(props.mode, { idempotencyKey: key });
|
|
965
|
-
key = null;
|
|
966
|
-
} catch { message.value = '请求未完成,可重试同一次创建。'; }
|
|
967
|
-
finally { busy.value = false; }
|
|
968
|
-
}
|
|
112
|
+
<script setup>
|
|
113
|
+
import { AuthLinkPasscode } from '@auth-link/web/vue';
|
|
969
114
|
</script>
|
|
970
|
-
|
|
971
115
|
<template>
|
|
972
|
-
<
|
|
973
|
-
|
|
974
|
-
@confirmed="confirmed" @close="finish('已关闭')" @rejected="finish('手机已拒绝本次请求')"
|
|
975
|
-
@expired="finish('请求已过期,请重新发起')" @error="message = '网络异常,请重试。'" />
|
|
976
|
-
<AuthLinkConfirm v-else :ticket="ticket" :client="client"
|
|
977
|
-
@confirmed="confirmed" @close="finish('已关闭')" @rejected="finish('手机已拒绝本次请求')"
|
|
978
|
-
@expired="finish('请求已过期,请重新发起')" @error="message = '网络异常,请重试。'" />
|
|
979
|
-
<p role="status">{{ message }}</p>
|
|
116
|
+
<AuthLinkPasscode :client="client" :expires-at="pending.expiresAt"
|
|
117
|
+
locale="zh-CN" variant="B" @verified="updateUI" />
|
|
980
118
|
</template>
|
|
981
119
|
```
|
|
982
120
|
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
此示例在过期后清空 ticket,用户可再次点击按钮发起请求。如果需要在过期弹窗内提供重新发起按钮,可自行传入 `onRefresh`,在回调中创建新请求并更新 ticket。`useAuthLink(() => options)` composable 与 React 的 `useAuthLink(options)` hook 可用于自定义界面,返回 `snapshot` 和 `retry`;Vue 的 snapshot 是浅 ref。
|
|
986
|
-
|
|
987
|
-
### 选择弹窗样式
|
|
988
|
-
|
|
989
|
-
初始化时通过 `variant` 选择样式,**不传时默认 A**。
|
|
990
|
-
|
|
991
|
-
| 参数值 | 电脑端 | 手机端 |
|
|
992
|
-
| --- | --- | --- |
|
|
993
|
-
| `A`(默认) | 极简居中卡片、细线数字更新进度条 | 居中卡片 |
|
|
994
|
-
| `B` | 二维码和核对码左右分栏 | 自动纵向排列 |
|
|
995
|
-
| `C` | 紧凑卡片、底部取消入口 | 底部弹层,适配安全区域 |
|
|
996
|
-
|
|
997
|
-
```ts
|
|
998
|
-
openAuthLinkBind({ ticket, client }); // 默认 A、简体中文
|
|
999
|
-
openAuthLinkConfirm({ ticket, client, variant: 'B' });
|
|
1000
|
-
// modal.setVariant('C'); // 只更新显示,不重建请求、不重启查询
|
|
1001
|
-
```
|
|
1002
|
-
|
|
1003
|
-
```tsx
|
|
1004
|
-
<AuthLinkBind ticket={ticket} client={client} variant="C" />
|
|
1005
|
-
```
|
|
1006
|
-
|
|
1007
|
-
```vue
|
|
1008
|
-
<AuthLinkConfirm :ticket="ticket" :client="client" variant="B" />
|
|
1009
|
-
```
|
|
1010
|
-
|
|
1011
|
-
三套样式统一使用细进度条和固定文案“核对码每 30 秒自动更新”,不显示数字更新秒数。底部通常显示“等待手机确认”;仅最后 30 秒改为柔和橙色“请求即将过期 · 00:29”。新核对码轻微淡入,遵守系统减少动态效果设置;数字刷新不延长请求有效期。
|
|
1012
|
-
|
|
1013
|
-
三套样式使用相同的鉴权、过期和回调逻辑。React / Vue 可响应式切换 `variant`,不会重新发起请求;无效的运行时值回退到 A。B / C 的底部“取消”和右上角关闭行为一致,仅停止前端观察,不会替用户拒绝服务端请求。确认成功仍自动关闭。关闭图标保留 44px 点击区域和键盘焦点提示。
|
|
1014
|
-
|
|
1015
|
-
### 组件参数与事件
|
|
1016
|
-
|
|
1017
|
-
`AuthLinkBind` 用于绑定二维码,`AuthLinkConfirm` 用于手机确认。两者使用相同的主要参数:
|
|
1018
|
-
|
|
1019
|
-
| 参数 | 类型 | 说明 |
|
|
1020
|
-
| --- | --- | --- |
|
|
1021
|
-
| `ticket` | `Ticket`,必填 |应用后台创建的当前请求;组件不会自行创建请求 |
|
|
1022
|
-
| `client` | `AuthLinkClient`,必填 | 查询应用后台结果的客户端 |
|
|
1023
|
-
| `locale` | `Locale`,见下表 | 界面语言,默认 `zh-CN` |
|
|
1024
|
-
| `variant` | `DialogVariant` | `A`(默认)、`B` 或 `C`;只改变布局 |
|
|
1025
|
-
| `showQr` | `boolean` | 确认组件是否额外显示二维码;绑定组件始终显示 |
|
|
1026
|
-
| `intervalMs` | `number` | 结果轮询间隔,默认 1500 毫秒 |
|
|
1027
|
-
| `onRefresh` | `() => void` | 过期后,由网站重新创建请求并更新 ticket |
|
|
121
|
+
### 失败与清理
|
|
1028
122
|
|
|
1029
|
-
|
|
1030
|
-
| --- | --- | --- |
|
|
1031
|
-
| `onConfirmed` / `confirmed` | `Confirmation` |应用后台完成结果验证和消费后 |
|
|
1032
|
-
| `onRejected` / `rejected` | `Rejection` | 手机拒绝请求,弹窗自动关闭 |
|
|
1033
|
-
| `onExpired` / `expired` | 无 | 请求已过期 |
|
|
1034
|
-
| `onError` / `error` | `Error` | 网络错误、响应校验失败或成功回调执行失败等 |
|
|
123
|
+
已使用的码不能用于另一个操作或会话;刚登录或首次绑定后需等待下一组数字。PASSCODE_INVALID / PASSCODE_USED / PASSCODE_LOCKED 是验证失败,不能当成成功。网络结果不明时,后台保留原幂等键和原码重试,业务不能重复执行。
|
|
1035
124
|
|
|
1036
|
-
|
|
125
|
+
destroy() 中止浏览器请求并清理计时器,不触发关闭回调;close() 还调用 onClose。关闭弹窗不会回滚服务端操作,取消与会话待办由 CMS 管理。等待和本地过期均不轮询。
|
|
1037
126
|
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
| 入口 | 用途 |
|
|
1041
|
-
| --- | --- |
|
|
1042
|
-
| `@auth-link/web` | `createAuthLinkClient`、`requestKey`、公开类型及无框架工具 |
|
|
1043
|
-
| `@auth-link/web/react` | React 组件和 `useAuthLink` |
|
|
1044
|
-
| `@auth-link/web/vue` | Vue 组件和 `useAuthLink` |
|
|
1045
|
-
| `@auth-link/web/styles.css` | 组件样式,需显式导入 |
|
|
1046
|
-
|
|
1047
|
-
### 应用后台接口约定
|
|
1048
|
-
|
|
1049
|
-
默认前缀 `/api/authlink`;下面两个接口由接入方实现,**不是直接把浏览器请求转发到租户密钥 API**。
|
|
1050
|
-
|
|
1051
|
-
#### `POST /requests`
|
|
1052
|
-
|
|
1053
|
-
浏览器按所选模式携带网站登录凭据:Cookie 模式发送 session cookie 和配置的 CSRF 头,Bearer 模式发送 `Authorization`。创建还发送稳定的 `Idempotency-Key`,body:
|
|
1054
|
-
|
|
1055
|
-
```json
|
|
1056
|
-
{"purpose":"bind"}
|
|
1057
|
-
```
|
|
1058
|
-
|
|
1059
|
-
后台从经过验证的 session 或 Bearer token 取得用户 ID,创建并持久保存 state、创建/消费幂等键、用户/session 关联,然后调用 AuthLink 服务端创建请求。返回其公开 ticket:
|
|
1060
|
-
|
|
1061
|
-
```ts
|
|
1062
|
-
type Ticket = {
|
|
1063
|
-
requestId: string;
|
|
1064
|
-
purpose: 'bind' | 'confirm';
|
|
1065
|
-
qr: string; // AuthLink 返回的 QR JSON,不是 HTML
|
|
1066
|
-
pairingCode: string;
|
|
1067
|
-
expiresAt: string;
|
|
1068
|
-
displayCode: {
|
|
1069
|
-
value: string; // 六位数字,保留前导零
|
|
1070
|
-
serverTime: string; validUntil: string;
|
|
1071
|
-
periodSeconds: 30;
|
|
1072
|
-
};
|
|
1073
|
-
};
|
|
1074
|
-
```
|
|
1075
|
-
|
|
1076
|
-
#### `POST /requests/{requestId}/result`
|
|
1077
|
-
|
|
1078
|
-
同样验证登录身份(Cookie 模式还需 CSRF)和请求归属。后台调用 AuthLink 状态接口,将 `displayCode` 原样返回,不能缓存跨过 `validUntil`。新代码由后台实时获取,不是前端自行生成。
|
|
1079
|
-
|
|
1080
|
-
尚未完成时返回 `{requestId,status,displayCode?}`;状态可为 new / pending / approved / consumed / rejected / expired。`approved` 不能触发成功事件。
|
|
1081
|
-
|
|
1082
|
-
收到 approved / consumed 后,后台使用保存的稳定消费幂等键调用 `/consume`,核对完整结果,在自己数据库事务中记录此次 session 的确认,再返回已验证的回执。组件确认所需最小字段:
|
|
1083
|
-
|
|
1084
|
-
```json
|
|
1085
|
-
{
|
|
1086
|
-
"status":"confirmed",
|
|
1087
|
-
"requestId":"43字符请求ID",
|
|
1088
|
-
"verificationId":"43字符结果ID",
|
|
1089
|
-
"purpose":"confirm",
|
|
1090
|
-
"authenticationPolicy":"device-presence.v1",
|
|
1091
|
-
"expiresAt":"与创建请求完全一致的期限"
|
|
1092
|
-
}
|
|
1093
|
-
```
|
|
1094
|
-
|
|
1095
|
-
服务端必须在同一事务内记录已验证的确认结果,并校验请求归属。网页事件只用于更新界面;受保护接口必须依赖后台的可信确认记录,不能依赖 JS 回调或浏览器传来的 confirmed。
|
|
1096
|
-
|
|
1097
|
-
### 数字、时钟与安全
|
|
1098
|
-
|
|
1099
|
-
- 每个请求独立派生数字生成 seed;seed 只通过 claim 发给手机,并纳入设备签名上下文。网页只得到当前数字、服务端时间和本步期限。
|
|
1100
|
-
- 倒计时使用服务端时间锚点和单调时钟;本机系统时钟错误不直接导致倒计时漂移。网络延迟仍有影响,跨步时可能短暂显示“正在更新数字”,稳定后再核对。
|
|
1101
|
-
- 旧数字一过本步期限就隐藏,即使网络请求仍未返回。整个请求过期、拒绝或失败会隐藏数字和二维码。
|
|
1102
|
-
- 组件按请求检查成功结果、用途、双重认证策略和有效期。取消、卸载和切换请求后,旧响应不能触发成功回调。
|
|
1103
|
-
- 每个组件实例对同一请求只发一次成功事件;刷新或重新挂载不替代网站持久化幂等。
|
|
1104
|
-
- 包不接收网站业务授权内容,不提供 apiKey 配置,不执行支付/授权等业务操作。
|
|
1105
|
-
- 二维码在浏览器内生成,忽略后台 qrSvg,不使用 innerHTML;不上传给第三方图片服务。应用 CSP 需允许 `img-src 'self' data:`。
|
|
1106
|
-
|
|
1107
|
-
### 样式与语言
|
|
1108
|
-
|
|
1109
|
-
CSS 单独导入,所有类使用 `authlink-` 前缀。弹窗挂载到 `document.body`,可在 `:root` 或 `.authlink-dialog` 覆盖 `--authlink-foreground`、`--authlink-background`、`--authlink-accent`、`--authlink-muted`。面板语言见下表,默认简体中文。
|
|
1110
|
-
|
|
1111
|
-
React / Vue 均支持 `className`;Vue 还支持字符串、数组和对象形式的 `class`,与 `className` 合并。“重新发起”按钮使用父组件最新传入的 `onRefresh` 回调。
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
| Code | Language |
|
|
1115
|
-
| --- | --- |
|
|
1116
|
-
| `en` | English |
|
|
1117
|
-
| `zh-CN` | 简体中文 (default) |
|
|
1118
|
-
| `zh-TW` | 繁體中文 |
|
|
1119
|
-
| `ja` | 日本語 |
|
|
1120
|
-
| `bn` | বাংলা |
|
|
1121
|
-
| `es` | Español |
|
|
1122
|
-
| `fil` | Filipino |
|
|
1123
|
-
| `hi` | हिन्दी |
|
|
1124
|
-
| `id` | Bahasa Indonesia |
|
|
1125
|
-
| `ms` | Bahasa Melayu |
|
|
1126
|
-
| `pt` | Português |
|
|
1127
|
-
| `th` | ไทย |
|
|
1128
|
-
| `vi` | Tiếng Việt |
|
|
1129
|
-
|
|
1130
|
-
可以从根入口导入 `supportedLocales` 获取支持列表。文档默认英文,另有中文与日文版本。
|
|
1131
|
-
|
|
1132
|
-
### 兼容性
|
|
1133
|
-
|
|
1134
|
-
React 18.2+ / 19、Vue 3.3+、TypeScript、ESM。React 和 Vue 是可选 peer,只安装所用框架。构建工具环境需 Node 22.13+。
|
|
1135
|
-
|
|
1136
|
-
### 许可证
|
|
1137
|
-
|
|
1138
|
-
MIT。完整许可文本见 `LICENSE`,打包包含的第三方库归属说明见 `THIRD_PARTY_NOTICES.md`。
|
|
1139
|
-
|
|
1140
|
-
### Go Vue CMS: zh-CN
|
|
1141
|
-
|
|
1142
|
-
本指南按实际 Go CMS + Vue 3 的接入顺序整理。下面使用可替换的示例域名,不依赖某台电脑的配置、测试账号、密码或租户密钥。网站负责登录、数据库和业务接口;Web SDK 负责展示和观察请求,Go SDK 负责后台调用与回执校验。
|
|
1143
|
-
|
|
1144
|
-
#### 1. 区分三个来源并安装 SDK
|
|
1145
|
-
|
|
1146
|
-
| 角色 | 示例来源 | 配置位置 |
|
|
1147
|
-
| --- | --- | --- |
|
|
1148
|
-
| Vue | `https://cms.example.com` | `apiOrigin` 指向下方的 Go 后台 |
|
|
1149
|
-
| Go CMS API | `https://cms-api.example.com` | `baseUrl=https://cms-api.example.com/api/authlink` |
|
|
1150
|
-
| AuthLink API | `https://api.getauthlink.com` | Go SDK 的 `Origin`;浏览器的 `authLinkOrigin` |
|
|
1151
|
-
|
|
1152
|
-
AuthLink API 使用生产地址 `https://api.getauthlink.com`;Vue 网站和 Go CMS 的域名仍是接入方自己的示例,不能替换成 AuthLink 官网域名。
|
|
1153
|
-
|
|
1154
|
-
登记租户的站点 origin 是 Vue 网站来源;Go SDK 的 `Origin` 和凭据导出 JSON 中的 API origin 是 AuthLink API 来源。浏览器的 `baseUrl` 指向 Go 业务后台,不能指向 AuthLink 租户 API。公开运行配置只包含这三个 origin;`TenantID`、`APIKey` 保留在 Go 私密配置或环境变量中。
|
|
1155
|
-
|
|
1156
|
-
```sh
|
|
1157
|
-
npm install @auth-link/web@latest vue
|
|
1158
|
-
# In your Go backend module, after unpacking the supplied Go SDK:
|
|
1159
|
-
go mod edit -replace=authlink.local/sdk=./third_party/authlink-go
|
|
1160
|
-
go mod edit -require=authlink.local/sdk@v0.0.0
|
|
1161
|
-
go mod tidy
|
|
1162
|
-
```
|
|
1163
|
-
|
|
1164
|
-
Go SDK 当前随源码或官网的 Go SDK 源码包交付,保留 `third_party/authlink-go/go.mod`,导入 `authlink "authlink.local/sdk"`;这不是公共 `go get` 地址,也不是 npm 包内置的后台。用可信后台配置调用 `authlink.New(authlink.Config{Origin: authOrigin, TenantID: tenantID, APIKey: apiKey})`。
|
|
1165
|
-
|
|
1166
|
-
#### 2. 先完成网站登录,再读取会话
|
|
1167
|
-
|
|
1168
|
-
本站现有登录接口(参考 CMS 为 `POST /api/login`)验证用户后签发 HttpOnly、Secure 的 session Cookie。Vue 用 `credentials:'include'` 调用 Go 的 `GET /api/session`。已登录时返回 `authenticated:true` 与 `csrf`;未登录时先回到网站登录流程。
|
|
1169
|
-
|
|
1170
|
-
`csrf` 是本 CMS 的响应字段名;SDK 配置项仍叫 `csrfToken`,写成 `csrfToken: () => session.value?.csrf ?? ''` 即可。SDK 不要求你的后台一定返回名为 `csrfToken` 的字段。令牌由 Go 为当前 session 生成并保存,浏览器只读取,不能用租户密钥或手机核对码代替。创建和结果查询均需验证 `X-CSRF-Token` 与同一 session 的值一致。
|
|
1171
|
-
|
|
1172
|
-
Vue 与 API 使用同一 HTTPS 主域名下的两个子域名时,是跨 origin、同 site。参考 CMS 的 host-only Cookie 不设置 `Domain`,使用 `SameSite=Strict; Secure; HttpOnly; Path=/`;请求目标仍为 API 域名。真正跨 site 时还需按浏览器 Cookie 策略配置,不能只依靠 CORS。
|
|
1173
|
-
|
|
1174
|
-
#### 3. Go 配置 CORS 与业务路由
|
|
1175
|
-
|
|
1176
|
-
```http
|
|
1177
|
-
Access-Control-Allow-Origin: https://cms.example.com
|
|
1178
|
-
Access-Control-Allow-Credentials: true
|
|
1179
|
-
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS
|
|
1180
|
-
Access-Control-Allow-Headers: Content-Type, X-CSRF-Token, Idempotency-Key
|
|
1181
|
-
Vary: Origin
|
|
1182
|
-
Cache-Control: no-store
|
|
1183
|
-
```
|
|
1184
|
-
|
|
1185
|
-
只为精确允许的 Vue origin 返回这些 CORS 头;允许来源的正常和错误响应都要携带。`OPTIONS` 先验证来源、方法和请求头,成功返回 204,不要求登录或 CSRF;随后实际请求才验证登录、来源、CSRF 和归属。不能用 `*` 或无条件反射来源。上面包含 CMS 草稿编辑所用的 PUT;只接入 SDK 的站点可按实际路由收窄。
|
|
1186
|
-
|
|
1187
|
-
| 网站自己的路由 | 请求 | 返回 |
|
|
1188
|
-
| --- | --- | --- |
|
|
1189
|
-
| `GET /api/session` | — | `{authenticated:true, csrf:"…", subject:"…", username:"…"}`;未登录: `{authenticated:false}` |
|
|
1190
|
-
| `POST /api/authlink/requests` | `{purpose:"bind"}` 或 `{purpose:"confirm",postId,version}`; `Idempotency-Key` | 公开 `Ticket` |
|
|
1191
|
-
| `POST /api/authlink/requests/{id}/result` | `{}`;当前 session + CSRF | 待处理状态/displayCode 或已验证的 `confirmed` 回执 |
|
|
1192
|
-
| `POST /api/posts/{id}/publish` | `{requestId,version}`; 当前 session + CSRF | `{ok:true}` 校验已保存的确认记录和业务意图后返回 |
|
|
1193
|
-
|
|
1194
|
-
上述路由由 Go CMS 实现,不是安装 Web SDK 后自动出现的接口。`postId` / `version` / `/publish` 是本例业务约定,不是 AuthLink 平台字段。
|
|
1195
|
-
|
|
1196
|
-
#### 4. 创建前落库,消费后再返回 confirmed
|
|
1197
|
-
|
|
1198
|
-
```text
|
|
1199
|
-
Vue → Go /api/session → current session + csrf
|
|
1200
|
-
Vue → Go /api/authlink/requests → Go SDK CreateRequest → public ticket
|
|
1201
|
-
Vue dialog → Go /api/authlink/requests/{id}/result → Status + Consume
|
|
1202
|
-
Go commits verified receipt → Vue confirmed event
|
|
1203
|
-
Vue → Go /api/posts/{id}/publish → validate saved intent/receipt → publish
|
|
1204
|
-
```
|
|
1205
|
-
|
|
1206
|
-
Go 从可信 session 取稳定用户 ID,不能接受浏览器自报的 `externalUserId`。创建顺序:
|
|
1207
|
-
|
|
1208
|
-
1. 校验 purpose、创建幂等键,以及文章归属和当前版本(若有)。
|
|
1209
|
-
2. 生成独立随机 state 和消费幂等键;把原创建键、CreateInput、当前用户/session 和业务意图落库,再向 AuthLink 发请求。网络结果不明时从数据库恢复同一记录、输入和键。
|
|
1210
|
-
3. 调用 `CreateRequest`,保存返回的 requestId、原始 expiresAt 与 ticket,去掉可选 qrSvg 后返回公开 ticket。对同一 session + 创建键加唯一约束,键复用到其他 purpose / 文章 / 版本时返回冲突。
|
|
1211
|
-
4. 结果接口按 requestId + 当前 session 加锁读取记录;已保存回执直接复用。用 `Status` 查询,只有 approved / consumed 才以保存的 `Expected` 和消费键调用 `Consume`。SDK 校验失败不能返回成功。
|
|
1212
|
-
5. 在事务里保存回执、用户/session 确认记录和审计,requestId / verificationId 建唯一约束,提交成功后才返回 `confirmed`。待处理状态保留原 displayCode,不跨数字期限缓存。
|
|
1213
|
-
|
|
1214
|
-
下面是 SDK 调用层代码,**不是包含登录、数据库和路由的完整 HTTP 服务**;注释中的落库与事务必须由你的 Go 后台实现。初始化客户端、构造 Input、所有权检查及请求记录的读写按上述步骤完成。
|
|
1215
|
-
|
|
1216
|
-
```go
|
|
1217
|
-
package cmsauth
|
|
1218
|
-
|
|
1219
|
-
import (
|
|
1220
|
-
"context"
|
|
1221
|
-
authlink "authlink.local/sdk"
|
|
1222
|
-
)
|
|
1223
|
-
|
|
1224
|
-
// Load this record from your database for the authenticated user/session.
|
|
1225
|
-
// Save Input (including State), CreateKey and ConsumeKey BEFORE calling Create.
|
|
1226
|
-
// Intent (post ID/version), ownership and unique constraints belong in your DB.
|
|
1227
|
-
type StoredRequest struct {
|
|
1228
|
-
Input authlink.CreateInput
|
|
1229
|
-
CreateKey string
|
|
1230
|
-
ConsumeKey string
|
|
1231
|
-
Ticket authlink.Ticket
|
|
1232
|
-
}
|
|
1233
|
-
|
|
1234
|
-
// On network retries, load the SAME record; do not regenerate State or keys.
|
|
1235
|
-
func Create(ctx context.Context, sdk *authlink.Client, saved StoredRequest) (authlink.Ticket, error) {
|
|
1236
|
-
return sdk.CreateRequest(ctx, saved.Input, saved.CreateKey)
|
|
1237
|
-
}
|
|
1238
|
-
|
|
1239
|
-
type PublicConfirmation struct {
|
|
1240
|
-
Status string `json:"status"`
|
|
1241
|
-
RequestID string `json:"requestId"`
|
|
1242
|
-
VerificationID string `json:"verificationId"`
|
|
1243
|
-
Purpose string `json:"purpose"`
|
|
1244
|
-
ExpiresAt string `json:"expiresAt"`
|
|
1245
|
-
AuthenticationPolicy string `json:"authenticationPolicy"`
|
|
1246
|
-
}
|
|
1247
|
-
|
|
1248
|
-
// Caller checks session/CSRF/ownership, locks the saved record and first returns
|
|
1249
|
-
// any already-saved receipt. For a new confirmed result, caller must persist
|
|
1250
|
-
// the receipt and confirmation in a DB transaction BEFORE returning HTTP 200.
|
|
1251
|
-
func Poll(ctx context.Context, sdk *authlink.Client, saved StoredRequest) (any, error) {
|
|
1252
|
-
status, err := sdk.Status(ctx, saved.Ticket.RequestID)
|
|
1253
|
-
if err != nil { return nil, err }
|
|
1254
|
-
if status.Status != "approved" && status.Status != "consumed" { return status, nil }
|
|
1255
|
-
result, err := sdk.Consume(ctx, authlink.Expected{
|
|
1256
|
-
RequestID: saved.Ticket.RequestID,
|
|
1257
|
-
ExternalUserID: saved.Input.ExternalUserID,
|
|
1258
|
-
Purpose: saved.Input.Purpose,
|
|
1259
|
-
State: saved.Input.State,
|
|
1260
|
-
ExpiresAt: saved.Ticket.ExpiresAt,
|
|
1261
|
-
}, saved.ConsumeKey)
|
|
1262
|
-
if err != nil { return nil, err }
|
|
1263
|
-
return PublicConfirmation{
|
|
1264
|
-
Status: "confirmed", RequestID: result.RequestID,
|
|
1265
|
-
VerificationID: result.VerificationID, Purpose: result.Purpose,
|
|
1266
|
-
ExpiresAt: saved.Ticket.ExpiresAt, AuthenticationPolicy: result.AuthenticationPolicy,
|
|
1267
|
-
}, nil
|
|
1268
|
-
}
|
|
1269
|
-
```
|
|
1270
|
-
|
|
1271
|
-
#### 5. Vue 组件:稳定 ticket、按业务绑定创建、清理与重试
|
|
1272
|
-
|
|
1273
|
-
完整文件也包含在包内 `examples/vue-cms.vue`。网站登录后挂载它,传入可信 `apiOrigin`、`authLinkOrigin`,可选传入后台加载的草稿 `post={id,version}`。父层用当前登录 session 的标识做组件 key,退出、重新登录或切换账号时先卸载旧组件并清空会话、旧 ticket、幂等键和待发布操作,再挂载新组件。不要只改用户名后继续使用旧 ticket。
|
|
1274
|
-
|
|
1275
|
-
```vue
|
|
1276
|
-
<script setup lang="ts">
|
|
1277
|
-
import { markRaw, onMounted, onUnmounted, ref, shallowRef } from 'vue';
|
|
1278
|
-
import { createAuthLinkClient, requestKey, validateTicket } from '@auth-link/web';
|
|
1279
|
-
import type { Confirmation, Mode, Ticket } from '@auth-link/web';
|
|
1280
|
-
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/vue';
|
|
1281
|
-
import '@auth-link/web/styles.css';
|
|
1282
|
-
|
|
1283
|
-
type Post = { id: string; version: number };
|
|
1284
|
-
type Publication = Post & { requestId: string };
|
|
1285
|
-
// Supply trusted deployment configuration. Mount after site login and remount
|
|
1286
|
-
// with :key="session.subject" after login, logout or account/session changes.
|
|
1287
|
-
const props = defineProps<{ apiOrigin: string; authLinkOrigin: string; post?: Post }>();
|
|
1288
|
-
const session = ref<{ authenticated: boolean; csrf?: string } | null>(null);
|
|
1289
|
-
const ticket = shallowRef<Ticket | null>(null);
|
|
1290
|
-
const publication = shallowRef<Post | null>(null);
|
|
1291
|
-
const retryPublish = shallowRef<Publication | null>(null);
|
|
1292
|
-
const busy = ref(false), message = ref('');
|
|
1293
|
-
let creation: { signature: string; key: string } | null = null;
|
|
1294
|
-
const lifetime = new AbortController();
|
|
1295
|
-
const client = markRaw(createAuthLinkClient({
|
|
1296
|
-
baseUrl: `${props.apiOrigin}/api/authlink`,
|
|
1297
|
-
allowedBackendOrigins: [props.apiOrigin],
|
|
1298
|
-
credentials: 'include',
|
|
1299
|
-
csrfToken: () => session.value?.csrf ?? '',
|
|
1300
|
-
authLinkOrigin: props.authLinkOrigin,
|
|
1301
|
-
}));
|
|
1302
|
-
|
|
1303
|
-
async function api(path: string, body?: unknown, headers: Record<string, string> = {}) {
|
|
1304
|
-
const response = await fetch(`${props.apiOrigin}${path}`, {
|
|
1305
|
-
method: body === undefined ? 'GET' : 'POST',
|
|
1306
|
-
credentials: 'include', cache: 'no-store', redirect: 'error',
|
|
1307
|
-
signal: lifetime.signal,
|
|
1308
|
-
headers: body === undefined ? {} : {
|
|
1309
|
-
'Content-Type': 'application/json', 'X-CSRF-Token': session.value?.csrf ?? '', ...headers,
|
|
1310
|
-
},
|
|
1311
|
-
body: body === undefined ? undefined : JSON.stringify(body),
|
|
1312
|
-
});
|
|
1313
|
-
const value = await response.json();
|
|
1314
|
-
if (response.status === 401) {
|
|
1315
|
-
session.value = null; closeTicket(); retryPublish.value = null; creation = null;
|
|
1316
|
-
}
|
|
1317
|
-
if (!response.ok) throw new Error(value.code ?? 'REQUEST_FAILED');
|
|
1318
|
-
return value;
|
|
1319
|
-
}
|
|
1320
|
-
function closeTicket() { ticket.value = null; publication.value = null; }
|
|
1321
|
-
function showError(error: Error) { message.value = error.message; }
|
|
1322
|
-
function finish(text: string) { closeTicket(); message.value = text; }
|
|
1323
|
-
|
|
1324
|
-
async function start(purpose: Mode, post?: Post) {
|
|
1325
|
-
if (busy.value || ticket.value || !session.value?.authenticated) return;
|
|
1326
|
-
busy.value = true; message.value = ''; retryPublish.value = null;
|
|
1327
|
-
const intent = post ? { id: post.id, version: post.version } : null;
|
|
1328
|
-
const signature = JSON.stringify({ purpose, postId: intent?.id, version: intent?.version });
|
|
1329
|
-
try {
|
|
1330
|
-
if (creation?.signature !== signature) creation = { signature, key: requestKey() };
|
|
1331
|
-
// SDK create() sends only {purpose}. Business fields use your own API.
|
|
1332
|
-
const value = intent
|
|
1333
|
-
? validateTicket(await api('/api/authlink/requests', {
|
|
1334
|
-
purpose, postId: intent.id, version: intent.version,
|
|
1335
|
-
}, { 'Idempotency-Key': creation.key }), purpose, props.authLinkOrigin)
|
|
1336
|
-
: await client.create(purpose, { idempotencyKey: creation.key, signal: lifetime.signal });
|
|
1337
|
-
if (lifetime.signal.aborted) return;
|
|
1338
|
-
publication.value = intent; ticket.value = value; creation = null;
|
|
1339
|
-
} catch (error) {
|
|
1340
|
-
if (!lifetime.signal.aborted) showError(error as Error);
|
|
1341
|
-
// Retain creation.key for a retry of the SAME purpose/post/version.
|
|
1342
|
-
} finally { busy.value = false; }
|
|
1343
|
-
}
|
|
1344
|
-
async function publish() {
|
|
1345
|
-
const intent = retryPublish.value;
|
|
1346
|
-
if (!intent || busy.value) return;
|
|
1347
|
-
busy.value = true;
|
|
1348
|
-
try {
|
|
1349
|
-
await api(`/api/posts/${intent.id}/publish`, { version: intent.version, requestId: intent.requestId });
|
|
1350
|
-
retryPublish.value = null; message.value = 'Published. Reload your posts from the backend.';
|
|
1351
|
-
} catch (error) { if (!lifetime.signal.aborted) showError(error as Error); }
|
|
1352
|
-
finally { busy.value = false; }
|
|
1353
|
-
}
|
|
1354
|
-
async function confirmed(result: Confirmation) {
|
|
1355
|
-
const intent = publication.value;
|
|
1356
|
-
closeTicket();
|
|
1357
|
-
if (intent) { retryPublish.value = { ...intent, requestId: result.requestId }; await publish(); }
|
|
1358
|
-
else message.value = 'Verified. Reload account status from the backend.';
|
|
1359
|
-
}
|
|
1360
|
-
onMounted(async () => {
|
|
1361
|
-
try {
|
|
1362
|
-
const value = await api('/api/session');
|
|
1363
|
-
if (value.authenticated !== true || typeof value.csrf !== 'string' || !value.csrf) {
|
|
1364
|
-
throw new Error('LOGIN_REQUIRED');
|
|
1365
|
-
}
|
|
1366
|
-
session.value = value;
|
|
1367
|
-
} catch (error) { if (!lifetime.signal.aborted) showError(error as Error); }
|
|
1368
|
-
});
|
|
1369
|
-
onUnmounted(() => { lifetime.abort(); closeTicket(); creation = null; retryPublish.value = null; });
|
|
1370
|
-
</script>
|
|
1371
|
-
|
|
1372
|
-
<template>
|
|
1373
|
-
<button :disabled="busy || !!ticket || !session?.authenticated" @click="start('bind')">Bind phone</button>
|
|
1374
|
-
<button :disabled="busy || !!ticket || !session?.authenticated" @click="start('confirm')">Confirm</button>
|
|
1375
|
-
<button v-if="post" :disabled="busy || !!ticket || !session?.authenticated" @click="start('confirm', post)">Confirm publication</button>
|
|
1376
|
-
<button v-if="retryPublish" :disabled="busy || !!ticket" @click="publish">Retry the same publication</button>
|
|
1377
|
-
<AuthLinkBind v-if="ticket?.purpose === 'bind'" :ticket="ticket" :client="client" variant="B"
|
|
1378
|
-
@confirmed="confirmed" @close="finish('Closed')" @rejected="finish('Rejected')"
|
|
1379
|
-
@expired="finish('Expired; start a new request')" @error="showError" />
|
|
1380
|
-
<AuthLinkConfirm v-else-if="ticket?.purpose === 'confirm'" :ticket="ticket" :client="client" variant="B"
|
|
1381
|
-
@confirmed="confirmed" @close="finish('Closed')" @rejected="finish('Rejected')"
|
|
1382
|
-
@expired="finish('Expired; start a new request')" @error="showError" />
|
|
1383
|
-
<p role="status">{{ message }}</p>
|
|
1384
|
-
</template>
|
|
1385
|
-
```
|
|
1386
|
-
|
|
1387
|
-
普通绑定/确认使用 `client.create(purpose, {idempotencyKey})`。该方法只发送 purpose,**不能传入 postId/version 扩展请求体**。确认发布通过自己的 fetch 发送这些业务字段,再用 `validateTicket(response, 'confirm', authLinkOrigin)` 校验;后续弹窗查询仍复用官方 client。
|
|
1388
|
-
|
|
1389
|
-
同一次创建失败保留同一个键;用途或文章版本改变才换新键。`shallowRef` 保存 ticket,`markRaw` 保存客户端。组件挂载只打开和观察已有请求;不在 mounted/watch 中创建请求。关闭、拒绝和过期清空 ticket;网络错误保留弹窗,允许重试原请求。确认成功先清空 ticket,再调用独立业务接口;失败保留同一个 requestId / 文章 / 版本用于重试,先从后台确认真实状态后再刷新页面。上例省略网站自己的登录表单、文章列表和错误码中文映射。
|
|
1390
|
-
|
|
1391
|
-
#### 6. 发布接口必须再做后台检查
|
|
1392
|
-
|
|
1393
|
-
`confirmed` 回调只触发界面更新与下一次 API 请求,不是放行凭据。Go 的发布事务必须验证当前 session 对应的已落库回执,purpose=confirm、意图=publish、同一 postId、同一 version、文章归属和草稿状态,以及首次应用时尚未过期。成功时更新文章并标记请求 applied;重试已应用的同一操作返回原成功,不重复发布或写审计。请求不能用于另一文章或新版本,修改内容后须重新确认。前端不把文章内容、action 或 transactionHash 塞入 AuthLink 消费回执。
|
|
1394
|
-
|
|
1395
|
-
#### 验收顺序
|
|
1396
|
-
|
|
1397
|
-
登录 → 读取 session → 查询后台真实账号状态(参考 CMS 通过 overview 调用 Go SDK `AccountStatus`)→ 未绑定时 bind → 手机扫码批准 → 后台消费并刷新账号状态 → 保存草稿 → 按 postId/version confirm → 手机批准 → 结果消费落库 → 独立发布接口 → 重复发布/错误版本/拒绝/过期验证。真实设备验收仍由用户在手机上完成;本地编译和模拟 HTTP 测试不能代替这一步。
|
|
127
|
+
旧 openAuthLink / Ticket / Consume 流程仍供此前协议使用;新 App 使用 openPasscode / AuthLinkPasscode 以及后台 Authenticate / authenticate。此次不提供旧绑定升级。
|
|
1398
128
|
|
|
1399
129
|
---
|
|
1400
130
|
|
|
1401
131
|
## 日本語
|
|
1402
132
|
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
### Go + Vue の接続手順
|
|
1406
|
-
|
|
1407
|
-
Go + Vue の実際の接続手順は [ログイン、端末登録、確認後の公開](#go-vue-cms-ja)、完全なコンポーネントは `examples/vue-cms.vue` を参照してください。
|
|
1408
|
-
|
|
1409
|
-
サイトのログイン → Go `/api/session` の authenticated/csrf → `csrfToken: () => session.csrf` で別 origin のクライアント設定 → bind/confirm 作成 → Go で消費・検証・DB コミット → ダイアログを閉じる → 独立した業務 API で保存済み確認結果を再検証して公開、という順序です。baseUrl は Go、authLinkOrigin は AuthLink を指し、テナントキーは Go に保持します。記事/版付き要求は独自 fetch と validateTicket を使い、SDK create は purpose のみ送ります。
|
|
1410
|
-
|
|
1411
|
-
### 主な機能
|
|
1412
|
-
|
|
1413
|
-
- ブラウザー内で生成するスマートフォン登録用 QR コード。
|
|
1414
|
-
- アプリと同期し、30 秒ごとに更新される照合コード。
|
|
1415
|
-
- 承認・拒否・期限切れ・エラーのイベント。
|
|
1416
|
-
- React コンポーネントと hook、Vue コンポーネントと composable、フレームワーク非依存の API。
|
|
1417
|
-
- **簡体字中国語を既定とする 13 言語**。コンポーネントごとに指定可能。
|
|
1418
|
-
- TypeScript、独立した CSS、任意の React / Vue peer dependency。
|
|
133
|
+
### 認証コードを直接検証
|
|
1419
134
|
|
|
1420
|
-
|
|
135
|
+
アプリに6桁の認証コードを直接表示します。通常の検証では、毎回の承認、認証用requestId、businessId、ポーリングは不要です。初回はQRで端末を確認し、サイトで現在のコードを検証して連携を完了します。
|
|
1421
136
|
|
|
1422
|
-
|
|
137
|
+
画面を開く前にCMSサーバーでセッションの唯一の保留中操作を原子的に確保します。別タブから上書きさせません。ユーザーはサーバーのセッションから取得し、CSRF、業務権限、元のフォームを確認します。コードを検証し、verificationIdと元の操作を原子的に確定してから成功を返します。onVerifiedは表示更新専用です。
|
|
1423
138
|
|
|
1424
139
|
```sh
|
|
1425
|
-
npm install @auth-link/web
|
|
1426
|
-
```
|
|
1427
|
-
|
|
1428
|
-
対応環境:React 18.2+ / 19、Vue 3.3+、TypeScript、ESM。利用するフレームワークだけをインストールしてください。ツール環境には Node 22.13+ が必要です。
|
|
1429
|
-
|
|
1430
|
-
### 接続の流れ
|
|
1431
|
-
|
|
1432
|
-
1. サイトのバックエンドに AuthLink のテナント資格情報を設定します。
|
|
1433
|
-
2. 下記の業務バックエンド(同一オリジンまたは明示的に許可した別オリジン)の作成・結果取得 API を実装します。
|
|
1434
|
-
3. ユーザー操作でリクエストを作成し、取得した ticket をコンポーネントに渡します。
|
|
1435
|
-
4. バックエンドが結果を検証・消費した後に確認完了を返します。
|
|
1436
|
-
|
|
1437
|
-
ブラウザーからこのライブラリを呼び出せますが、テナント API キーと結果の消費処理は必ずサーバー側に置きます。標準クライアントは既定の同一オリジンと、明示的に許可した別オリジンに対応します。独自の通信方式では `AuthLinkClient` を実装できますが、資格情報と検証をブラウザーに移さないでください。
|
|
1438
|
-
|
|
1439
|
-
### クライアント作成(既定の同一オリジン Cookie モード)
|
|
1440
|
-
|
|
1441
|
-
`readCsrfTokenFromYourCms` は SDK のエクスポートではなく、接続先サイトで実装する関数です。現在のログインセッションに対してバックエンドが発行した CSRF token を読み取ります。CMS は必須ではありません。ブラウザーで値を生成したり、AuthLink の API キーを返したりしないでください。
|
|
1442
|
-
|
|
1443
|
-
既存フレームワークの CSRF 機構を優先してください。独自に実装する場合は、サーバーで暗号学的乱数(Node の `randomBytes(32).toString('base64url')` など)を生成し、セッションに保存して HTML 属性をエスケープしたうえでページに埋め込みます。下記の `{{ csrfToken }}` はサーバーテンプレートの変数です。このページを公開キャッシュしないでください。
|
|
1444
|
-
|
|
1445
|
-
```html
|
|
1446
|
-
<meta name="csrf-token" content="{{ csrfToken }}">
|
|
1447
|
-
```
|
|
1448
|
-
|
|
1449
|
-
SDK は各リクエストで token を読み取り、`X-CSRF-Token` と同一オリジンのセッション cookie を送信します。作成 API と結果 API の両方で、バックエンドが同じセッションの token と照合し、欠落・不一致や不正なリクエスト元を拒否する必要があります。ログインやセッション変更後は最新 token を取得してください。SPA ではサイト独自の同一オリジン初期化 API から取得する方法も使えます。別のヘッダー名を使うフレームワークでは`csrfHeaderName` または独自 `AuthLinkClient` で適合します。
|
|
1450
|
-
|
|
1451
|
-
`authlink-client.ts` を作成します:
|
|
1452
|
-
|
|
1453
|
-
```ts
|
|
1454
|
-
// authlink-client.ts
|
|
1455
|
-
import { createAuthLinkClient } from '@auth-link/web';
|
|
1456
|
-
import '@auth-link/web/styles.css';
|
|
1457
|
-
|
|
1458
|
-
// The application server renders this meta element using the current session's
|
|
1459
|
-
// CSRF token. This function only reads that token; it does not generate one.
|
|
1460
|
-
export function readCsrfTokenFromYourCms(): string {
|
|
1461
|
-
const token = document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.content;
|
|
1462
|
-
if (!token) throw new Error('Missing CSRF token; load the authenticated application page first.');
|
|
1463
|
-
return token;
|
|
1464
|
-
}
|
|
1465
|
-
|
|
1466
|
-
export const client = createAuthLinkClient({
|
|
1467
|
-
baseUrl: '/api/authlink',
|
|
1468
|
-
csrfToken: readCsrfTokenFromYourCms,
|
|
1469
|
-
// AuthLink production API origin.
|
|
1470
|
-
authLinkOrigin: 'https://api.getauthlink.com',
|
|
1471
|
-
});
|
|
1472
|
-
```
|
|
1473
|
-
|
|
1474
|
-
AuthLink の本番 API は `https://api.getauthlink.com` です。baseUrl は自サイトの業務バックエンドを指し、AuthLink 公式サイトのドメインは API に使いません。独自に配置したサービスへ接続する場合は、その設定済み origin を使用します。リクエストは下記の React 例のようにユーザー操作で作成します。
|
|
1475
|
-
|
|
1476
|
-
### フロントエンドとバックエンドの別オリジン対応(0.0.2 以降)
|
|
1477
|
-
|
|
1478
|
-
既定は同一オリジンの `/api/authlink` です。別オリジンの業務 API に直接接続するには完全な `baseUrl` と `allowedBackendOrigins` を指定します。例:フロントエンド `https://www.example.com`、バックエンド `https://api.example.com`。サブドメインやポートが異なる場合も別オリジンです。許可リストにはパス、ワイルドカード、ユーザー名・パスワードを含めず、信頼する固定設定を使います。HTTPS が必須で、開発用 HTTP loopback(localhost / 127.0.0.1 / [::1])のみ例外です。
|
|
1479
|
-
|
|
1480
|
-
SDK は認証情報を読む前に接続先を検証し、リダイレクトを拒否します。`authLinkOrigin` は QR 内の AuthLink サービスオリジンの検証用で、業務 API の許可リストとは別です。
|
|
1481
|
-
|
|
1482
|
-
#### 別オリジンの Cookie / session
|
|
1483
|
-
|
|
1484
|
-
汎用例の JSON 名は csrfToken ですが、Go CMS の実際の応答は `{ authenticated: true, csrf: '…' }` です。session.csrf を SDK の csrfToken コールバックに渡せばよく、バックエンドのフィールド名を変更する必要はありません。
|
|
1485
|
-
|
|
1486
|
-
下記の `GET /api/session` はサイトで実装する例示 API で、SDK が提供する API ではありません。ログイン session の `{ "csrfToken": "現在のtoken" }` を返し、`Cache-Control: no-store` と CORS を設定します。既存サイトの API パスに適合してください。
|
|
1487
|
-
|
|
1488
|
-
```ts
|
|
1489
|
-
import { createAuthLinkClient } from '@auth-link/web';
|
|
1490
|
-
|
|
1491
|
-
/** /api/session is an example endpoint implemented by your application backend. */
|
|
1492
|
-
export async function createSessionBackendClient(backendOrigin: string) {
|
|
1493
|
-
const response = await fetch(`${backendOrigin}/api/session`, {
|
|
1494
|
-
credentials: 'include', cache: 'no-store', redirect: 'error',
|
|
1495
|
-
});
|
|
1496
|
-
if (!response.ok) throw new Error('Session initialization failed');
|
|
1497
|
-
const session: unknown = await response.json();
|
|
1498
|
-
if (!session || typeof session !== 'object' || !('csrfToken' in session) ||
|
|
1499
|
-
typeof session.csrfToken !== 'string' || !session.csrfToken) {
|
|
1500
|
-
throw new Error('The session endpoint must return { csrfToken: string }');
|
|
1501
|
-
}
|
|
1502
|
-
let currentCsrfToken = session.csrfToken;
|
|
1503
|
-
return {
|
|
1504
|
-
client: createAuthLinkClient({
|
|
1505
|
-
baseUrl: `${backendOrigin}/api/authlink`,
|
|
1506
|
-
allowedBackendOrigins: [backendOrigin],
|
|
1507
|
-
credentials: 'include',
|
|
1508
|
-
csrfToken: () => currentCsrfToken,
|
|
1509
|
-
}),
|
|
1510
|
-
// Call after your application's session/token refresh; recreate on account changes.
|
|
1511
|
-
updateCsrfToken(value: string) { currentCsrfToken = value; },
|
|
1512
|
-
};
|
|
1513
|
-
}
|
|
140
|
+
npm install @auth-link/web@^1.1.0
|
|
1514
141
|
```
|
|
1515
142
|
|
|
1516
|
-
ログイン後に `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` が必要で、ブラウザーによっては引き続き拒否されます。
|
|
1517
|
-
|
|
1518
|
-
#### Bearer token / JWT
|
|
1519
|
-
|
|
1520
|
-
サイトの既存ログイン状態を渡してください。ログイン・更新処理で `auth.accessToken` を更新すると、SDK は作成・ポーリングのたびに最新値を読み取ります。
|
|
1521
|
-
|
|
1522
|
-
```ts
|
|
1523
|
-
import { createAuthLinkClient } from '@auth-link/web';
|
|
1524
|
-
|
|
1525
|
-
/** auth is your website's existing login state, updated by its login/refresh flow. */
|
|
1526
|
-
export function createBearerBackendClient(backendOrigin: string, auth: { accessToken: string }) {
|
|
1527
|
-
return createAuthLinkClient({
|
|
1528
|
-
baseUrl: `${backendOrigin}/api/authlink`,
|
|
1529
|
-
allowedBackendOrigins: [backendOrigin],
|
|
1530
|
-
credentials: 'omit',
|
|
1531
|
-
accessToken: () => auth.accessToken,
|
|
1532
|
-
});
|
|
1533
|
-
}
|
|
1534
|
-
```
|
|
1535
|
-
|
|
1536
|
-
これはサイト利用者のログイン token であり、AuthLink のテナント API キーではありません。SDK が `Authorization: Bearer ...` を付加します。`accessToken` 指定時は既定で `credentials: 'omit'` となり、Cookie にフォールバックせず Bearer のみで認証するバックエンドでは CSRF を省略できます。`include` / `same-origin` を明示して Cookie を併用する場合は CSRF の提供・検証も必要です。
|
|
1537
|
-
|
|
1538
|
-
#### バックエンドの CORS
|
|
1539
|
-
|
|
1540
|
-
`OPTIONS` プリフライトを処理し、実リクエスト・エラー応答・session 初期化 API にも必要な CORS ヘッダーを返します。フロントエンドが `https://www.example.com` の例:
|
|
1541
|
-
|
|
1542
|
-
```http
|
|
1543
|
-
Access-Control-Allow-Origin: https://www.example.com
|
|
1544
|
-
Access-Control-Allow-Credentials: true
|
|
1545
|
-
Access-Control-Allow-Methods: GET, POST, OPTIONS
|
|
1546
|
-
Access-Control-Allow-Headers: Content-Type, X-CSRF-Token, Idempotency-Key, Authorization
|
|
1547
|
-
Vary: Origin
|
|
1548
|
-
```
|
|
1549
|
-
|
|
1550
|
-
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) を参照してください。
|
|
1551
|
-
|
|
1552
|
-
#### クライアント設定
|
|
1553
|
-
|
|
1554
|
-
| 設定 | 説明 |
|
|
1555
|
-
| --- | --- |
|
|
1556
|
-
| `baseUrl` | 業務 API の接頭辞、既定 `/api/authlink`;別オリジン時は完全 URL |
|
|
1557
|
-
| `allowedBackendOrigins` | 追加許可する正確な業務 API オリジンの配列 |
|
|
1558
|
-
| `credentials` | 既定 `same-origin`、`accessToken` 指定時 `omit`;別オリジン Cookie は `include` |
|
|
1559
|
-
| `csrfToken` | リクエストごとの同期/非同期取得関数;Cookie モードは必須 |
|
|
1560
|
-
| `csrfHeaderName` | 既定 `X-CSRF-Token`、フレームワークに合わせて変更可能 |
|
|
1561
|
-
| `accessToken` | サイトのログイン token 取得関数;`Bearer ` 接頭辞は付けない |
|
|
1562
|
-
| `headers` | 追加 `HeadersInit`、またはそれを返す同期/非同期関数 |
|
|
1563
|
-
| `authLinkOrigin` | QR 内の信頼するサービスオリジン。業務 API オリジンとは別 |
|
|
1564
|
-
| `fetch` | 任意の fetch 実装;接続先検証は維持 |
|
|
1565
|
-
|
|
1566
|
-
追加ヘッダーは SDK 管理の `Accept`、`Content-Type`、`Authorization`、`Idempotency-Key`、設定済み CSRF ヘッダーを上書きできません(`RESERVED_HEADER`)。`accessToken` と `csrfHeaderName` を使用してください。設定型 `ClientOptions` はルートエントリーからインポートできます。
|
|
1567
|
-
|
|
1568
|
-
未許可オリジンは `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` になります。
|
|
1569
|
-
|
|
1570
|
-
### 関数でダイアログを開く(React / Vue / JavaScript)
|
|
1571
|
-
|
|
1572
143
|
```ts
|
|
1573
|
-
import {
|
|
1574
|
-
import { client } from './authlink-client';
|
|
144
|
+
import { openPasscode, createPasscodeClient } from '@auth-link/web';
|
|
1575
145
|
import '@auth-link/web/styles.css';
|
|
1576
|
-
|
|
1577
|
-
const
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
146
|
+
const client = createPasscodeClient({ baseUrl: '/api', csrfToken: () => csrfToken });
|
|
147
|
+
const modal = openPasscode({
|
|
148
|
+
client, expiresAt: pending.expiresAt, locale: 'zh-CN', variant: 'B',
|
|
149
|
+
// First-time enrollment only:
|
|
150
|
+
// bindingQr: pending.bindingQr, authLinkOrigin: 'https://api.getauthlink.com',
|
|
151
|
+
onVerified: result => updateUI(result.verificationId),
|
|
1582
152
|
});
|
|
1583
|
-
//
|
|
1584
|
-
// modal.close(); modal.setLocale('en');
|
|
153
|
+
// modal.setLocale('en'); modal.setVariant('C'); modal.destroy();
|
|
1585
154
|
```
|
|
1586
155
|
|
|
1587
|
-
|
|
156
|
+
標準クライアントは現在の認証情報とCSRFを付け、CMSのPOST /api/authへ{passcode}を送信します。フォームも送る場合はclient.verifyで{form,passcode}をCMSへ送信し、サーバーで保存済み内容と照合します。テナントキーやコード生成用秘密はブラウザーへ渡しません。
|
|
1588
157
|
|
|
1589
|
-
|
|
158
|
+
### オプションとコールバック
|
|
1590
159
|
|
|
160
|
+
必須はclient.verify(passcode, signal)とexpiresAt(CMS操作の期限)です。任意でlocale、variant A/B/C、初回用bindingQrとauthLinkOrigin、onVerified、onError、onClose、onExpiredを指定します。成功結果はstatus、verificationId、authenticationPolicy、expiresAtを含み、requestIdやbusinessIdは含みません。
|
|
1591
161
|
|
|
1592
|
-
|
|
162
|
+
Cookie認証ではCSRFが必須です。Bearer認証はaccessTokenとcredentials=omitを使います。別オリジンのCMSはallowedBackendOriginsを明示し、ループバック開発以外ではHTTPSを使います。
|
|
1593
163
|
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
```tsx
|
|
1597
|
-
"use client";
|
|
1598
|
-
import { useRef, useState } from 'react';
|
|
1599
|
-
import { requestKey } from '@auth-link/web';
|
|
1600
|
-
import type { Mode, Ticket } from '@auth-link/web';
|
|
1601
|
-
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/react';
|
|
1602
|
-
import { client } from './authlink-client';
|
|
1603
|
-
|
|
1604
|
-
export function AuthLinkPanel({ mode }: { mode: Mode }) {
|
|
1605
|
-
const [ticket, setTicket] = useState<Ticket | null>(null);
|
|
1606
|
-
const [busy, setBusy] = useState(false);
|
|
1607
|
-
const [message, setMessage] = useState('');
|
|
1608
|
-
const key = useRef<string | null>(null);
|
|
1609
|
-
const creating = useRef(false);
|
|
1610
|
-
function finish(message: string) {
|
|
1611
|
-
setTicket(null);
|
|
1612
|
-
setMessage(message);
|
|
1613
|
-
}
|
|
1614
|
-
function showBound(requestId: string) {
|
|
1615
|
-
// UI feedback only. The backend has already verified and saved the binding.
|
|
1616
|
-
finish(`Phone bound (request ${requestId})`);
|
|
1617
|
-
}
|
|
1618
|
-
function showConfirmed(requestId: string) {
|
|
1619
|
-
finish(`Confirmed (request ${requestId})`);
|
|
1620
|
-
}
|
|
1621
|
-
const start = async () => {
|
|
1622
|
-
if (creating.current || ticket) return;
|
|
1623
|
-
creating.current = true;
|
|
1624
|
-
setBusy(true);
|
|
1625
|
-
setMessage('');
|
|
1626
|
-
try {
|
|
1627
|
-
key.current ??= requestKey();
|
|
1628
|
-
setTicket(await client.create(mode, { idempotencyKey: key.current }));
|
|
1629
|
-
key.current = null;
|
|
1630
|
-
} catch { setMessage('Request failed; retry the same creation.'); }
|
|
1631
|
-
finally { creating.current = false; setBusy(false); }
|
|
1632
|
-
};
|
|
1633
|
-
const Component = mode === 'bind' ? AuthLinkBind : AuthLinkConfirm;
|
|
1634
|
-
return <>
|
|
1635
|
-
{!ticket && <button type="button" disabled={busy} onClick={() => void start()}>Start verification</button>}
|
|
1636
|
-
{ticket && <Component ticket={ticket} client={client}
|
|
1637
|
-
onConfirmed={result => result.purpose === 'bind' ? showBound(result.requestId) : showConfirmed(result.requestId)}
|
|
1638
|
-
onClose={() => finish('Closed')}
|
|
1639
|
-
onRejected={() => finish('Request rejected on the phone')}
|
|
1640
|
-
onExpired={() => finish('Request expired; start again')}
|
|
1641
|
-
onError={error => setMessage(error.message)} />}
|
|
1642
|
-
<p role="status">{message}</p>
|
|
1643
|
-
</>;
|
|
1644
|
-
}
|
|
1645
|
-
```
|
|
164
|
+
### ReactとVue
|
|
1646
165
|
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
`locale` を省略すると簡体字中国語です。日本語は `locale="ja"`、簡体字中国語は `locale="zh-CN"` を指定します。client と ticket はレンダー間で安定したオブジェクトにしてください。React エントリーは `"use client"` を保持し、SSR ではリクエストを作成しません。
|
|
1651
|
-
|
|
1652
|
-
### Vue
|
|
1653
|
-
|
|
1654
|
-
```vue
|
|
1655
|
-
<script setup lang="ts">
|
|
1656
|
-
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/vue';
|
|
1657
|
-
import type { Ticket, Confirmation } from '@auth-link/web';
|
|
1658
|
-
import { client } from './authlink-client';
|
|
1659
|
-
|
|
1660
|
-
defineProps<{ ticket: Ticket }>();
|
|
1661
|
-
function confirmed(result: Confirmation) {
|
|
1662
|
-
console.log('Confirmed request:', result.requestId);
|
|
1663
|
-
}
|
|
1664
|
-
</script>
|
|
1665
|
-
|
|
1666
|
-
<template>
|
|
1667
|
-
<AuthLinkBind v-if="ticket.purpose === 'bind'" :ticket="ticket" :client="client"
|
|
1668
|
-
@confirmed="confirmed" />
|
|
1669
|
-
<AuthLinkConfirm v-else :ticket="ticket" :client="client" locale="ja"
|
|
1670
|
-
@confirmed="confirmed" />
|
|
1671
|
-
</template>
|
|
1672
|
-
```
|
|
1673
|
-
|
|
1674
|
-
`:locale="selectedLanguage"` で表示言語を切り替えられます。言語切り替えによって新しい認証リクエストは作成されません。
|
|
1675
|
-
|
|
1676
|
-
### レイアウトの選択
|
|
1677
|
-
|
|
1678
|
-
初期化時の `variant` で選択します。省略時は **A** です。
|
|
1679
|
-
|
|
1680
|
-
| 値 | デスクトップ | モバイル |
|
|
1681
|
-
| --- | --- | --- |
|
|
1682
|
-
| `A`(既定) | ミニマルなカードと細いコード更新バー | 中央のカード |
|
|
1683
|
-
| `B` | QR と照合コードの二列表示 | 縦並び |
|
|
1684
|
-
| `C` | コンパクトなカードとキャンセル操作 | セーフエリア対応のボトムシート |
|
|
1685
|
-
|
|
1686
|
-
```ts
|
|
1687
|
-
openAuthLinkBind({ ticket, client }); // A、既定言語は簡体字中国語
|
|
1688
|
-
openAuthLinkConfirm({ ticket, client, variant: 'B' });
|
|
1689
|
-
// modal.setVariant('C');
|
|
1690
|
-
```
|
|
166
|
+
Reactは同じオプションを使い、Vueはverified、error、close、expiredイベントを発行します。clientの参照を安定させてください。13言語に対応し、既定は簡体字中国語です。Aはシンプル、Bは分割、Cはコンパクト表示です。
|
|
1691
167
|
|
|
1692
168
|
```tsx
|
|
1693
|
-
|
|
169
|
+
import { AuthLinkPasscode } from '@auth-link/web/react';
|
|
170
|
+
// Keep client stable (for example with useMemo).
|
|
171
|
+
<AuthLinkPasscode client={client} expiresAt={pending.expiresAt}
|
|
172
|
+
locale="zh-CN" variant="B" onVerified={updateUI} />
|
|
1694
173
|
```
|
|
1695
|
-
|
|
1696
174
|
```vue
|
|
1697
|
-
<
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
すべてのレイアウトで細い進捗バーと「照合コードは30秒ごとに自動更新」を表示します。通常は「スマートフォンの確認待ち」を表示し、残り30秒になったときだけオレンジ色の期限警告と 00:29 形式に切り替わります。コード変更時の短いフェードはモーション低減設定に従い、リクエスト期限は延長されません。
|
|
1701
|
-
|
|
1702
|
-
React / Vue では表示中にも変更でき、リクエストやポーリングは再作成されません。未対応の値は A に戻ります。B / C のキャンセル操作は閉じるアイコンと同じく表示の監視を停止し、サーバーのリクエストは拒否しません。確認成功時は自動で閉じます。閉じる操作のタッチ領域は 44px で、キーボードのフォーカス表示も維持します。
|
|
1703
|
-
|
|
1704
|
-
### コンポーネントの設定
|
|
1705
|
-
|
|
1706
|
-
| 設定 | 型 | 説明 |
|
|
1707
|
-
| --- | --- | --- |
|
|
1708
|
-
| `ticket` | `Ticket`、必須 | バックエンドで作成したリクエスト |
|
|
1709
|
-
| `client` | `AuthLinkClient`、必須 | バックエンドの結果を取得するクライアント |
|
|
1710
|
-
| `locale` | `Locale` | 既定は `zh-CN` |
|
|
1711
|
-
| `variant` | `DialogVariant` | `A`(既定)、`B`、`C` |
|
|
1712
|
-
| `showQr` | `boolean` | 確認画面にも QR を表示。登録画面では常に表示 |
|
|
1713
|
-
| `intervalMs` | `number` | 250~10000 ミリ秒。既定は 1500 ミリ秒 |
|
|
1714
|
-
| `onRefresh` | `() => void` | 期限切れ後、新規作成して ticket を更新する処理 |
|
|
1715
|
-
|
|
1716
|
-
| React コールバック / Vue イベント | 引数 | 意味 |
|
|
1717
|
-
| --- | --- | --- |
|
|
1718
|
-
| `onConfirmed` / `confirmed` | `Confirmation` | バックエンドによる検証と消費が完了 |
|
|
1719
|
-
| `onRejected` / `rejected` | `Rejection` | 拒否時はダイアログを自動で閉じる |
|
|
1720
|
-
| `onExpired` / `expired` | なし | 有効期限切れ |
|
|
1721
|
-
| `onError` / `error` | `Error` | 通信・応答検証・コールバックのエラー |
|
|
1722
|
-
|
|
1723
|
-
拒否時は `{ status: 'rejected', code: 'REJECTED', requestId, purpose }` を返します。`REJECTED` は SDK の業務ステータスで、HTTP ステータスや承認証明ではありません。拒否・再試行画面は表示せず、`onClose` も通知しません。メッセージや新規作成はサイト側で処理してください。React / Vue では `onRejected` / `@rejected` で ticket を解除してコンポーネントを破棄します。ヘッドレス hook の `snapshot.status` は `rejected` のままです。
|
|
1724
|
-
|
|
1725
|
-
独自 UI には React の `useAuthLink(options)`、Vue の `useAuthLink(() => options)` を利用できます。返される値は `snapshot` と `retry` です。Vue の snapshot は shallow ref です。retry は既存リクエストを再開し、onRefresh はサイト側のコードで新規作成します。
|
|
1726
|
-
|
|
1727
|
-
### バックエンド API
|
|
1728
|
-
|
|
1729
|
-
既定の接頭辞は `/api/authlink` です。両 API で Cookie + 設定した CSRF ヘッダー、または Bearer token による本人確認とリクエスト所有者を検証してください。作成時は `Idempotency-Key` も送信されます。サイトのユーザー ID は検証済みセッション/token から決定します。
|
|
1730
|
-
|
|
1731
|
-
```ts
|
|
1732
|
-
import type { Ticket, Result } from '@auth-link/web';
|
|
1733
|
-
|
|
1734
|
-
// POST /api/authlink/requests
|
|
1735
|
-
// Body: { purpose: 'bind' | 'confirm' }
|
|
1736
|
-
// Response: Ticket
|
|
1737
|
-
|
|
1738
|
-
// POST /api/authlink/requests/{requestId}/result
|
|
1739
|
-
// Body: {}
|
|
1740
|
-
// Response: Result
|
|
1741
|
-
```
|
|
1742
|
-
|
|
1743
|
-
```json
|
|
1744
|
-
{
|
|
1745
|
-
"status": "confirmed",
|
|
1746
|
-
"requestId": "<request-id>",
|
|
1747
|
-
"verificationId": "<verification-id>",
|
|
1748
|
-
"purpose": "confirm",
|
|
1749
|
-
"authenticationPolicy": "device-presence.v1",
|
|
1750
|
-
"expiresAt": "<same-expiry-as-ticket>"
|
|
1751
|
-
}
|
|
1752
|
-
```
|
|
1753
|
-
|
|
1754
|
-
作成 API は AuthLink の公開 ticket(`requestId`、`purpose`、`qr`、`pairingCode`、`expiresAt`、現在の `displayCode`)を返します。displayCode は `value`、`serverTime`、`validUntil`、`periodSeconds: 30` を持ちます。確認用 ticket には displayCode が必要です。
|
|
1755
|
-
|
|
1756
|
-
結果 API は未完了状態と最新の表示コードを返します。`new` / `pending` / `approved` / `consumed` だけでは成功イベントは発火しません。`confirmed` を返す前に、バックエンドは保存した state と消費用冪等キーで AuthLink の結果を消費し、完全な受領情報を検証して正しいセッションに記録します。requestId / verificationId による永続的な冪等処理が必要です。
|
|
1757
|
-
|
|
1758
|
-
### 対応言語
|
|
1759
|
-
|
|
1760
|
-
| Code | Language |
|
|
1761
|
-
| --- | --- |
|
|
1762
|
-
| `en` | English |
|
|
1763
|
-
| `zh-CN` | 简体中文 (default) |
|
|
1764
|
-
| `zh-TW` | 繁體中文 |
|
|
1765
|
-
| `ja` | 日本語 |
|
|
1766
|
-
| `bn` | বাংলা |
|
|
1767
|
-
| `es` | Español |
|
|
1768
|
-
| `fil` | Filipino |
|
|
1769
|
-
| `hi` | हिन्दी |
|
|
1770
|
-
| `id` | Bahasa Indonesia |
|
|
1771
|
-
| `ms` | Bahasa Melayu |
|
|
1772
|
-
| `pt` | Português |
|
|
1773
|
-
| `th` | ไทย |
|
|
1774
|
-
| `vi` | Tiếng Việt |
|
|
1775
|
-
|
|
1776
|
-
未指定・未対応の言語コードは簡体字中国語にフォールバックします。ルート要素には `lang` が設定されます。ルートエントリーの `supportedLocales` で一覧を取得できます。言語変更は表示文言だけに作用し、数字やリクエストは変更しません。ドキュメントは英語・中国語・日本語で提供します。
|
|
1777
|
-
|
|
1778
|
-
### スタイルとエントリー
|
|
1779
|
-
|
|
1780
|
-
`@auth-link/web/styles.css` を明示的に読み込みます。ダイアログは `document.body` に追加されるため、`:root` または `.authlink-dialog` で `--authlink-foreground`、`--authlink-background`、`--authlink-accent`、`--authlink-muted` を上書きします。クラス名の接頭辞は `authlink-` です。
|
|
1781
|
-
|
|
1782
|
-
React / Vue はダイアログの `className` に対応します。Vue は文字列・配列・オブジェクト形式の `class` も受け取り、`className` と結合します。再作成ボタンは親が渡した最新の `onRefresh` を呼び出します。
|
|
1783
|
-
|
|
1784
|
-
| エントリー | 内容 |
|
|
1785
|
-
| --- | --- |
|
|
1786
|
-
| `@auth-link/web` | クライアント、冪等キー、対応言語、型、基本 API |
|
|
1787
|
-
| `@auth-link/web/react` | React コンポーネントと hook |
|
|
1788
|
-
| `@auth-link/web/vue` | Vue コンポーネントと composable |
|
|
1789
|
-
| `@auth-link/web/styles.css` | スタイル |
|
|
1790
|
-
|
|
1791
|
-
### セキュリティと有効期限
|
|
1792
|
-
|
|
1793
|
-
- 数字はアプリとの目視照合用です。数字だけで認証や承認はできません。
|
|
1794
|
-
- ブラウザーに生成 seed、端末秘密鍵、テナント秘密情報を渡しません。
|
|
1795
|
-
- リクエストは最大 120 秒。コード更新で期限は延長されません。サービスとアプリはモバイルプロトコル 7 に対応する必要があります。
|
|
1796
|
-
- サーバー時刻と単調増加時計で残り時間を計算し、通信が止まっても期限切れの数字は隠します。更新境界で短い待ち時間が生じる場合があります。
|
|
1797
|
-
- アンマウントや ticket 変更で監視を中止します。インスタンス内のイベント重複防止とは別に、バックエンドで永続的な冪等処理が必要です。
|
|
1798
|
-
- フロントエンドのイベントは UI 更新用です。保護 API はバックエンドの信頼できる記録で判断します。
|
|
1799
|
-
- QR はローカル生成し、バックエンドの SVG を挿入しません。CSP は `img-src 'self' data:` を許可してください。
|
|
1800
|
-
|
|
1801
|
-
### ライセンス
|
|
1802
|
-
|
|
1803
|
-
MIT。ライセンス全文は `LICENSE`、同梱ライブラリの帰属表示は `THIRD_PARTY_NOTICES.md` を参照してください。
|
|
1804
|
-
|
|
1805
|
-
### Go Vue CMS: ja
|
|
1806
|
-
|
|
1807
|
-
実際の Go CMS + Vue 3 の接続順序を示します。例のドメインは置き換え用で、ローカル設定・テスト用パスワード・テナント資格情報は含めません。ログイン、DB、業務 API はサイト側で実装し、Web SDK は表示と監視、Go SDK は AuthLink 呼び出しと応答検証を担当します。
|
|
1808
|
-
|
|
1809
|
-
#### 1. 3 つの origin と SDK
|
|
1810
|
-
|
|
1811
|
-
| 役割 | 例 | 設定 |
|
|
1812
|
-
| --- | --- | --- |
|
|
1813
|
-
| Vue | `https://cms.example.com` | `apiOrigin` は下記 Go バックエンド |
|
|
1814
|
-
| Go CMS API | `https://cms-api.example.com` | `baseUrl=https://cms-api.example.com/api/authlink` |
|
|
1815
|
-
| AuthLink API | `https://api.getauthlink.com` | Go SDK の `Origin`;ブラウザーの `authLinkOrigin` |
|
|
1816
|
-
|
|
1817
|
-
AuthLink API は本番の `https://api.getauthlink.com` を使います。Vue と Go CMS の origin は接続先サイト自身の例であり、AuthLink 公式サイトのドメインへ置き換えません。
|
|
1818
|
-
|
|
1819
|
-
テナントに登録するサイト origin は Vue の origin です。Go SDK の Origin と資格情報 JSON の API origin は AuthLink API を指します。ブラウザーの baseUrl は Go の業務 API です。TenantID/APIKey はバックエンドの非公開設定にのみ保存します。
|
|
1820
|
-
|
|
1821
|
-
```sh
|
|
1822
|
-
npm install @auth-link/web@latest vue
|
|
1823
|
-
# In your Go backend module, after unpacking the supplied Go SDK:
|
|
1824
|
-
go mod edit -replace=authlink.local/sdk=./third_party/authlink-go
|
|
1825
|
-
go mod edit -require=authlink.local/sdk@v0.0.0
|
|
1826
|
-
go mod tidy
|
|
1827
|
-
```
|
|
1828
|
-
|
|
1829
|
-
Go SDK はソースまたは公式サイトの Go SDK アーカイブとして取得します。公開 Go module や npm 同梱サーバーではありません。SDK 自身の go.mod を保持し、`authlink "authlink.local/sdk"` を import します。信頼できる設定から `authlink.New(authlink.Config{Origin: authOrigin, TenantID: tenantID, APIKey: apiKey})` で初期化します。
|
|
1830
|
-
|
|
1831
|
-
#### 2. サイトのログインと session
|
|
1832
|
-
|
|
1833
|
-
サイトのログイン API(参照 CMS は POST /api/login)が Secure・HttpOnly の session Cookie を発行します。Vue は credentials=include で GET /api/session を読み、authenticated=true と csrf を確認してから要求を作成します。未ログインならサイト自身のログインへ戻します。
|
|
1834
|
-
|
|
1835
|
-
この CMS の JSON フィールド名は **csrf**、SDK オプション名は **csrfToken** です。`csrfToken: () => session.value?.csrf ?? ''` で対応します。JSON の名前を SDK に合わせる必要はありません。Go が session ごとに生成・保存し、作成と結果照会の両方で X-CSRF-Token を検証します。テナントキーや照合数字を代用しません。
|
|
1836
|
-
|
|
1837
|
-
同じサイトの HTTPS サブドメイン同士は別 origin・同 site です。参照 API の Cookie は Domain を指定しない host-only、SameSite=Strict; Secure; HttpOnly; Path=/ です。別 site の場合は CORS に加えてブラウザーの Cookie 制限も考慮します。
|
|
1838
|
-
|
|
1839
|
-
#### 3. Go の CORS と業務ルート
|
|
1840
|
-
|
|
1841
|
-
```http
|
|
1842
|
-
Access-Control-Allow-Origin: https://cms.example.com
|
|
1843
|
-
Access-Control-Allow-Credentials: true
|
|
1844
|
-
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS
|
|
1845
|
-
Access-Control-Allow-Headers: Content-Type, X-CSRF-Token, Idempotency-Key
|
|
1846
|
-
Vary: Origin
|
|
1847
|
-
Cache-Control: no-store
|
|
1848
|
-
```
|
|
1849
|
-
|
|
1850
|
-
正確に許可した Vue origin にだけ返し、その origin のエラー応答にも付与します。OPTIONS は origin・method・headers を検証して 204 を返し、ログインや CSRF は要求しません。実リクエストでログイン、CSRF、所有者を検証します。任意 origin の反射や * は使いません。PUT は CMS の下書き編集用なので必要なルートに合わせて限定できます。
|
|
1851
|
-
|
|
1852
|
-
| サイト自身のルート | 入力 | 出力 |
|
|
1853
|
-
| --- | --- | --- |
|
|
1854
|
-
| `GET /api/session` | — | `{authenticated:true, csrf:"…", subject:"…", username:"…"}`;未ログイン: `{authenticated:false}` |
|
|
1855
|
-
| `POST /api/authlink/requests` | `{purpose:"bind"}` または `{purpose:"confirm",postId,version}`; `Idempotency-Key` | 公開 `Ticket` |
|
|
1856
|
-
| `POST /api/authlink/requests/{id}/result` | `{}`;現在の session + CSRF | 待機状態/displayCode または検証済み `confirmed` |
|
|
1857
|
-
| `POST /api/posts/{id}/publish` | `{requestId,version}`; 現在の session + CSRF | `{ok:true}` 保存済み確認結果と業務意図の検証後 |
|
|
1858
|
-
|
|
1859
|
-
これらのルートは Go CMS が実装します。postId/version と公開ルートはこの業務の契約で、AuthLink のプロトコル項目ではありません。
|
|
1860
|
-
|
|
1861
|
-
#### 4. 作成前に保存し、検証のコミット後に confirmed
|
|
1862
|
-
|
|
1863
|
-
```text
|
|
1864
|
-
Vue → Go /api/session → current session + csrf
|
|
1865
|
-
Vue → Go /api/authlink/requests → Go SDK CreateRequest → public ticket
|
|
1866
|
-
Vue dialog → Go /api/authlink/requests/{id}/result → Status + Consume
|
|
1867
|
-
Go commits verified receipt → Vue confirmed event
|
|
1868
|
-
Vue → Go /api/posts/{id}/publish → validate saved intent/receipt → publish
|
|
1869
|
-
```
|
|
1870
|
-
|
|
1871
|
-
安定したユーザー ID は認証済み session から取得します。用途、作成キー、記事の所有者と版を検証し、state と消費キーを別々に生成します。上流通信の前に CreateInput、ブラウザーの作成キー、ユーザー/session、記事公開の意図を保存します。通信失敗時は同一レコード・入力・キーを再利用します。session + 作成キーを一意にし、異なる用途・記事・版への再利用を拒否します。
|
|
1872
|
-
|
|
1873
|
-
ticket、requestId、元の expiresAt を保存し、任意の qrSvg を除いて公開 ticket を返します。結果 API は現在の session が所有する記録をロックし、保存済み確認結果があれば再利用します。Status が approved/consumed のときだけ、DB の値から Expected を組み立て Consume を実行します。検証済み確認結果、session の確認記録、監査を requestId/verificationId の一意制約付きトランザクションで保存し、コミット後に confirmed を返します。待機中は displayCode を有効期限を越えてキャッシュしません。
|
|
1874
|
-
|
|
1875
|
-
以下は SDK 呼び出し層であり、完全な HTTP サーバーではありません。DB、トランザクション、所有者検証は説明とコメントに従ってサイト側で実装します。
|
|
1876
|
-
|
|
1877
|
-
```go
|
|
1878
|
-
package cmsauth
|
|
1879
|
-
|
|
1880
|
-
import (
|
|
1881
|
-
"context"
|
|
1882
|
-
authlink "authlink.local/sdk"
|
|
1883
|
-
)
|
|
1884
|
-
|
|
1885
|
-
// Load this record from your database for the authenticated user/session.
|
|
1886
|
-
// Save Input (including State), CreateKey and ConsumeKey BEFORE calling Create.
|
|
1887
|
-
// Intent (post ID/version), ownership and unique constraints belong in your DB.
|
|
1888
|
-
type StoredRequest struct {
|
|
1889
|
-
Input authlink.CreateInput
|
|
1890
|
-
CreateKey string
|
|
1891
|
-
ConsumeKey string
|
|
1892
|
-
Ticket authlink.Ticket
|
|
1893
|
-
}
|
|
1894
|
-
|
|
1895
|
-
// On network retries, load the SAME record; do not regenerate State or keys.
|
|
1896
|
-
func Create(ctx context.Context, sdk *authlink.Client, saved StoredRequest) (authlink.Ticket, error) {
|
|
1897
|
-
return sdk.CreateRequest(ctx, saved.Input, saved.CreateKey)
|
|
1898
|
-
}
|
|
1899
|
-
|
|
1900
|
-
type PublicConfirmation struct {
|
|
1901
|
-
Status string `json:"status"`
|
|
1902
|
-
RequestID string `json:"requestId"`
|
|
1903
|
-
VerificationID string `json:"verificationId"`
|
|
1904
|
-
Purpose string `json:"purpose"`
|
|
1905
|
-
ExpiresAt string `json:"expiresAt"`
|
|
1906
|
-
AuthenticationPolicy string `json:"authenticationPolicy"`
|
|
1907
|
-
}
|
|
1908
|
-
|
|
1909
|
-
// Caller checks session/CSRF/ownership, locks the saved record and first returns
|
|
1910
|
-
// any already-saved receipt. For a new confirmed result, caller must persist
|
|
1911
|
-
// the receipt and confirmation in a DB transaction BEFORE returning HTTP 200.
|
|
1912
|
-
func Poll(ctx context.Context, sdk *authlink.Client, saved StoredRequest) (any, error) {
|
|
1913
|
-
status, err := sdk.Status(ctx, saved.Ticket.RequestID)
|
|
1914
|
-
if err != nil { return nil, err }
|
|
1915
|
-
if status.Status != "approved" && status.Status != "consumed" { return status, nil }
|
|
1916
|
-
result, err := sdk.Consume(ctx, authlink.Expected{
|
|
1917
|
-
RequestID: saved.Ticket.RequestID,
|
|
1918
|
-
ExternalUserID: saved.Input.ExternalUserID,
|
|
1919
|
-
Purpose: saved.Input.Purpose,
|
|
1920
|
-
State: saved.Input.State,
|
|
1921
|
-
ExpiresAt: saved.Ticket.ExpiresAt,
|
|
1922
|
-
}, saved.ConsumeKey)
|
|
1923
|
-
if err != nil { return nil, err }
|
|
1924
|
-
return PublicConfirmation{
|
|
1925
|
-
Status: "confirmed", RequestID: result.RequestID,
|
|
1926
|
-
VerificationID: result.VerificationID, Purpose: result.Purpose,
|
|
1927
|
-
ExpiresAt: saved.Ticket.ExpiresAt, AuthenticationPolicy: result.AuthenticationPolicy,
|
|
1928
|
-
}, nil
|
|
1929
|
-
}
|
|
1930
|
-
```
|
|
1931
|
-
|
|
1932
|
-
#### 5. Vue のライフサイクルと業務データ付き要求
|
|
1933
|
-
|
|
1934
|
-
完全なファイルは `examples/vue-cms.vue` にも同梱します。サイトのログイン後、信頼できる apiOrigin/authLinkOrigin と任意の保存済み下書き `post={id,version}` を渡してマウントします。親は認証 session の識別子を key に使います。ログアウト・再ログイン・アカウント切り替えでは先にアンマウントし、古い ticket・作成キー・未完了の公開処理を消去してから新規マウントします。
|
|
1935
|
-
|
|
1936
|
-
```vue
|
|
1937
|
-
<script setup lang="ts">
|
|
1938
|
-
import { markRaw, onMounted, onUnmounted, ref, shallowRef } from 'vue';
|
|
1939
|
-
import { createAuthLinkClient, requestKey, validateTicket } from '@auth-link/web';
|
|
1940
|
-
import type { Confirmation, Mode, Ticket } from '@auth-link/web';
|
|
1941
|
-
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/vue';
|
|
1942
|
-
import '@auth-link/web/styles.css';
|
|
1943
|
-
|
|
1944
|
-
type Post = { id: string; version: number };
|
|
1945
|
-
type Publication = Post & { requestId: string };
|
|
1946
|
-
// Supply trusted deployment configuration. Mount after site login and remount
|
|
1947
|
-
// with :key="session.subject" after login, logout or account/session changes.
|
|
1948
|
-
const props = defineProps<{ apiOrigin: string; authLinkOrigin: string; post?: Post }>();
|
|
1949
|
-
const session = ref<{ authenticated: boolean; csrf?: string } | null>(null);
|
|
1950
|
-
const ticket = shallowRef<Ticket | null>(null);
|
|
1951
|
-
const publication = shallowRef<Post | null>(null);
|
|
1952
|
-
const retryPublish = shallowRef<Publication | null>(null);
|
|
1953
|
-
const busy = ref(false), message = ref('');
|
|
1954
|
-
let creation: { signature: string; key: string } | null = null;
|
|
1955
|
-
const lifetime = new AbortController();
|
|
1956
|
-
const client = markRaw(createAuthLinkClient({
|
|
1957
|
-
baseUrl: `${props.apiOrigin}/api/authlink`,
|
|
1958
|
-
allowedBackendOrigins: [props.apiOrigin],
|
|
1959
|
-
credentials: 'include',
|
|
1960
|
-
csrfToken: () => session.value?.csrf ?? '',
|
|
1961
|
-
authLinkOrigin: props.authLinkOrigin,
|
|
1962
|
-
}));
|
|
1963
|
-
|
|
1964
|
-
async function api(path: string, body?: unknown, headers: Record<string, string> = {}) {
|
|
1965
|
-
const response = await fetch(`${props.apiOrigin}${path}`, {
|
|
1966
|
-
method: body === undefined ? 'GET' : 'POST',
|
|
1967
|
-
credentials: 'include', cache: 'no-store', redirect: 'error',
|
|
1968
|
-
signal: lifetime.signal,
|
|
1969
|
-
headers: body === undefined ? {} : {
|
|
1970
|
-
'Content-Type': 'application/json', 'X-CSRF-Token': session.value?.csrf ?? '', ...headers,
|
|
1971
|
-
},
|
|
1972
|
-
body: body === undefined ? undefined : JSON.stringify(body),
|
|
1973
|
-
});
|
|
1974
|
-
const value = await response.json();
|
|
1975
|
-
if (response.status === 401) {
|
|
1976
|
-
session.value = null; closeTicket(); retryPublish.value = null; creation = null;
|
|
1977
|
-
}
|
|
1978
|
-
if (!response.ok) throw new Error(value.code ?? 'REQUEST_FAILED');
|
|
1979
|
-
return value;
|
|
1980
|
-
}
|
|
1981
|
-
function closeTicket() { ticket.value = null; publication.value = null; }
|
|
1982
|
-
function showError(error: Error) { message.value = error.message; }
|
|
1983
|
-
function finish(text: string) { closeTicket(); message.value = text; }
|
|
1984
|
-
|
|
1985
|
-
async function start(purpose: Mode, post?: Post) {
|
|
1986
|
-
if (busy.value || ticket.value || !session.value?.authenticated) return;
|
|
1987
|
-
busy.value = true; message.value = ''; retryPublish.value = null;
|
|
1988
|
-
const intent = post ? { id: post.id, version: post.version } : null;
|
|
1989
|
-
const signature = JSON.stringify({ purpose, postId: intent?.id, version: intent?.version });
|
|
1990
|
-
try {
|
|
1991
|
-
if (creation?.signature !== signature) creation = { signature, key: requestKey() };
|
|
1992
|
-
// SDK create() sends only {purpose}. Business fields use your own API.
|
|
1993
|
-
const value = intent
|
|
1994
|
-
? validateTicket(await api('/api/authlink/requests', {
|
|
1995
|
-
purpose, postId: intent.id, version: intent.version,
|
|
1996
|
-
}, { 'Idempotency-Key': creation.key }), purpose, props.authLinkOrigin)
|
|
1997
|
-
: await client.create(purpose, { idempotencyKey: creation.key, signal: lifetime.signal });
|
|
1998
|
-
if (lifetime.signal.aborted) return;
|
|
1999
|
-
publication.value = intent; ticket.value = value; creation = null;
|
|
2000
|
-
} catch (error) {
|
|
2001
|
-
if (!lifetime.signal.aborted) showError(error as Error);
|
|
2002
|
-
// Retain creation.key for a retry of the SAME purpose/post/version.
|
|
2003
|
-
} finally { busy.value = false; }
|
|
2004
|
-
}
|
|
2005
|
-
async function publish() {
|
|
2006
|
-
const intent = retryPublish.value;
|
|
2007
|
-
if (!intent || busy.value) return;
|
|
2008
|
-
busy.value = true;
|
|
2009
|
-
try {
|
|
2010
|
-
await api(`/api/posts/${intent.id}/publish`, { version: intent.version, requestId: intent.requestId });
|
|
2011
|
-
retryPublish.value = null; message.value = 'Published. Reload your posts from the backend.';
|
|
2012
|
-
} catch (error) { if (!lifetime.signal.aborted) showError(error as Error); }
|
|
2013
|
-
finally { busy.value = false; }
|
|
2014
|
-
}
|
|
2015
|
-
async function confirmed(result: Confirmation) {
|
|
2016
|
-
const intent = publication.value;
|
|
2017
|
-
closeTicket();
|
|
2018
|
-
if (intent) { retryPublish.value = { ...intent, requestId: result.requestId }; await publish(); }
|
|
2019
|
-
else message.value = 'Verified. Reload account status from the backend.';
|
|
2020
|
-
}
|
|
2021
|
-
onMounted(async () => {
|
|
2022
|
-
try {
|
|
2023
|
-
const value = await api('/api/session');
|
|
2024
|
-
if (value.authenticated !== true || typeof value.csrf !== 'string' || !value.csrf) {
|
|
2025
|
-
throw new Error('LOGIN_REQUIRED');
|
|
2026
|
-
}
|
|
2027
|
-
session.value = value;
|
|
2028
|
-
} catch (error) { if (!lifetime.signal.aborted) showError(error as Error); }
|
|
2029
|
-
});
|
|
2030
|
-
onUnmounted(() => { lifetime.abort(); closeTicket(); creation = null; retryPublish.value = null; });
|
|
175
|
+
<script setup>
|
|
176
|
+
import { AuthLinkPasscode } from '@auth-link/web/vue';
|
|
2031
177
|
</script>
|
|
2032
|
-
|
|
2033
178
|
<template>
|
|
2034
|
-
<
|
|
2035
|
-
|
|
2036
|
-
<button v-if="post" :disabled="busy || !!ticket || !session?.authenticated" @click="start('confirm', post)">Confirm publication</button>
|
|
2037
|
-
<button v-if="retryPublish" :disabled="busy || !!ticket" @click="publish">Retry the same publication</button>
|
|
2038
|
-
<AuthLinkBind v-if="ticket?.purpose === 'bind'" :ticket="ticket" :client="client" variant="B"
|
|
2039
|
-
@confirmed="confirmed" @close="finish('Closed')" @rejected="finish('Rejected')"
|
|
2040
|
-
@expired="finish('Expired; start a new request')" @error="showError" />
|
|
2041
|
-
<AuthLinkConfirm v-else-if="ticket?.purpose === 'confirm'" :ticket="ticket" :client="client" variant="B"
|
|
2042
|
-
@confirmed="confirmed" @close="finish('Closed')" @rejected="finish('Rejected')"
|
|
2043
|
-
@expired="finish('Expired; start a new request')" @error="showError" />
|
|
2044
|
-
<p role="status">{{ message }}</p>
|
|
179
|
+
<AuthLinkPasscode :client="client" :expires-at="pending.expiresAt"
|
|
180
|
+
locale="zh-CN" variant="B" @verified="updateUI" />
|
|
2045
181
|
</template>
|
|
2046
182
|
```
|
|
2047
183
|
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
マウント時は既存要求を監視し、mounted/watch で新規作成しません。閉じる・拒否・期限切れでは ticket を消去し、通信エラーでは同じ要求を再試行できるよう表示を維持します。confirmed 後は表示を閉じ、独立した公開 API を呼びます。失敗時は同じ requestId/記事/版で再試行し、実状態をバックエンドから再取得します。サイト自身のログインフォーム・記事一覧・エラー翻訳は例から省略しています。
|
|
2051
|
-
|
|
2052
|
-
#### 6. 公開トランザクションで再検証
|
|
184
|
+
### 失敗と終了処理
|
|
2053
185
|
|
|
2054
|
-
|
|
186
|
+
使用済みコードは別操作や別セッションに使えません。ログインや初回連携直後は次のコードを待ちます。PASSCODE_INVALID、PASSCODE_USED、PASSCODE_LOCKEDを成功として扱わないでください。通信結果不明時は元の冪等キーとコードを保持して再試行し、業務を二重実行しません。
|
|
2055
187
|
|
|
2056
|
-
|
|
188
|
+
destroy()はブラウザー要求を中止してタイマーを解除し、終了コールバックを呼びません。close()はonCloseも呼びます。画面を閉じてもサーバー処理は元に戻らず、キャンセルと保留中操作はCMS側で管理します。待機やローカル期限判定はポーリングしません。
|
|
2057
189
|
|
|
2058
|
-
|
|
190
|
+
旧openAuthLink / Ticket / Consumeは以前のプロトコル向けに残ります。新アプリはopenPasscode / AuthLinkPasscodeとサーバーのAuthenticate / authenticateを使います。旧連携の移行機能は提供しません。
|