@auth-link/web 0.0.1 → 0.0.3
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 -4
- package/LICENSE +21 -0
- package/README.md +1386 -120
- package/dist/index.js +50 -11
- package/dist/index.js.map +2 -2
- package/dist/react.js.map +2 -2
- package/dist/types/core.d.ts +13 -2
- package/dist/types/index.d.ts +1 -0
- package/dist/vue.js +12 -3
- package/dist/vue.js.map +2 -2
- package/docs/README.en.md +180 -25
- package/docs/README.ja.md +199 -44
- package/docs/README.zh-CN.md +251 -58
- package/docs/go-vue.en.md +254 -0
- package/docs/go-vue.ja.md +254 -0
- package/docs/go-vue.zh-CN.md +258 -0
- package/examples/vue-cms.vue +109 -0
- package/package.json +5 -3
package/README.md
CHANGED
|
@@ -6,6 +6,12 @@
|
|
|
6
6
|
|
|
7
7
|
Responsive dialogs for **AuthLink phone binding and mobile confirmation**, with direct function calls and React / Vue components. Display binding QR codes, synchronized six-digit matching codes, countdowns and confirmation results in any web application. No particular site platform is required.
|
|
8
8
|
|
|
9
|
+
### Go backend + Vue walkthrough
|
|
10
|
+
|
|
11
|
+
Start with [Go + Vue: login, binding and confirmed publication](#go-vue-cms-en) and the `examples/vue-cms.vue`.
|
|
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
|
+
|
|
9
15
|
### Features
|
|
10
16
|
|
|
11
17
|
- Phone-binding QR codes generated locally in the browser.
|
|
@@ -28,41 +34,148 @@ Compatibility: React 18.2+ / 19, Vue 3.3+, TypeScript, ESM. Install only the fra
|
|
|
28
34
|
### Browser integration
|
|
29
35
|
|
|
30
36
|
1. Configure your backend's AuthLink tenant credentials.
|
|
31
|
-
2. Implement the two same-origin
|
|
37
|
+
2. Implement the two application backend endpoints below (same-origin or explicitly allowed cross-origin), authenticated to the current website user.
|
|
32
38
|
3. Create a request on a user action and pass its ticket to a component.
|
|
33
39
|
4. Your backend verifies and consumes the result before returning a confirmed response.
|
|
34
40
|
|
|
35
|
-
The browser can call this library directly. Tenant credentials and result consumption belong on your backend; never embed a tenant API key in frontend code. The supplied client
|
|
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)
|
|
36
44
|
|
|
37
|
-
|
|
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`:
|
|
38
56
|
|
|
39
57
|
```ts
|
|
40
58
|
// authlink-client.ts
|
|
41
|
-
import { createAuthLinkClient
|
|
59
|
+
import { createAuthLinkClient } from '@auth-link/web';
|
|
42
60
|
import '@auth-link/web/styles.css';
|
|
43
61
|
|
|
62
|
+
// The application server renders this meta element using the current session's
|
|
63
|
+
// CSRF token. This function only reads that token; it does not generate one.
|
|
64
|
+
export function readCsrfTokenFromYourCms(): string {
|
|
65
|
+
const token = document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.content;
|
|
66
|
+
if (!token) throw new Error('Missing CSRF token; load the authenticated application page first.');
|
|
67
|
+
return token;
|
|
68
|
+
}
|
|
69
|
+
|
|
44
70
|
export const client = createAuthLinkClient({
|
|
45
71
|
baseUrl: '/api/authlink',
|
|
46
|
-
csrfToken:
|
|
47
|
-
|
|
48
|
-
if (!token) throw new Error('Missing CSRF token');
|
|
49
|
-
return token;
|
|
50
|
-
},
|
|
72
|
+
csrfToken: readCsrfTokenFromYourCms,
|
|
73
|
+
// Replace this example with the configured AuthLink service origin.
|
|
51
74
|
authLinkOrigin: 'https://auth.example.com',
|
|
52
75
|
});
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Replace `https://auth.example.com` with the configured AuthLink origin. Create requests only in user event handlers, as in the React example below.
|
|
79
|
+
|
|
80
|
+
### Separate frontend and backend origins (since 0.0.2)
|
|
81
|
+
|
|
82
|
+
The default is still same-origin `/api/authlink`. For direct cross-origin requests, configure an absolute `baseUrl` and exact `allowedBackendOrigins`, for example frontend `https://www.example.com` and application API `https://api.example.com`. Subdomains and different ports are different origins. Entries must be origins only, without paths, wildcards or embedded credentials, and must come from trusted configuration. HTTPS is required except for explicitly allowed HTTP loopback development origins (localhost, 127.0.0.1, [::1]).
|
|
83
|
+
|
|
84
|
+
The SDK validates the destination before evaluating credentials and refuses redirects. `authLinkOrigin` separately validates the AuthLink service origin encoded in the QR; it is not the application API allowlist.
|
|
85
|
+
|
|
86
|
+
#### Cross-origin session cookies
|
|
87
|
+
|
|
88
|
+
This complete initialization function uses an example `GET /api/session` endpoint that **your application implements**, returning `{ "csrfToken": "current-session-token" }` for the authenticated session with `Cache-Control: no-store` and CORS enabled. Replace that path with your existing session endpoint.
|
|
89
|
+
|
|
90
|
+
`csrfToken` is the JSON property chosen for this generic example. The Go CMS walkthrough uses `{ authenticated: true, csrf: '…' }` instead; map session.csrf to the SDK csrfToken callback without renaming your backend response.
|
|
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.
|
|
53
121
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
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
|
+
}
|
|
58
138
|
```
|
|
59
139
|
|
|
60
|
-
|
|
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.
|
|
61
173
|
|
|
62
174
|
### Open a dialog directly (React, Vue or plain JavaScript)
|
|
63
175
|
|
|
64
176
|
```ts
|
|
65
177
|
import { openAuthLinkBind, openAuthLinkConfirm, requestKey } from '@auth-link/web';
|
|
178
|
+
import { client } from './authlink-client';
|
|
66
179
|
import '@auth-link/web/styles.css';
|
|
67
180
|
|
|
68
181
|
// Call in your button handler, after your backend creates the request.
|
|
@@ -81,22 +194,62 @@ The dialog adapts to mobile widths, has a scrollable height, keyboard Escape and
|
|
|
81
194
|
|
|
82
195
|
### React
|
|
83
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" />`.
|
|
198
|
+
|
|
84
199
|
```tsx
|
|
200
|
+
"use client";
|
|
201
|
+
import { useRef, useState } from 'react';
|
|
202
|
+
import { requestKey } from '@auth-link/web';
|
|
203
|
+
import type { Mode, Ticket } from '@auth-link/web';
|
|
85
204
|
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/react';
|
|
86
|
-
import type { Ticket, Confirmation } from '@auth-link/web';
|
|
87
205
|
import { client } from './authlink-client';
|
|
88
206
|
|
|
89
|
-
export function
|
|
90
|
-
const
|
|
91
|
-
|
|
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); }
|
|
92
235
|
};
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
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
|
+
</>;
|
|
97
247
|
}
|
|
98
248
|
```
|
|
99
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
|
+
|
|
100
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.
|
|
101
254
|
|
|
102
255
|
### Vue
|
|
@@ -177,7 +330,7 @@ Rejection returns `{ status: 'rejected', code: 'REJECTED', requestId, purpose }`
|
|
|
177
330
|
|
|
178
331
|
### Backend contract
|
|
179
332
|
|
|
180
|
-
The default prefix is `/api/authlink`. Both endpoints
|
|
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.
|
|
181
334
|
|
|
182
335
|
```ts
|
|
183
336
|
import type { Ticket, Result } from '@auth-link/web';
|
|
@@ -204,7 +357,7 @@ import type { Ticket, Result } from '@auth-link/web';
|
|
|
204
357
|
|
|
205
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.
|
|
206
359
|
|
|
207
|
-
The result endpoint verifies
|
|
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.
|
|
208
361
|
|
|
209
362
|
### Languages
|
|
210
363
|
|
|
@@ -230,6 +383,8 @@ Missing or unsupported locale codes fall back to Simplified Chinese. The panel s
|
|
|
230
383
|
|
|
231
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.
|
|
232
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
|
+
|
|
233
388
|
| Import | Contents |
|
|
234
389
|
| --- | --- |
|
|
235
390
|
| `@auth-link/web` | Client, request key, supported locales, types and core tools |
|
|
@@ -249,36 +404,272 @@ Explicitly import `@auth-link/web/styles.css`. Override `--authlink-foreground`,
|
|
|
249
404
|
|
|
250
405
|
### License
|
|
251
406
|
|
|
252
|
-
|
|
407
|
+
MIT. See `LICENSE` for the full license text and `THIRD_PARTY_NOTICES.md` for bundled third-party attribution.
|
|
253
408
|
|
|
254
|
-
|
|
409
|
+
### Go Vue CMS: en
|
|
255
410
|
|
|
256
|
-
|
|
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.
|
|
257
412
|
|
|
258
|
-
|
|
413
|
+
#### 1. Install and separate the three origins
|
|
259
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://auth.example.com` | Go SDK `Origin`; browser `authLinkOrigin` |
|
|
260
420
|
|
|
261
|
-
|
|
421
|
+
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.
|
|
262
422
|
|
|
263
|
-
```
|
|
264
|
-
|
|
423
|
+
```sh
|
|
424
|
+
npm install @auth-link/web@latest vue
|
|
425
|
+
# In your Go backend module, after unpacking the supplied Go SDK:
|
|
426
|
+
go mod edit -replace=authlink.local/sdk=./third_party/authlink-go
|
|
427
|
+
go mod edit -require=authlink.local/sdk@v0.0.0
|
|
428
|
+
go mod tidy
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
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`.
|
|
432
|
+
|
|
433
|
+
#### 2. Log in to the website and load its session
|
|
434
|
+
|
|
435
|
+
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.
|
|
436
|
+
|
|
437
|
+
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.
|
|
438
|
+
|
|
439
|
+
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.
|
|
440
|
+
|
|
441
|
+
#### 3. Configure Go CORS and application routes
|
|
442
|
+
|
|
443
|
+
```http
|
|
444
|
+
Access-Control-Allow-Origin: https://cms.example.com
|
|
445
|
+
Access-Control-Allow-Credentials: true
|
|
446
|
+
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS
|
|
447
|
+
Access-Control-Allow-Headers: Content-Type, X-CSRF-Token, Idempotency-Key
|
|
448
|
+
Vary: Origin
|
|
449
|
+
Cache-Control: no-store
|
|
450
|
+
```
|
|
451
|
+
|
|
452
|
+
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.
|
|
453
|
+
|
|
454
|
+
| Application route | Input | Output |
|
|
455
|
+
| --- | --- | --- |
|
|
456
|
+
| `GET /api/session` | — | `{authenticated:true, csrf:"…", subject:"…", username:"…"}`; logged out: `{authenticated:false}` |
|
|
457
|
+
| `POST /api/authlink/requests` | `{purpose:"bind"}` or `{purpose:"confirm",postId,version}`; `Idempotency-Key` | Public `Ticket` |
|
|
458
|
+
| `POST /api/authlink/requests/{id}/result` | `{}`; current session + CSRF | Pending status/displayCode or verified `confirmed` receipt |
|
|
459
|
+
| `POST /api/posts/{id}/publish` | `{requestId,version}`; current session + CSRF | `{ok:true}` after checking the saved confirmation and intent |
|
|
460
|
+
|
|
461
|
+
Your Go application implements all four routes. postId/version and the publication route are application-specific conventions, not AuthLink fields.
|
|
462
|
+
|
|
463
|
+
#### 4. Persist before creation; commit verification before confirmed
|
|
464
|
+
|
|
465
|
+
```text
|
|
466
|
+
Vue → Go /api/session → current session + csrf
|
|
467
|
+
Vue → Go /api/authlink/requests → Go SDK CreateRequest → public ticket
|
|
468
|
+
Vue dialog → Go /api/authlink/requests/{id}/result → Status + Consume
|
|
469
|
+
Go commits verified receipt → Vue confirmed event
|
|
470
|
+
Vue → Go /api/posts/{id}/publish → validate saved intent/receipt → publish
|
|
471
|
+
```
|
|
472
|
+
|
|
473
|
+
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.
|
|
474
|
+
|
|
475
|
+
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.
|
|
476
|
+
|
|
477
|
+
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.
|
|
478
|
+
|
|
479
|
+
```go
|
|
480
|
+
package cmsauth
|
|
481
|
+
|
|
482
|
+
import (
|
|
483
|
+
"context"
|
|
484
|
+
authlink "authlink.local/sdk"
|
|
485
|
+
)
|
|
486
|
+
|
|
487
|
+
// Load this record from your database for the authenticated user/session.
|
|
488
|
+
// Save Input (including State), CreateKey and ConsumeKey BEFORE calling Create.
|
|
489
|
+
// Intent (post ID/version), ownership and unique constraints belong in your DB.
|
|
490
|
+
type StoredRequest struct {
|
|
491
|
+
Input authlink.CreateInput
|
|
492
|
+
CreateKey string
|
|
493
|
+
ConsumeKey string
|
|
494
|
+
Ticket authlink.Ticket
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// On network retries, load the SAME record; do not regenerate State or keys.
|
|
498
|
+
func Create(ctx context.Context, sdk *authlink.Client, saved StoredRequest) (authlink.Ticket, error) {
|
|
499
|
+
return sdk.CreateRequest(ctx, saved.Input, saved.CreateKey)
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
type PublicConfirmation struct {
|
|
503
|
+
Status string `json:"status"`
|
|
504
|
+
RequestID string `json:"requestId"`
|
|
505
|
+
VerificationID string `json:"verificationId"`
|
|
506
|
+
Purpose string `json:"purpose"`
|
|
507
|
+
ExpiresAt string `json:"expiresAt"`
|
|
508
|
+
AuthenticationPolicy string `json:"authenticationPolicy"`
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// Caller checks session/CSRF/ownership, locks the saved record and first returns
|
|
512
|
+
// any already-saved receipt. For a new confirmed result, caller must persist
|
|
513
|
+
// the receipt and confirmation in a DB transaction BEFORE returning HTTP 200.
|
|
514
|
+
func Poll(ctx context.Context, sdk *authlink.Client, saved StoredRequest) (any, error) {
|
|
515
|
+
status, err := sdk.Status(ctx, saved.Ticket.RequestID)
|
|
516
|
+
if err != nil { return nil, err }
|
|
517
|
+
if status.Status != "approved" && status.Status != "consumed" { return status, nil }
|
|
518
|
+
result, err := sdk.Consume(ctx, authlink.Expected{
|
|
519
|
+
RequestID: saved.Ticket.RequestID,
|
|
520
|
+
ExternalUserID: saved.Input.ExternalUserID,
|
|
521
|
+
Purpose: saved.Input.Purpose,
|
|
522
|
+
State: saved.Input.State,
|
|
523
|
+
ExpiresAt: saved.Ticket.ExpiresAt,
|
|
524
|
+
}, saved.ConsumeKey)
|
|
525
|
+
if err != nil { return nil, err }
|
|
526
|
+
return PublicConfirmation{
|
|
527
|
+
Status: "confirmed", RequestID: result.RequestID,
|
|
528
|
+
VerificationID: result.VerificationID, Purpose: result.Purpose,
|
|
529
|
+
ExpiresAt: saved.Ticket.ExpiresAt, AuthenticationPolicy: result.AuthenticationPolicy,
|
|
530
|
+
}, nil
|
|
531
|
+
}
|
|
532
|
+
```
|
|
533
|
+
|
|
534
|
+
#### 5. Vue lifecycle and business-bound requests
|
|
535
|
+
|
|
536
|
+
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.
|
|
537
|
+
|
|
538
|
+
```vue
|
|
539
|
+
<script setup lang="ts">
|
|
540
|
+
import { markRaw, onMounted, onUnmounted, ref, shallowRef } from 'vue';
|
|
541
|
+
import { createAuthLinkClient, requestKey, validateTicket } from '@auth-link/web';
|
|
542
|
+
import type { Confirmation, Mode, Ticket } from '@auth-link/web';
|
|
543
|
+
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/vue';
|
|
265
544
|
import '@auth-link/web/styles.css';
|
|
266
545
|
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
546
|
+
type Post = { id: string; version: number };
|
|
547
|
+
type Publication = Post & { requestId: string };
|
|
548
|
+
// Supply trusted deployment configuration. Mount after site login and remount
|
|
549
|
+
// with :key="session.subject" after login, logout or account/session changes.
|
|
550
|
+
const props = defineProps<{ apiOrigin: string; authLinkOrigin: string; post?: Post }>();
|
|
551
|
+
const session = ref<{ authenticated: boolean; csrf?: string } | null>(null);
|
|
552
|
+
const ticket = shallowRef<Ticket | null>(null);
|
|
553
|
+
const publication = shallowRef<Post | null>(null);
|
|
554
|
+
const retryPublish = shallowRef<Publication | null>(null);
|
|
555
|
+
const busy = ref(false), message = ref('');
|
|
556
|
+
let creation: { signature: string; key: string } | null = null;
|
|
557
|
+
const lifetime = new AbortController();
|
|
558
|
+
const client = markRaw(createAuthLinkClient({
|
|
559
|
+
baseUrl: `${props.apiOrigin}/api/authlink`,
|
|
560
|
+
allowedBackendOrigins: [props.apiOrigin],
|
|
561
|
+
credentials: 'include',
|
|
562
|
+
csrfToken: () => session.value?.csrf ?? '',
|
|
563
|
+
authLinkOrigin: props.authLinkOrigin,
|
|
564
|
+
}));
|
|
565
|
+
|
|
566
|
+
async function api(path: string, body?: unknown, headers: Record<string, string> = {}) {
|
|
567
|
+
const response = await fetch(`${props.apiOrigin}${path}`, {
|
|
568
|
+
method: body === undefined ? 'GET' : 'POST',
|
|
569
|
+
credentials: 'include', cache: 'no-store', redirect: 'error',
|
|
570
|
+
signal: lifetime.signal,
|
|
571
|
+
headers: body === undefined ? {} : {
|
|
572
|
+
'Content-Type': 'application/json', 'X-CSRF-Token': session.value?.csrf ?? '', ...headers,
|
|
573
|
+
},
|
|
574
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
575
|
+
});
|
|
576
|
+
const value = await response.json();
|
|
577
|
+
if (response.status === 401) {
|
|
578
|
+
session.value = null; closeTicket(); retryPublish.value = null; creation = null;
|
|
579
|
+
}
|
|
580
|
+
if (!response.ok) throw new Error(value.code ?? 'REQUEST_FAILED');
|
|
581
|
+
return value;
|
|
582
|
+
}
|
|
583
|
+
function closeTicket() { ticket.value = null; publication.value = null; }
|
|
584
|
+
function showError(error: Error) { message.value = error.message; }
|
|
585
|
+
function finish(text: string) { closeTicket(); message.value = text; }
|
|
586
|
+
|
|
587
|
+
async function start(purpose: Mode, post?: Post) {
|
|
588
|
+
if (busy.value || ticket.value || !session.value?.authenticated) return;
|
|
589
|
+
busy.value = true; message.value = ''; retryPublish.value = null;
|
|
590
|
+
const intent = post ? { id: post.id, version: post.version } : null;
|
|
591
|
+
const signature = JSON.stringify({ purpose, postId: intent?.id, version: intent?.version });
|
|
592
|
+
try {
|
|
593
|
+
if (creation?.signature !== signature) creation = { signature, key: requestKey() };
|
|
594
|
+
// SDK create() sends only {purpose}. Business fields use your own API.
|
|
595
|
+
const value = intent
|
|
596
|
+
? validateTicket(await api('/api/authlink/requests', {
|
|
597
|
+
purpose, postId: intent.id, version: intent.version,
|
|
598
|
+
}, { 'Idempotency-Key': creation.key }), purpose, props.authLinkOrigin)
|
|
599
|
+
: await client.create(purpose, { idempotencyKey: creation.key, signal: lifetime.signal });
|
|
600
|
+
if (lifetime.signal.aborted) return;
|
|
601
|
+
publication.value = intent; ticket.value = value; creation = null;
|
|
602
|
+
} catch (error) {
|
|
603
|
+
if (!lifetime.signal.aborted) showError(error as Error);
|
|
604
|
+
// Retain creation.key for a retry of the SAME purpose/post/version.
|
|
605
|
+
} finally { busy.value = false; }
|
|
606
|
+
}
|
|
607
|
+
async function publish() {
|
|
608
|
+
const intent = retryPublish.value;
|
|
609
|
+
if (!intent || busy.value) return;
|
|
610
|
+
busy.value = true;
|
|
611
|
+
try {
|
|
612
|
+
await api(`/api/posts/${intent.id}/publish`, { version: intent.version, requestId: intent.requestId });
|
|
613
|
+
retryPublish.value = null; message.value = 'Published. Reload your posts from the backend.';
|
|
614
|
+
} catch (error) { if (!lifetime.signal.aborted) showError(error as Error); }
|
|
615
|
+
finally { busy.value = false; }
|
|
616
|
+
}
|
|
617
|
+
async function confirmed(result: Confirmation) {
|
|
618
|
+
const intent = publication.value;
|
|
619
|
+
closeTicket();
|
|
620
|
+
if (intent) { retryPublish.value = { ...intent, requestId: result.requestId }; await publish(); }
|
|
621
|
+
else message.value = 'Verified. Reload account status from the backend.';
|
|
622
|
+
}
|
|
623
|
+
onMounted(async () => {
|
|
624
|
+
try {
|
|
625
|
+
const value = await api('/api/session');
|
|
626
|
+
if (value.authenticated !== true || typeof value.csrf !== 'string' || !value.csrf) {
|
|
627
|
+
throw new Error('LOGIN_REQUIRED');
|
|
628
|
+
}
|
|
629
|
+
session.value = value;
|
|
630
|
+
} catch (error) { if (!lifetime.signal.aborted) showError(error as Error); }
|
|
274
631
|
});
|
|
275
|
-
|
|
276
|
-
|
|
632
|
+
onUnmounted(() => { lifetime.abort(); closeTicket(); creation = null; retryPublish.value = null; });
|
|
633
|
+
</script>
|
|
634
|
+
|
|
635
|
+
<template>
|
|
636
|
+
<button :disabled="busy || !!ticket || !session?.authenticated" @click="start('bind')">Bind phone</button>
|
|
637
|
+
<button :disabled="busy || !!ticket || !session?.authenticated" @click="start('confirm')">Confirm</button>
|
|
638
|
+
<button v-if="post" :disabled="busy || !!ticket || !session?.authenticated" @click="start('confirm', post)">Confirm publication</button>
|
|
639
|
+
<button v-if="retryPublish" :disabled="busy || !!ticket" @click="publish">Retry the same publication</button>
|
|
640
|
+
<AuthLinkBind v-if="ticket?.purpose === 'bind'" :ticket="ticket" :client="client" variant="B"
|
|
641
|
+
@confirmed="confirmed" @close="finish('Closed')" @rejected="finish('Rejected')"
|
|
642
|
+
@expired="finish('Expired; start a new request')" @error="showError" />
|
|
643
|
+
<AuthLinkConfirm v-else-if="ticket?.purpose === 'confirm'" :ticket="ticket" :client="client" variant="B"
|
|
644
|
+
@confirmed="confirmed" @close="finish('Closed')" @rejected="finish('Rejected')"
|
|
645
|
+
@expired="finish('Expired; start a new request')" @error="showError" />
|
|
646
|
+
<p role="status">{{ message }}</p>
|
|
647
|
+
</template>
|
|
277
648
|
```
|
|
278
649
|
|
|
279
|
-
|
|
650
|
+
`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.
|
|
280
651
|
|
|
281
|
-
|
|
652
|
+
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.
|
|
653
|
+
|
|
654
|
+
#### 6. Recheck confirmation in the publish transaction
|
|
655
|
+
|
|
656
|
+
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.
|
|
657
|
+
|
|
658
|
+
#### Acceptance sequence
|
|
659
|
+
|
|
660
|
+
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.
|
|
661
|
+
|
|
662
|
+
---
|
|
663
|
+
|
|
664
|
+
## 简体中文
|
|
665
|
+
|
|
666
|
+
**AuthLink 官方前端组件包**,帮助网站接入手机绑定与 App 确认流程,支持 React 18/19、Vue 3.3+、TypeScript 和 ESM。
|
|
667
|
+
|
|
668
|
+
### Go + Vue 完整接入
|
|
669
|
+
|
|
670
|
+
按实际 CMS 流程接入,推荐先读 [Go + Vue:从登录、绑定到确认发布](#go-vue-cms-zh-cn),完整组件见 `examples/vue-cms.vue`。
|
|
671
|
+
|
|
672
|
+
顺序是:网站登录 → 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。
|
|
282
673
|
|
|
283
674
|
|
|
284
675
|
### 功能
|
|
@@ -294,7 +685,7 @@ React / Vue 的 AuthLinkBind、AuthLinkConfirm 挂载后也直接打开弹窗,
|
|
|
294
685
|
|
|
295
686
|
### 接入步骤
|
|
296
687
|
|
|
297
|
-
1.
|
|
688
|
+
1. 在应用后台完成站点租户配置,并实现本文的创建请求、查询结果两个业务后台接口(同源或显式配置的跨域后台)。
|
|
298
689
|
2. 安装包、导入样式,创建指向应用后台的客户端。
|
|
299
690
|
3. 用户点击绑定或验证时创建请求,将返回的 ticket 交给 React/Vue 组件。
|
|
300
691
|
4. 用户在 App 确认后,应用后台验证并消费结果,组件收到可信确认事件。
|
|
@@ -317,46 +708,228 @@ React / Vue 的 AuthLinkBind、AuthLinkConfirm 挂载后也直接打开弹窗,
|
|
|
317
708
|
npm install @auth-link/web
|
|
318
709
|
```
|
|
319
710
|
|
|
320
|
-
###
|
|
711
|
+
### 创建应用客户端(默认同源 Cookie 模式)
|
|
712
|
+
|
|
713
|
+
`readCsrfTokenFromYourCms` 是接入方函数,不是包里的导出;名称不要求与你的网站框架一致,也不要求使用 CMS。它只读取**你的网站后台提供的 CSRF token**,用于保护携带登录 cookie 的请求,不是 AuthLink 租户 API key、登录 cookie 或手机核对码。
|
|
714
|
+
|
|
715
|
+
下面采用页面 meta 标签的方式。后台需要先准备 token:
|
|
716
|
+
|
|
717
|
+
1. 优先复用网站框架现有的 CSRF 机制;没有现成机制时,在服务端为当前登录 session 生成并保存密码学安全随机 token,例如 Node 的 `randomBytes(32).toString('base64url')`。不要在浏览器随机生成一个值,也不要使用所有用户共用的固定字符串。
|
|
718
|
+
2. 服务端使用当前 session 的 token 渲染下面的标签,正确转义 HTML 属性;`{{ csrfToken }}` 表示服务器模板变量,不是可直接照抄的 token。包含会话 token 的页面不能被公开缓存。
|
|
719
|
+
3. 创建和查询接口都读取 `X-CSRF-Token`,与同一登录 session 保存的 token 校验;缺失、不匹配或请求来源不符合网站要求时拒绝请求。仅让前端发送这个头,并不会自动启用后台校验。
|
|
720
|
+
4. 登录、退出或会话/token 更新后,让页面重新取得当前 token。SPA 也可以由网站实现同源会话初始化接口返回 token,再通过 `csrfToken` 回调提供;这不是 SDK 自带接口。
|
|
721
|
+
|
|
722
|
+
```html
|
|
723
|
+
<!-- 由你的网站后台渲染到当前用户的页面 head 中 -->
|
|
724
|
+
<meta name="csrf-token" content="{{ csrfToken }}">
|
|
725
|
+
```
|
|
726
|
+
|
|
727
|
+
新建 `authlink-client.ts`:
|
|
321
728
|
|
|
322
729
|
```ts
|
|
323
|
-
|
|
730
|
+
// authlink-client.ts
|
|
731
|
+
import { createAuthLinkClient } from '@auth-link/web';
|
|
324
732
|
import '@auth-link/web/styles.css';
|
|
325
733
|
|
|
326
|
-
//
|
|
734
|
+
// The application server renders this meta element using the current session's
|
|
735
|
+
// CSRF token. This function only reads that token; it does not generate one.
|
|
736
|
+
export function readCsrfTokenFromYourCms(): string {
|
|
737
|
+
const token = document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.content;
|
|
738
|
+
if (!token) throw new Error('Missing CSRF token; load the authenticated application page first.');
|
|
739
|
+
return token;
|
|
740
|
+
}
|
|
741
|
+
|
|
327
742
|
export const client = createAuthLinkClient({
|
|
328
743
|
baseUrl: '/api/authlink',
|
|
329
|
-
csrfToken:
|
|
330
|
-
|
|
744
|
+
csrfToken: readCsrfTokenFromYourCms,
|
|
745
|
+
// Replace this example with the configured AuthLink service origin.
|
|
746
|
+
authLinkOrigin: 'https://auth.example.com',
|
|
747
|
+
});
|
|
748
|
+
```
|
|
749
|
+
|
|
750
|
+
把 `https://auth.example.com` 换成实际 AuthLink 服务来源。SDK 会在每次请求时调用读取函数,自动把值放入 `X-CSRF-Token`,并携带同源登录 cookie;前端不需要读取 HttpOnly 登录 cookie。若网站框架默认使用其他 CSRF 头名,可用 `csrfHeaderName` 配成后台期望的头名,或者实现自定义 `AuthLinkClient`。
|
|
751
|
+
|
|
752
|
+
`create` 只传用途,网站账号由后台登录 session 决定。客户端通常只初始化一次;用户点击按钮时才创建请求。完整调用见下方 React 示例,不要把 `client.create()` 放在模块加载、React effect 或 Vue watch 中。
|
|
753
|
+
|
|
754
|
+
### 前后端分离与跨域后台(0.0.2 起)
|
|
755
|
+
|
|
756
|
+
默认仍使用同源 `/api/authlink`。直接访问另一个后台来源时,同时配置完整 `baseUrl` 和 `allowedBackendOrigins`,例如网页在 `https://www.example.com`,业务后台在 `https://api.example.com`。来源是协议、主机和端口的组合;同一主域名下不同子域名也属于跨域。
|
|
757
|
+
|
|
758
|
+
`allowedBackendOrigins` 是前端明确授权的**业务后台来源**,不能带路径、通配符、用户名或密码,不能来自用户输入。生产环境使用 HTTPS;HTTP 仅允许 localhost / 127.0.0.1 / [::1] 开发环境,端口必须匹配。SDK 会先校验目标再读取凭据,并拒绝 HTTP 重定向。`authLinkOrigin` 则用于校验二维码中的 AuthLink 服务来源,两者作用不同,可按需要同时配置。
|
|
759
|
+
|
|
760
|
+
#### 跨域 Cookie / session
|
|
761
|
+
|
|
762
|
+
下面给出完整的初始化函数。`GET /api/session` 是接入网站自己实现的示例会话接口,不是包或 AuthLink 服务自带的接口;它应根据现有登录 cookie 返回 `{ "csrfToken": "当前会话的真实CSRF token" }`,设置 `Cache-Control: no-store` 并配置下文的 CORS。部署时将路径换成网站实际的会话初始化接口。
|
|
763
|
+
|
|
764
|
+
这里的 `csrfToken` 是通用示例选定的 JSON 字段名。Go CMS 实例实际返回 `{ authenticated: true, csrf: '…' }`;读取 `session.csrf` 并交给同名 SDK 配置回调即可,无须改动后台响应。完整映射见上方 Go + Vue 指南。
|
|
765
|
+
|
|
766
|
+
```ts
|
|
767
|
+
import { createAuthLinkClient } from '@auth-link/web';
|
|
768
|
+
|
|
769
|
+
/** /api/session is an example endpoint implemented by your application backend. */
|
|
770
|
+
export async function createSessionBackendClient(backendOrigin: string) {
|
|
771
|
+
const response = await fetch(`${backendOrigin}/api/session`, {
|
|
772
|
+
credentials: 'include', cache: 'no-store', redirect: 'error',
|
|
773
|
+
});
|
|
774
|
+
if (!response.ok) throw new Error('Session initialization failed');
|
|
775
|
+
const session: unknown = await response.json();
|
|
776
|
+
if (!session || typeof session !== 'object' || !('csrfToken' in session) ||
|
|
777
|
+
typeof session.csrfToken !== 'string' || !session.csrfToken) {
|
|
778
|
+
throw new Error('The session endpoint must return { csrfToken: string }');
|
|
779
|
+
}
|
|
780
|
+
let currentCsrfToken = session.csrfToken;
|
|
781
|
+
return {
|
|
782
|
+
client: createAuthLinkClient({
|
|
783
|
+
baseUrl: `${backendOrigin}/api/authlink`,
|
|
784
|
+
allowedBackendOrigins: [backendOrigin],
|
|
785
|
+
credentials: 'include',
|
|
786
|
+
csrfToken: () => currentCsrfToken,
|
|
787
|
+
}),
|
|
788
|
+
// Call after your application's session/token refresh; recreate on account changes.
|
|
789
|
+
updateCsrfToken(value: string) { currentCsrfToken = value; },
|
|
790
|
+
};
|
|
791
|
+
}
|
|
792
|
+
```
|
|
793
|
+
|
|
794
|
+
登录后调用 `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 策略的开关。
|
|
795
|
+
|
|
796
|
+
#### 跨域 Bearer token / JWT
|
|
797
|
+
|
|
798
|
+
传入网站自己的登录状态对象;网站完成登录或刷新后更新这个对象的 `accessToken`。回调会在每次创建和轮询时重新读取最新 token,无需重建弹窗。
|
|
799
|
+
|
|
800
|
+
```ts
|
|
801
|
+
import { createAuthLinkClient } from '@auth-link/web';
|
|
802
|
+
|
|
803
|
+
/** auth is your website's existing login state, updated by its login/refresh flow. */
|
|
804
|
+
export function createBearerBackendClient(backendOrigin: string, auth: { accessToken: string }) {
|
|
805
|
+
return createAuthLinkClient({
|
|
806
|
+
baseUrl: `${backendOrigin}/api/authlink`,
|
|
807
|
+
allowedBackendOrigins: [backendOrigin],
|
|
808
|
+
credentials: 'omit',
|
|
809
|
+
accessToken: () => auth.accessToken,
|
|
810
|
+
});
|
|
811
|
+
}
|
|
812
|
+
```
|
|
813
|
+
|
|
814
|
+
`accessToken` 必须是接入网站的用户登录 token,不能是 AuthLink 租户 API key。SDK 自动添加 `Authorization: Bearer ...`。纯 Bearer 模式默认 `credentials: 'omit'`,可不传 `csrfToken`;后台应仅按 Bearer token 认证,不回退到 Cookie 登录。若显式设置 `credentials: 'include'` 或 `'same-origin'` 混用 Cookie,仍须提供并校验 `csrfToken`。
|
|
815
|
+
|
|
816
|
+
#### 后台 CORS 配置
|
|
817
|
+
|
|
818
|
+
后台需处理浏览器发出的 `OPTIONS` 预检,并在预检、实际响应和错误响应中返回相应 CORS 头。会话初始化接口也需要这些设置。以下假设前端来源是 `https://www.example.com`:
|
|
819
|
+
|
|
820
|
+
```http
|
|
821
|
+
Access-Control-Allow-Origin: https://www.example.com
|
|
822
|
+
Access-Control-Allow-Credentials: true
|
|
823
|
+
Access-Control-Allow-Methods: GET, POST, OPTIONS
|
|
824
|
+
Access-Control-Allow-Headers: Content-Type, X-CSRF-Token, Idempotency-Key, Authorization
|
|
825
|
+
Vary: Origin
|
|
826
|
+
```
|
|
827
|
+
|
|
828
|
+
携带 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)。
|
|
829
|
+
|
|
830
|
+
#### 请求客户端配置
|
|
831
|
+
|
|
832
|
+
| 配置 | 说明 |
|
|
833
|
+
| --- | --- |
|
|
834
|
+
| `baseUrl` | 业务后台前缀,默认 `/api/authlink`;跨域时填写完整地址 |
|
|
835
|
+
| `allowedBackendOrigins` | 额外允许的精确后台来源数组,默认只允许当前网页同源 |
|
|
836
|
+
| `credentials` | Cookie 模式默认 `same-origin`;提供 `accessToken` 时默认 `omit`;跨域 Cookie 显式设置 `include` |
|
|
837
|
+
| `csrfToken` | 每次请求读取 CSRF token 的同步或异步函数;Cookie 模式必填 |
|
|
838
|
+
| `csrfHeaderName` | CSRF 请求头名,默认 `X-CSRF-Token`,例如可设为 `X-XSRF-TOKEN` |
|
|
839
|
+
| `accessToken` | 每次请求读取网站 Bearer token 的同步或异步函数;不要包含 `Bearer ` 前缀 |
|
|
840
|
+
| `headers` | 额外的 `HeadersInit` 或返回它的同步/异步函数,可传工作区等自定义头 |
|
|
841
|
+
| `authLinkOrigin` | 核对二维码中的 AuthLink 服务来源,与业务后台来源独立 |
|
|
842
|
+
| `fetch` | 可选 fetch 实现;仍受目标来源和协议校验约束 |
|
|
843
|
+
|
|
844
|
+
SDK 管理 `Accept`、`Content-Type`、`Authorization`、`Idempotency-Key` 和配置的 CSRF 头,`headers` 不能覆盖这些字段,否则报 `RESERVED_HEADER`。用 `accessToken` 设置 Bearer token,用 `csrfHeaderName` 适配后台框架。`ClientOptions` 可从根入口导入为 TypeScript 类型。
|
|
845
|
+
|
|
846
|
+
未授权来源报 `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`,具体原因需查看浏览器开发者工具。
|
|
847
|
+
|
|
848
|
+
### 直接调用弹窗(React、Vue 或原生 JavaScript)
|
|
849
|
+
|
|
850
|
+
```ts
|
|
851
|
+
import { openAuthLinkBind, openAuthLinkConfirm, requestKey } from '@auth-link/web';
|
|
852
|
+
import { client } from './authlink-client';
|
|
853
|
+
import '@auth-link/web/styles.css';
|
|
854
|
+
|
|
855
|
+
// 在按钮事件中创建请求,再打开弹窗;client 为上文 authlink-client.ts 导出的同源客户端。
|
|
856
|
+
const ticket = await client.create('confirm', { idempotencyKey: requestKey() });
|
|
857
|
+
const modal = openAuthLinkConfirm({
|
|
858
|
+
ticket, client, locale: 'zh-CN',
|
|
859
|
+
onConfirmed: result => console.log(result.requestId),
|
|
860
|
+
onRejected: result => console.log(result.code), // REJECTED,此时弹窗已关闭
|
|
861
|
+
onClose: () => console.log('已关闭'),
|
|
331
862
|
});
|
|
332
|
-
//
|
|
333
|
-
|
|
334
|
-
const ticket = await client.create('bind', { idempotencyKey: key });
|
|
335
|
-
// 创建响应丢失时复用 key 重试,不能每次重试都生成新 key。
|
|
863
|
+
// 绑定使用 openAuthLinkBind({ ticket: bindingTicket, client })。
|
|
864
|
+
// modal.close(); modal.setLocale('ja');
|
|
336
865
|
```
|
|
337
866
|
|
|
338
|
-
|
|
867
|
+
React / Vue 的 AuthLinkBind、AuthLinkConfirm 挂载后也直接打开弹窗,不再内嵌在页面。React 用 onClose、Vue 用 @close 清空 ticket 并卸载组件。服务端渲染不创建弹窗或请求。支持手机窄屏、内容滚动、关闭按钮及 Escape;要求浏览器支持原生 dialog.showModal()。弹窗挂到 document.body,主题变量请配置在 :root 或 .authlink-dialog。
|
|
868
|
+
|
|
869
|
+
关闭只停止前端查询,不拒绝或撤销服务端请求;请求仍按原有效期结束。确认成功或拒绝后弹窗自动关闭,分别回调 onConfirmed 或 onRejected,不触发用户关闭回调。直接调用时,页面卸载须执行 modal.destroy() 清理,它不触发用户关闭回调。切换语言用 modal.setLocale(),不会重建鉴权请求。
|
|
870
|
+
|
|
339
871
|
|
|
340
872
|
### React
|
|
341
873
|
|
|
874
|
+
下面的 `showBound` 也是接入方函数,负责更新页面提示和清空 `ticket`,从而卸载弹窗;它不向后台提交“绑定成功”,也不保存绑定。绑定及确认记录必须在后台查询结果接口验证、消费并保存后,才返回 `confirmed`。
|
|
875
|
+
|
|
876
|
+
这个示例包含按钮、请求创建、结果提示和弹窗清理,不再依赖未定义的 `showBound`、`showRejected` 等函数。使用 `<AuthLinkPanel mode="bind" />` 绑定,使用 `<AuthLinkPanel mode="confirm" />` 请求手机确认。
|
|
877
|
+
|
|
342
878
|
```tsx
|
|
879
|
+
"use client";
|
|
880
|
+
import { useRef, useState } from 'react';
|
|
881
|
+
import { requestKey } from '@auth-link/web';
|
|
882
|
+
import type { Mode, Ticket } from '@auth-link/web';
|
|
343
883
|
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/react';
|
|
344
|
-
import
|
|
345
|
-
import { client } from './authlink-client'; // 上文创建的客户端
|
|
346
|
-
|
|
347
|
-
export function BindPanel({ ticket }: { ticket: Ticket }) {
|
|
348
|
-
return <AuthLinkBind ticket={ticket} client={client} locale="zh-CN"
|
|
349
|
-
onConfirmed={result => showBound(result.requestId)}
|
|
350
|
-
onRejected={() => showRejected()} onExpired={() => showExpired()}
|
|
351
|
-
onError={error => showNetworkError(error.message)} />;
|
|
352
|
-
}
|
|
884
|
+
import { client } from './authlink-client';
|
|
353
885
|
|
|
354
|
-
export function
|
|
355
|
-
|
|
356
|
-
|
|
886
|
+
export function AuthLinkPanel({ mode }: { mode: Mode }) {
|
|
887
|
+
const [ticket, setTicket] = useState<Ticket | null>(null);
|
|
888
|
+
const [busy, setBusy] = useState(false);
|
|
889
|
+
const [message, setMessage] = useState('');
|
|
890
|
+
const key = useRef<string | null>(null);
|
|
891
|
+
const creating = useRef(false);
|
|
892
|
+
function finish(message: string) {
|
|
893
|
+
setTicket(null);
|
|
894
|
+
setMessage(message);
|
|
895
|
+
}
|
|
896
|
+
function showBound(requestId: string) {
|
|
897
|
+
// UI feedback only. The backend has already verified and saved the binding.
|
|
898
|
+
finish(`手机绑定成功(请求 ${requestId})`);
|
|
899
|
+
}
|
|
900
|
+
function showConfirmed(requestId: string) {
|
|
901
|
+
finish(`手机确认成功(请求 ${requestId})`);
|
|
902
|
+
}
|
|
903
|
+
const start = async () => {
|
|
904
|
+
if (creating.current || ticket) return;
|
|
905
|
+
creating.current = true;
|
|
906
|
+
setBusy(true);
|
|
907
|
+
setMessage('');
|
|
908
|
+
try {
|
|
909
|
+
key.current ??= requestKey();
|
|
910
|
+
setTicket(await client.create(mode, { idempotencyKey: key.current }));
|
|
911
|
+
key.current = null;
|
|
912
|
+
} catch { setMessage('请求未完成,可重试同一次创建。'); }
|
|
913
|
+
finally { creating.current = false; setBusy(false); }
|
|
914
|
+
};
|
|
915
|
+
const Component = mode === 'bind' ? AuthLinkBind : AuthLinkConfirm;
|
|
916
|
+
return <>
|
|
917
|
+
{!ticket && <button type="button" disabled={busy} onClick={() => void start()}>开始验证</button>}
|
|
918
|
+
{ticket && <Component ticket={ticket} client={client}
|
|
919
|
+
onConfirmed={result => result.purpose === 'bind' ? showBound(result.requestId) : showConfirmed(result.requestId)}
|
|
920
|
+
onClose={() => finish('已关闭')}
|
|
921
|
+
onRejected={() => finish('手机已拒绝本次请求')}
|
|
922
|
+
onExpired={() => finish('请求已过期,请重新发起')}
|
|
923
|
+
onError={error => setMessage(error.message)} />}
|
|
924
|
+
<p role="status">{message}</p>
|
|
925
|
+
</>;
|
|
357
926
|
}
|
|
358
927
|
```
|
|
359
928
|
|
|
929
|
+
`requestId` 用于展示或追踪本次请求,不是授权凭据。`showBound` 也可以按网站需求显示 toast、重新查询已有的账号状态接口或导航到绑定管理页。刷新页面后,应重新从后台读取真实绑定状态,不能只依赖 React state 或 localStorage。其他业务接口仍需在后台检查权限。
|
|
930
|
+
|
|
931
|
+
创建失败时示例保留同一个幂等键;再次点击会重试同一次创建。创建成功后清空幂等键,新的用户操作才创建新请求。关闭、成功、拒绝和过期都会清空 ticket;网络错误保留弹窗,供其重试当前请求。
|
|
932
|
+
|
|
360
933
|
确认组件默认只显示动态数字;`showQr` 可额外显示扫码入口。绑定组件始终显示二维码。`onRefresh` 可提供重新创建请求的函数;仅过期后显示该按钮。组件自身的“重试”只恢复当前请求,不创建第二个请求。
|
|
361
934
|
|
|
362
935
|
未指定 `locale` 时使用简体中文;不支持的语言代码也回退到简体中文。组件根元素设置对应的 `lang`,语言切换不会重新创建鉴权请求。
|
|
@@ -367,25 +940,47 @@ React 入口保留 `"use client"`,可用于 Next.js 客户端组件。导入
|
|
|
367
940
|
|
|
368
941
|
```vue
|
|
369
942
|
<script setup lang="ts">
|
|
943
|
+
import { ref, shallowRef } from 'vue';
|
|
944
|
+
import { requestKey } from '@auth-link/web';
|
|
945
|
+
import type { Confirmation, Mode, Ticket } from '@auth-link/web';
|
|
370
946
|
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/vue';
|
|
371
|
-
import
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
947
|
+
import { client } from './authlink-client';
|
|
948
|
+
const props = defineProps<{ mode: Mode }>();
|
|
949
|
+
const ticket = shallowRef<Ticket | null>(null);
|
|
950
|
+
const busy = ref(false);
|
|
951
|
+
const message = ref('');
|
|
952
|
+
let key: string | null = null;
|
|
953
|
+
function finish(text: string) { ticket.value = null; message.value = text; }
|
|
954
|
+
function confirmed(result: Confirmation) {
|
|
955
|
+
finish(`${result.purpose === 'bind' ? '已绑定' : '已确认'}(请求 ${result.requestId})`);
|
|
956
|
+
}
|
|
957
|
+
async function start() {
|
|
958
|
+
if (busy.value) return;
|
|
959
|
+
busy.value = true;
|
|
960
|
+
key ??= requestKey();
|
|
961
|
+
try {
|
|
962
|
+
ticket.value = await client.create(props.mode, { idempotencyKey: key });
|
|
963
|
+
key = null;
|
|
964
|
+
} catch { message.value = '请求未完成,可重试同一次创建。'; }
|
|
965
|
+
finally { busy.value = false; }
|
|
966
|
+
}
|
|
376
967
|
</script>
|
|
377
968
|
|
|
378
969
|
<template>
|
|
379
|
-
<
|
|
380
|
-
|
|
970
|
+
<button v-if="!ticket" type="button" :disabled="busy" @click="start">开始验证</button>
|
|
971
|
+
<AuthLinkBind v-else-if="mode === 'bind'" :ticket="ticket" :client="client"
|
|
972
|
+
@confirmed="confirmed" @close="finish('已关闭')" @rejected="finish('手机已拒绝本次请求')"
|
|
973
|
+
@expired="finish('请求已过期,请重新发起')" @error="message = '网络异常,请重试。'" />
|
|
381
974
|
<AuthLinkConfirm v-else :ticket="ticket" :client="client"
|
|
382
|
-
|
|
975
|
+
@confirmed="confirmed" @close="finish('已关闭')" @rejected="finish('手机已拒绝本次请求')"
|
|
976
|
+
@expired="finish('请求已过期,请重新发起')" @error="message = '网络异常,请重试。'" />
|
|
977
|
+
<p role="status">{{ message }}</p>
|
|
383
978
|
</template>
|
|
384
979
|
```
|
|
385
980
|
|
|
386
981
|
拒绝时返回 `{ status: 'rejected', code: 'REJECTED', requestId, purpose }`。`REJECTED` 是 SDK 业务状态码,不是 HTTP 状态码或授权凭证。组件自动关闭,不再显示“已拒绝 / 重新发起”面板,也不触发 `onClose`;提示和重新发起由接入网站在回调中决定。React / Vue 请在 `onRejected` / `@rejected` 中清空 ticket、卸载组件。无 UI 的 hook 仍保留 `snapshot.status === 'rejected'`,供自定义界面使用。
|
|
387
982
|
|
|
388
|
-
|
|
983
|
+
此示例在过期后清空 ticket,用户可再次点击按钮发起请求。如果需要在过期弹窗内提供重新发起按钮,可自行传入 `onRefresh`,在回调中创建新请求并更新 ticket。`useAuthLink(() => options)` composable 与 React 的 `useAuthLink(options)` hook 可用于自定义界面,返回 `snapshot` 和 `retry`;Vue 的 snapshot 是浅 ref。
|
|
389
984
|
|
|
390
985
|
### 选择弹窗样式
|
|
391
986
|
|
|
@@ -447,19 +1042,19 @@ openAuthLinkConfirm({ ticket, client, variant: 'B' });
|
|
|
447
1042
|
| `@auth-link/web/vue` | Vue 组件和 `useAuthLink` |
|
|
448
1043
|
| `@auth-link/web/styles.css` | 组件样式,需显式导入 |
|
|
449
1044
|
|
|
450
|
-
|
|
1045
|
+
### 应用后台接口约定
|
|
451
1046
|
|
|
452
1047
|
默认前缀 `/api/authlink`;下面两个接口由接入方实现,**不是直接把浏览器请求转发到租户密钥 API**。
|
|
453
1048
|
|
|
454
1049
|
#### `POST /requests`
|
|
455
1050
|
|
|
456
|
-
|
|
1051
|
+
浏览器按所选模式携带网站登录凭据:Cookie 模式发送 session cookie 和配置的 CSRF 头,Bearer 模式发送 `Authorization`。创建还发送稳定的 `Idempotency-Key`,body:
|
|
457
1052
|
|
|
458
1053
|
```json
|
|
459
1054
|
{"purpose":"bind"}
|
|
460
1055
|
```
|
|
461
1056
|
|
|
462
|
-
|
|
1057
|
+
后台从经过验证的 session 或 Bearer token 取得用户 ID,创建并持久保存 state、创建/消费幂等键、用户/session 关联,然后调用 AuthLink 服务端创建请求。返回其公开 ticket:
|
|
463
1058
|
|
|
464
1059
|
```ts
|
|
465
1060
|
type Ticket = {
|
|
@@ -478,7 +1073,7 @@ type Ticket = {
|
|
|
478
1073
|
|
|
479
1074
|
#### `POST /requests/{requestId}/result`
|
|
480
1075
|
|
|
481
|
-
|
|
1076
|
+
同样验证登录身份(Cookie 模式还需 CSRF)和请求归属。后台调用 AuthLink 状态接口,将 `displayCode` 原样返回,不能缓存跨过 `validUntil`。新代码由后台实时获取,不是前端自行生成。
|
|
482
1077
|
|
|
483
1078
|
尚未完成时返回 `{requestId,status,displayCode?}`;状态可为 new / pending / approved / consumed / rejected / expired。`approved` 不能触发成功事件。
|
|
484
1079
|
|
|
@@ -509,7 +1104,9 @@ type Ticket = {
|
|
|
509
1104
|
|
|
510
1105
|
### 样式与语言
|
|
511
1106
|
|
|
512
|
-
CSS 单独导入,所有类使用 `authlink-`
|
|
1107
|
+
CSS 单独导入,所有类使用 `authlink-` 前缀。弹窗挂载到 `document.body`,可在 `:root` 或 `.authlink-dialog` 覆盖 `--authlink-foreground`、`--authlink-background`、`--authlink-accent`、`--authlink-muted`。面板语言见下表,默认简体中文。
|
|
1108
|
+
|
|
1109
|
+
React / Vue 均支持 `className`;Vue 还支持字符串、数组和对象形式的 `class`,与 `className` 合并。“重新发起”按钮使用父组件最新传入的 `onRefresh` 回调。
|
|
513
1110
|
|
|
514
1111
|
|
|
515
1112
|
| Code | Language |
|
|
@@ -534,32 +1131,278 @@ CSS 单独导入,所有类使用 `authlink-` 前缀。可在宿主容器覆盖
|
|
|
534
1131
|
|
|
535
1132
|
React 18.2+ / 19、Vue 3.3+、TypeScript、ESM。React 和 Vue 是可选 peer,只安装所用框架。构建工具环境需 Node 22.13+。
|
|
536
1133
|
|
|
537
|
-
|
|
1134
|
+
### 许可证
|
|
538
1135
|
|
|
539
|
-
|
|
1136
|
+
MIT。完整许可文本见 `LICENSE`,打包包含的第三方库归属说明见 `THIRD_PARTY_NOTICES.md`。
|
|
540
1137
|
|
|
541
|
-
|
|
1138
|
+
### Go Vue CMS: zh-CN
|
|
542
1139
|
|
|
543
|
-
|
|
1140
|
+
本指南按实际 Go CMS + Vue 3 的接入顺序整理。下面使用可替换的示例域名,不依赖某台电脑的配置、测试账号、密码或租户密钥。网站负责登录、数据库和业务接口;Web SDK 负责展示和观察请求,Go SDK 负责后台调用与回执校验。
|
|
544
1141
|
|
|
545
|
-
|
|
546
|
-
|
|
1142
|
+
#### 1. 区分三个来源并安装 SDK
|
|
1143
|
+
|
|
1144
|
+
| 角色 | 示例来源 | 配置位置 |
|
|
1145
|
+
| --- | --- | --- |
|
|
1146
|
+
| Vue | `https://cms.example.com` | `apiOrigin` 指向下方的 Go 后台 |
|
|
1147
|
+
| Go CMS API | `https://cms-api.example.com` | `baseUrl=https://cms-api.example.com/api/authlink` |
|
|
1148
|
+
| AuthLink API | `https://auth.example.com` | Go SDK 的 `Origin`;浏览器的 `authLinkOrigin` |
|
|
1149
|
+
|
|
1150
|
+
登记租户的站点 origin 是 Vue 网站来源;Go SDK 的 `Origin` 和凭据导出 JSON 中的 API origin 是 AuthLink API 来源。浏览器的 `baseUrl` 指向 Go 业务后台,不能指向 AuthLink 租户 API。公开运行配置只包含这三个 origin;`TenantID`、`APIKey` 保留在 Go 私密配置或环境变量中。
|
|
1151
|
+
|
|
1152
|
+
```sh
|
|
1153
|
+
npm install @auth-link/web@latest vue
|
|
1154
|
+
# In your Go backend module, after unpacking the supplied Go SDK:
|
|
1155
|
+
go mod edit -replace=authlink.local/sdk=./third_party/authlink-go
|
|
1156
|
+
go mod edit -require=authlink.local/sdk@v0.0.0
|
|
1157
|
+
go mod tidy
|
|
1158
|
+
```
|
|
1159
|
+
|
|
1160
|
+
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})`。
|
|
1161
|
+
|
|
1162
|
+
#### 2. 先完成网站登录,再读取会话
|
|
1163
|
+
|
|
1164
|
+
本站现有登录接口(参考 CMS 为 `POST /api/login`)验证用户后签发 HttpOnly、Secure 的 session Cookie。Vue 用 `credentials:'include'` 调用 Go 的 `GET /api/session`。已登录时返回 `authenticated:true` 与 `csrf`;未登录时先回到网站登录流程。
|
|
1165
|
+
|
|
1166
|
+
`csrf` 是本 CMS 的响应字段名;SDK 配置项仍叫 `csrfToken`,写成 `csrfToken: () => session.value?.csrf ?? ''` 即可。SDK 不要求你的后台一定返回名为 `csrfToken` 的字段。令牌由 Go 为当前 session 生成并保存,浏览器只读取,不能用租户密钥或手机核对码代替。创建和结果查询均需验证 `X-CSRF-Token` 与同一 session 的值一致。
|
|
1167
|
+
|
|
1168
|
+
Vue 与 API 使用同一 HTTPS 主域名下的两个子域名时,是跨 origin、同 site。参考 CMS 的 host-only Cookie 不设置 `Domain`,使用 `SameSite=Strict; Secure; HttpOnly; Path=/`;请求目标仍为 API 域名。真正跨 site 时还需按浏览器 Cookie 策略配置,不能只依靠 CORS。
|
|
1169
|
+
|
|
1170
|
+
#### 3. Go 配置 CORS 与业务路由
|
|
1171
|
+
|
|
1172
|
+
```http
|
|
1173
|
+
Access-Control-Allow-Origin: https://cms.example.com
|
|
1174
|
+
Access-Control-Allow-Credentials: true
|
|
1175
|
+
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS
|
|
1176
|
+
Access-Control-Allow-Headers: Content-Type, X-CSRF-Token, Idempotency-Key
|
|
1177
|
+
Vary: Origin
|
|
1178
|
+
Cache-Control: no-store
|
|
1179
|
+
```
|
|
1180
|
+
|
|
1181
|
+
只为精确允许的 Vue origin 返回这些 CORS 头;允许来源的正常和错误响应都要携带。`OPTIONS` 先验证来源、方法和请求头,成功返回 204,不要求登录或 CSRF;随后实际请求才验证登录、来源、CSRF 和归属。不能用 `*` 或无条件反射来源。上面包含 CMS 草稿编辑所用的 PUT;只接入 SDK 的站点可按实际路由收窄。
|
|
1182
|
+
|
|
1183
|
+
| 网站自己的路由 | 请求 | 返回 |
|
|
1184
|
+
| --- | --- | --- |
|
|
1185
|
+
| `GET /api/session` | — | `{authenticated:true, csrf:"…", subject:"…", username:"…"}`;未登录: `{authenticated:false}` |
|
|
1186
|
+
| `POST /api/authlink/requests` | `{purpose:"bind"}` 或 `{purpose:"confirm",postId,version}`; `Idempotency-Key` | 公开 `Ticket` |
|
|
1187
|
+
| `POST /api/authlink/requests/{id}/result` | `{}`;当前 session + CSRF | 待处理状态/displayCode 或已验证的 `confirmed` 回执 |
|
|
1188
|
+
| `POST /api/posts/{id}/publish` | `{requestId,version}`; 当前 session + CSRF | `{ok:true}` 校验已保存的确认记录和业务意图后返回 |
|
|
1189
|
+
|
|
1190
|
+
上述路由由 Go CMS 实现,不是安装 Web SDK 后自动出现的接口。`postId` / `version` / `/publish` 是本例业务约定,不是 AuthLink 平台字段。
|
|
1191
|
+
|
|
1192
|
+
#### 4. 创建前落库,消费后再返回 confirmed
|
|
1193
|
+
|
|
1194
|
+
```text
|
|
1195
|
+
Vue → Go /api/session → current session + csrf
|
|
1196
|
+
Vue → Go /api/authlink/requests → Go SDK CreateRequest → public ticket
|
|
1197
|
+
Vue dialog → Go /api/authlink/requests/{id}/result → Status + Consume
|
|
1198
|
+
Go commits verified receipt → Vue confirmed event
|
|
1199
|
+
Vue → Go /api/posts/{id}/publish → validate saved intent/receipt → publish
|
|
1200
|
+
```
|
|
1201
|
+
|
|
1202
|
+
Go 从可信 session 取稳定用户 ID,不能接受浏览器自报的 `externalUserId`。创建顺序:
|
|
1203
|
+
|
|
1204
|
+
1. 校验 purpose、创建幂等键,以及文章归属和当前版本(若有)。
|
|
1205
|
+
2. 生成独立随机 state 和消费幂等键;把原创建键、CreateInput、当前用户/session 和业务意图落库,再向 AuthLink 发请求。网络结果不明时从数据库恢复同一记录、输入和键。
|
|
1206
|
+
3. 调用 `CreateRequest`,保存返回的 requestId、原始 expiresAt 与 ticket,去掉可选 qrSvg 后返回公开 ticket。对同一 session + 创建键加唯一约束,键复用到其他 purpose / 文章 / 版本时返回冲突。
|
|
1207
|
+
4. 结果接口按 requestId + 当前 session 加锁读取记录;已保存回执直接复用。用 `Status` 查询,只有 approved / consumed 才以保存的 `Expected` 和消费键调用 `Consume`。SDK 校验失败不能返回成功。
|
|
1208
|
+
5. 在事务里保存回执、用户/session 确认记录和审计,requestId / verificationId 建唯一约束,提交成功后才返回 `confirmed`。待处理状态保留原 displayCode,不跨数字期限缓存。
|
|
1209
|
+
|
|
1210
|
+
下面是 SDK 调用层代码,**不是包含登录、数据库和路由的完整 HTTP 服务**;注释中的落库与事务必须由你的 Go 后台实现。初始化客户端、构造 Input、所有权检查及请求记录的读写按上述步骤完成。
|
|
1211
|
+
|
|
1212
|
+
```go
|
|
1213
|
+
package cmsauth
|
|
1214
|
+
|
|
1215
|
+
import (
|
|
1216
|
+
"context"
|
|
1217
|
+
authlink "authlink.local/sdk"
|
|
1218
|
+
)
|
|
1219
|
+
|
|
1220
|
+
// Load this record from your database for the authenticated user/session.
|
|
1221
|
+
// Save Input (including State), CreateKey and ConsumeKey BEFORE calling Create.
|
|
1222
|
+
// Intent (post ID/version), ownership and unique constraints belong in your DB.
|
|
1223
|
+
type StoredRequest struct {
|
|
1224
|
+
Input authlink.CreateInput
|
|
1225
|
+
CreateKey string
|
|
1226
|
+
ConsumeKey string
|
|
1227
|
+
Ticket authlink.Ticket
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
// On network retries, load the SAME record; do not regenerate State or keys.
|
|
1231
|
+
func Create(ctx context.Context, sdk *authlink.Client, saved StoredRequest) (authlink.Ticket, error) {
|
|
1232
|
+
return sdk.CreateRequest(ctx, saved.Input, saved.CreateKey)
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
type PublicConfirmation struct {
|
|
1236
|
+
Status string `json:"status"`
|
|
1237
|
+
RequestID string `json:"requestId"`
|
|
1238
|
+
VerificationID string `json:"verificationId"`
|
|
1239
|
+
Purpose string `json:"purpose"`
|
|
1240
|
+
ExpiresAt string `json:"expiresAt"`
|
|
1241
|
+
AuthenticationPolicy string `json:"authenticationPolicy"`
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
// Caller checks session/CSRF/ownership, locks the saved record and first returns
|
|
1245
|
+
// any already-saved receipt. For a new confirmed result, caller must persist
|
|
1246
|
+
// the receipt and confirmation in a DB transaction BEFORE returning HTTP 200.
|
|
1247
|
+
func Poll(ctx context.Context, sdk *authlink.Client, saved StoredRequest) (any, error) {
|
|
1248
|
+
status, err := sdk.Status(ctx, saved.Ticket.RequestID)
|
|
1249
|
+
if err != nil { return nil, err }
|
|
1250
|
+
if status.Status != "approved" && status.Status != "consumed" { return status, nil }
|
|
1251
|
+
result, err := sdk.Consume(ctx, authlink.Expected{
|
|
1252
|
+
RequestID: saved.Ticket.RequestID,
|
|
1253
|
+
ExternalUserID: saved.Input.ExternalUserID,
|
|
1254
|
+
Purpose: saved.Input.Purpose,
|
|
1255
|
+
State: saved.Input.State,
|
|
1256
|
+
ExpiresAt: saved.Ticket.ExpiresAt,
|
|
1257
|
+
}, saved.ConsumeKey)
|
|
1258
|
+
if err != nil { return nil, err }
|
|
1259
|
+
return PublicConfirmation{
|
|
1260
|
+
Status: "confirmed", RequestID: result.RequestID,
|
|
1261
|
+
VerificationID: result.VerificationID, Purpose: result.Purpose,
|
|
1262
|
+
ExpiresAt: saved.Ticket.ExpiresAt, AuthenticationPolicy: result.AuthenticationPolicy,
|
|
1263
|
+
}, nil
|
|
1264
|
+
}
|
|
1265
|
+
```
|
|
1266
|
+
|
|
1267
|
+
#### 5. Vue 组件:稳定 ticket、按业务绑定创建、清理与重试
|
|
1268
|
+
|
|
1269
|
+
完整文件也包含在包内 `examples/vue-cms.vue`。网站登录后挂载它,传入可信 `apiOrigin`、`authLinkOrigin`,可选传入后台加载的草稿 `post={id,version}`。父层用当前登录 session 的标识做组件 key,退出、重新登录或切换账号时先卸载旧组件并清空会话、旧 ticket、幂等键和待发布操作,再挂载新组件。不要只改用户名后继续使用旧 ticket。
|
|
1270
|
+
|
|
1271
|
+
```vue
|
|
1272
|
+
<script setup lang="ts">
|
|
1273
|
+
import { markRaw, onMounted, onUnmounted, ref, shallowRef } from 'vue';
|
|
1274
|
+
import { createAuthLinkClient, requestKey, validateTicket } from '@auth-link/web';
|
|
1275
|
+
import type { Confirmation, Mode, Ticket } from '@auth-link/web';
|
|
1276
|
+
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/vue';
|
|
547
1277
|
import '@auth-link/web/styles.css';
|
|
548
1278
|
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
1279
|
+
type Post = { id: string; version: number };
|
|
1280
|
+
type Publication = Post & { requestId: string };
|
|
1281
|
+
// Supply trusted deployment configuration. Mount after site login and remount
|
|
1282
|
+
// with :key="session.subject" after login, logout or account/session changes.
|
|
1283
|
+
const props = defineProps<{ apiOrigin: string; authLinkOrigin: string; post?: Post }>();
|
|
1284
|
+
const session = ref<{ authenticated: boolean; csrf?: string } | null>(null);
|
|
1285
|
+
const ticket = shallowRef<Ticket | null>(null);
|
|
1286
|
+
const publication = shallowRef<Post | null>(null);
|
|
1287
|
+
const retryPublish = shallowRef<Publication | null>(null);
|
|
1288
|
+
const busy = ref(false), message = ref('');
|
|
1289
|
+
let creation: { signature: string; key: string } | null = null;
|
|
1290
|
+
const lifetime = new AbortController();
|
|
1291
|
+
const client = markRaw(createAuthLinkClient({
|
|
1292
|
+
baseUrl: `${props.apiOrigin}/api/authlink`,
|
|
1293
|
+
allowedBackendOrigins: [props.apiOrigin],
|
|
1294
|
+
credentials: 'include',
|
|
1295
|
+
csrfToken: () => session.value?.csrf ?? '',
|
|
1296
|
+
authLinkOrigin: props.authLinkOrigin,
|
|
1297
|
+
}));
|
|
1298
|
+
|
|
1299
|
+
async function api(path: string, body?: unknown, headers: Record<string, string> = {}) {
|
|
1300
|
+
const response = await fetch(`${props.apiOrigin}${path}`, {
|
|
1301
|
+
method: body === undefined ? 'GET' : 'POST',
|
|
1302
|
+
credentials: 'include', cache: 'no-store', redirect: 'error',
|
|
1303
|
+
signal: lifetime.signal,
|
|
1304
|
+
headers: body === undefined ? {} : {
|
|
1305
|
+
'Content-Type': 'application/json', 'X-CSRF-Token': session.value?.csrf ?? '', ...headers,
|
|
1306
|
+
},
|
|
1307
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
1308
|
+
});
|
|
1309
|
+
const value = await response.json();
|
|
1310
|
+
if (response.status === 401) {
|
|
1311
|
+
session.value = null; closeTicket(); retryPublish.value = null; creation = null;
|
|
1312
|
+
}
|
|
1313
|
+
if (!response.ok) throw new Error(value.code ?? 'REQUEST_FAILED');
|
|
1314
|
+
return value;
|
|
1315
|
+
}
|
|
1316
|
+
function closeTicket() { ticket.value = null; publication.value = null; }
|
|
1317
|
+
function showError(error: Error) { message.value = error.message; }
|
|
1318
|
+
function finish(text: string) { closeTicket(); message.value = text; }
|
|
1319
|
+
|
|
1320
|
+
async function start(purpose: Mode, post?: Post) {
|
|
1321
|
+
if (busy.value || ticket.value || !session.value?.authenticated) return;
|
|
1322
|
+
busy.value = true; message.value = ''; retryPublish.value = null;
|
|
1323
|
+
const intent = post ? { id: post.id, version: post.version } : null;
|
|
1324
|
+
const signature = JSON.stringify({ purpose, postId: intent?.id, version: intent?.version });
|
|
1325
|
+
try {
|
|
1326
|
+
if (creation?.signature !== signature) creation = { signature, key: requestKey() };
|
|
1327
|
+
// SDK create() sends only {purpose}. Business fields use your own API.
|
|
1328
|
+
const value = intent
|
|
1329
|
+
? validateTicket(await api('/api/authlink/requests', {
|
|
1330
|
+
purpose, postId: intent.id, version: intent.version,
|
|
1331
|
+
}, { 'Idempotency-Key': creation.key }), purpose, props.authLinkOrigin)
|
|
1332
|
+
: await client.create(purpose, { idempotencyKey: creation.key, signal: lifetime.signal });
|
|
1333
|
+
if (lifetime.signal.aborted) return;
|
|
1334
|
+
publication.value = intent; ticket.value = value; creation = null;
|
|
1335
|
+
} catch (error) {
|
|
1336
|
+
if (!lifetime.signal.aborted) showError(error as Error);
|
|
1337
|
+
// Retain creation.key for a retry of the SAME purpose/post/version.
|
|
1338
|
+
} finally { busy.value = false; }
|
|
1339
|
+
}
|
|
1340
|
+
async function publish() {
|
|
1341
|
+
const intent = retryPublish.value;
|
|
1342
|
+
if (!intent || busy.value) return;
|
|
1343
|
+
busy.value = true;
|
|
1344
|
+
try {
|
|
1345
|
+
await api(`/api/posts/${intent.id}/publish`, { version: intent.version, requestId: intent.requestId });
|
|
1346
|
+
retryPublish.value = null; message.value = 'Published. Reload your posts from the backend.';
|
|
1347
|
+
} catch (error) { if (!lifetime.signal.aborted) showError(error as Error); }
|
|
1348
|
+
finally { busy.value = false; }
|
|
1349
|
+
}
|
|
1350
|
+
async function confirmed(result: Confirmation) {
|
|
1351
|
+
const intent = publication.value;
|
|
1352
|
+
closeTicket();
|
|
1353
|
+
if (intent) { retryPublish.value = { ...intent, requestId: result.requestId }; await publish(); }
|
|
1354
|
+
else message.value = 'Verified. Reload account status from the backend.';
|
|
1355
|
+
}
|
|
1356
|
+
onMounted(async () => {
|
|
1357
|
+
try {
|
|
1358
|
+
const value = await api('/api/session');
|
|
1359
|
+
if (value.authenticated !== true || typeof value.csrf !== 'string' || !value.csrf) {
|
|
1360
|
+
throw new Error('LOGIN_REQUIRED');
|
|
1361
|
+
}
|
|
1362
|
+
session.value = value;
|
|
1363
|
+
} catch (error) { if (!lifetime.signal.aborted) showError(error as Error); }
|
|
554
1364
|
});
|
|
555
|
-
|
|
556
|
-
|
|
1365
|
+
onUnmounted(() => { lifetime.abort(); closeTicket(); creation = null; retryPublish.value = null; });
|
|
1366
|
+
</script>
|
|
1367
|
+
|
|
1368
|
+
<template>
|
|
1369
|
+
<button :disabled="busy || !!ticket || !session?.authenticated" @click="start('bind')">Bind phone</button>
|
|
1370
|
+
<button :disabled="busy || !!ticket || !session?.authenticated" @click="start('confirm')">Confirm</button>
|
|
1371
|
+
<button v-if="post" :disabled="busy || !!ticket || !session?.authenticated" @click="start('confirm', post)">Confirm publication</button>
|
|
1372
|
+
<button v-if="retryPublish" :disabled="busy || !!ticket" @click="publish">Retry the same publication</button>
|
|
1373
|
+
<AuthLinkBind v-if="ticket?.purpose === 'bind'" :ticket="ticket" :client="client" variant="B"
|
|
1374
|
+
@confirmed="confirmed" @close="finish('Closed')" @rejected="finish('Rejected')"
|
|
1375
|
+
@expired="finish('Expired; start a new request')" @error="showError" />
|
|
1376
|
+
<AuthLinkConfirm v-else-if="ticket?.purpose === 'confirm'" :ticket="ticket" :client="client" variant="B"
|
|
1377
|
+
@confirmed="confirmed" @close="finish('Closed')" @rejected="finish('Rejected')"
|
|
1378
|
+
@expired="finish('Expired; start a new request')" @error="showError" />
|
|
1379
|
+
<p role="status">{{ message }}</p>
|
|
1380
|
+
</template>
|
|
557
1381
|
```
|
|
558
1382
|
|
|
559
|
-
|
|
1383
|
+
普通绑定/确认使用 `client.create(purpose, {idempotencyKey})`。该方法只发送 purpose,**不能传入 postId/version 扩展请求体**。确认发布通过自己的 fetch 发送这些业务字段,再用 `validateTicket(response, 'confirm', authLinkOrigin)` 校验;后续弹窗查询仍复用官方 client。
|
|
560
1384
|
|
|
561
|
-
|
|
1385
|
+
同一次创建失败保留同一个键;用途或文章版本改变才换新键。`shallowRef` 保存 ticket,`markRaw` 保存客户端。组件挂载只打开和观察已有请求;不在 mounted/watch 中创建请求。关闭、拒绝和过期清空 ticket;网络错误保留弹窗,允许重试原请求。确认成功先清空 ticket,再调用独立业务接口;失败保留同一个 requestId / 文章 / 版本用于重试,先从后台确认真实状态后再刷新页面。上例省略网站自己的登录表单、文章列表和错误码中文映射。
|
|
1386
|
+
|
|
1387
|
+
#### 6. 发布接口必须再做后台检查
|
|
562
1388
|
|
|
1389
|
+
`confirmed` 回调只触发界面更新与下一次 API 请求,不是放行凭据。Go 的发布事务必须验证当前 session 对应的已落库回执,purpose=confirm、意图=publish、同一 postId、同一 version、文章归属和草稿状态,以及首次应用时尚未过期。成功时更新文章并标记请求 applied;重试已应用的同一操作返回原成功,不重复发布或写审计。请求不能用于另一文章或新版本,修改内容后须重新确认。前端不把文章内容、action 或 transactionHash 塞入 AuthLink 消费回执。
|
|
1390
|
+
|
|
1391
|
+
#### 验收顺序
|
|
1392
|
+
|
|
1393
|
+
登录 → 读取 session → 查询后台真实账号状态(参考 CMS 通过 overview 调用 Go SDK `AccountStatus`)→ 未绑定时 bind → 手机扫码批准 → 后台消费并刷新账号状态 → 保存草稿 → 按 postId/version confirm → 手机批准 → 结果消费落库 → 独立发布接口 → 重复发布/错误版本/拒绝/过期验证。真实设备验收仍由用户在手机上完成;本地编译和模拟 HTTP 测试不能代替这一步。
|
|
1394
|
+
|
|
1395
|
+
---
|
|
1396
|
+
|
|
1397
|
+
## 日本語
|
|
1398
|
+
|
|
1399
|
+
**AuthLink のスマートフォン登録とアプリでの確認**を Web サイトに組み込む React / Vue コンポーネントです。登録用 QR コード、同期する 6 桁の照合コード、カウントダウン、確認結果を表示します。特定のサイト基盤には依存しません。
|
|
1400
|
+
|
|
1401
|
+
### Go + Vue の接続手順
|
|
1402
|
+
|
|
1403
|
+
Go + Vue の実際の接続手順は [ログイン、端末登録、確認後の公開](#go-vue-cms-ja)、完全なコンポーネントは `examples/vue-cms.vue` を参照してください。
|
|
1404
|
+
|
|
1405
|
+
サイトのログイン → Go `/api/session` の authenticated/csrf → `csrfToken: () => session.csrf` で別 origin のクライアント設定 → bind/confirm 作成 → Go で消費・検証・DB コミット → ダイアログを閉じる → 独立した業務 API で保存済み確認結果を再検証して公開、という順序です。baseUrl は Go、authLinkOrigin は AuthLink を指し、テナントキーは Go に保持します。記事/版付き要求は独自 fetch と validateTicket を使い、SDK create は purpose のみ送ります。
|
|
563
1406
|
|
|
564
1407
|
### 主な機能
|
|
565
1408
|
|
|
@@ -583,55 +1426,223 @@ npm install @auth-link/web
|
|
|
583
1426
|
### 接続の流れ
|
|
584
1427
|
|
|
585
1428
|
1. サイトのバックエンドに AuthLink のテナント資格情報を設定します。
|
|
586
|
-
2.
|
|
1429
|
+
2. 下記の業務バックエンド(同一オリジンまたは明示的に許可した別オリジン)の作成・結果取得 API を実装します。
|
|
587
1430
|
3. ユーザー操作でリクエストを作成し、取得した ticket をコンポーネントに渡します。
|
|
588
1431
|
4. バックエンドが結果を検証・消費した後に確認完了を返します。
|
|
589
1432
|
|
|
590
|
-
ブラウザーからこのライブラリを呼び出せますが、テナント API
|
|
1433
|
+
ブラウザーからこのライブラリを呼び出せますが、テナント API キーと結果の消費処理は必ずサーバー側に置きます。標準クライアントは既定の同一オリジンと、明示的に許可した別オリジンに対応します。独自の通信方式では `AuthLinkClient` を実装できますが、資格情報と検証をブラウザーに移さないでください。
|
|
1434
|
+
|
|
1435
|
+
### クライアント作成(既定の同一オリジン Cookie モード)
|
|
591
1436
|
|
|
592
|
-
|
|
1437
|
+
`readCsrfTokenFromYourCms` は SDK のエクスポートではなく、接続先サイトで実装する関数です。現在のログインセッションに対してバックエンドが発行した CSRF token を読み取ります。CMS は必須ではありません。ブラウザーで値を生成したり、AuthLink の API キーを返したりしないでください。
|
|
1438
|
+
|
|
1439
|
+
既存フレームワークの CSRF 機構を優先してください。独自に実装する場合は、サーバーで暗号学的乱数(Node の `randomBytes(32).toString('base64url')` など)を生成し、セッションに保存して HTML 属性をエスケープしたうえでページに埋め込みます。下記の `{{ csrfToken }}` はサーバーテンプレートの変数です。このページを公開キャッシュしないでください。
|
|
1440
|
+
|
|
1441
|
+
```html
|
|
1442
|
+
<meta name="csrf-token" content="{{ csrfToken }}">
|
|
1443
|
+
```
|
|
1444
|
+
|
|
1445
|
+
SDK は各リクエストで token を読み取り、`X-CSRF-Token` と同一オリジンのセッション cookie を送信します。作成 API と結果 API の両方で、バックエンドが同じセッションの token と照合し、欠落・不一致や不正なリクエスト元を拒否する必要があります。ログインやセッション変更後は最新 token を取得してください。SPA ではサイト独自の同一オリジン初期化 API から取得する方法も使えます。別のヘッダー名を使うフレームワークでは`csrfHeaderName` または独自 `AuthLinkClient` で適合します。
|
|
1446
|
+
|
|
1447
|
+
`authlink-client.ts` を作成します:
|
|
593
1448
|
|
|
594
1449
|
```ts
|
|
595
1450
|
// authlink-client.ts
|
|
596
|
-
import { createAuthLinkClient
|
|
1451
|
+
import { createAuthLinkClient } from '@auth-link/web';
|
|
597
1452
|
import '@auth-link/web/styles.css';
|
|
598
1453
|
|
|
1454
|
+
// The application server renders this meta element using the current session's
|
|
1455
|
+
// CSRF token. This function only reads that token; it does not generate one.
|
|
1456
|
+
export function readCsrfTokenFromYourCms(): string {
|
|
1457
|
+
const token = document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.content;
|
|
1458
|
+
if (!token) throw new Error('Missing CSRF token; load the authenticated application page first.');
|
|
1459
|
+
return token;
|
|
1460
|
+
}
|
|
1461
|
+
|
|
599
1462
|
export const client = createAuthLinkClient({
|
|
600
1463
|
baseUrl: '/api/authlink',
|
|
601
|
-
csrfToken:
|
|
602
|
-
|
|
603
|
-
if (!token) throw new Error('Missing CSRF token');
|
|
604
|
-
return token;
|
|
605
|
-
},
|
|
1464
|
+
csrfToken: readCsrfTokenFromYourCms,
|
|
1465
|
+
// Replace this example with the configured AuthLink service origin.
|
|
606
1466
|
authLinkOrigin: 'https://auth.example.com',
|
|
607
1467
|
});
|
|
1468
|
+
```
|
|
1469
|
+
|
|
1470
|
+
`https://auth.example.com` は実際の AuthLink オリジンに置き換えてください。リクエストは下記の React 例のようにユーザー操作で作成します。
|
|
1471
|
+
|
|
1472
|
+
### フロントエンドとバックエンドの別オリジン対応(0.0.2 以降)
|
|
1473
|
+
|
|
1474
|
+
既定は同一オリジンの `/api/authlink` です。別オリジンの業務 API に直接接続するには完全な `baseUrl` と `allowedBackendOrigins` を指定します。例:フロントエンド `https://www.example.com`、バックエンド `https://api.example.com`。サブドメインやポートが異なる場合も別オリジンです。許可リストにはパス、ワイルドカード、ユーザー名・パスワードを含めず、信頼する固定設定を使います。HTTPS が必須で、開発用 HTTP loopback(localhost / 127.0.0.1 / [::1])のみ例外です。
|
|
1475
|
+
|
|
1476
|
+
SDK は認証情報を読む前に接続先を検証し、リダイレクトを拒否します。`authLinkOrigin` は QR 内の AuthLink サービスオリジンの検証用で、業務 API の許可リストとは別です。
|
|
1477
|
+
|
|
1478
|
+
#### 別オリジンの Cookie / session
|
|
608
1479
|
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
1480
|
+
汎用例の JSON 名は csrfToken ですが、Go CMS の実際の応答は `{ authenticated: true, csrf: '…' }` です。session.csrf を SDK の csrfToken コールバックに渡せばよく、バックエンドのフィールド名を変更する必要はありません。
|
|
1481
|
+
|
|
1482
|
+
下記の `GET /api/session` はサイトで実装する例示 API で、SDK が提供する API ではありません。ログイン session の `{ "csrfToken": "現在のtoken" }` を返し、`Cache-Control: no-store` と CORS を設定します。既存サイトの API パスに適合してください。
|
|
1483
|
+
|
|
1484
|
+
```ts
|
|
1485
|
+
import { createAuthLinkClient } from '@auth-link/web';
|
|
1486
|
+
|
|
1487
|
+
/** /api/session is an example endpoint implemented by your application backend. */
|
|
1488
|
+
export async function createSessionBackendClient(backendOrigin: string) {
|
|
1489
|
+
const response = await fetch(`${backendOrigin}/api/session`, {
|
|
1490
|
+
credentials: 'include', cache: 'no-store', redirect: 'error',
|
|
1491
|
+
});
|
|
1492
|
+
if (!response.ok) throw new Error('Session initialization failed');
|
|
1493
|
+
const session: unknown = await response.json();
|
|
1494
|
+
if (!session || typeof session !== 'object' || !('csrfToken' in session) ||
|
|
1495
|
+
typeof session.csrfToken !== 'string' || !session.csrfToken) {
|
|
1496
|
+
throw new Error('The session endpoint must return { csrfToken: string }');
|
|
1497
|
+
}
|
|
1498
|
+
let currentCsrfToken = session.csrfToken;
|
|
1499
|
+
return {
|
|
1500
|
+
client: createAuthLinkClient({
|
|
1501
|
+
baseUrl: `${backendOrigin}/api/authlink`,
|
|
1502
|
+
allowedBackendOrigins: [backendOrigin],
|
|
1503
|
+
credentials: 'include',
|
|
1504
|
+
csrfToken: () => currentCsrfToken,
|
|
1505
|
+
}),
|
|
1506
|
+
// Call after your application's session/token refresh; recreate on account changes.
|
|
1507
|
+
updateCsrfToken(value: string) { currentCsrfToken = value; },
|
|
1508
|
+
};
|
|
1509
|
+
}
|
|
1510
|
+
```
|
|
1511
|
+
|
|
1512
|
+
ログイン後に `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` が必要で、ブラウザーによっては引き続き拒否されます。
|
|
1513
|
+
|
|
1514
|
+
#### Bearer token / JWT
|
|
1515
|
+
|
|
1516
|
+
サイトの既存ログイン状態を渡してください。ログイン・更新処理で `auth.accessToken` を更新すると、SDK は作成・ポーリングのたびに最新値を読み取ります。
|
|
1517
|
+
|
|
1518
|
+
```ts
|
|
1519
|
+
import { createAuthLinkClient } from '@auth-link/web';
|
|
1520
|
+
|
|
1521
|
+
/** auth is your website's existing login state, updated by its login/refresh flow. */
|
|
1522
|
+
export function createBearerBackendClient(backendOrigin: string, auth: { accessToken: string }) {
|
|
1523
|
+
return createAuthLinkClient({
|
|
1524
|
+
baseUrl: `${backendOrigin}/api/authlink`,
|
|
1525
|
+
allowedBackendOrigins: [backendOrigin],
|
|
1526
|
+
credentials: 'omit',
|
|
1527
|
+
accessToken: () => auth.accessToken,
|
|
1528
|
+
});
|
|
1529
|
+
}
|
|
613
1530
|
```
|
|
614
1531
|
|
|
615
|
-
|
|
1532
|
+
これはサイト利用者のログイン token であり、AuthLink のテナント API キーではありません。SDK が `Authorization: Bearer ...` を付加します。`accessToken` 指定時は既定で `credentials: 'omit'` となり、Cookie にフォールバックせず Bearer のみで認証するバックエンドでは CSRF を省略できます。`include` / `same-origin` を明示して Cookie を併用する場合は CSRF の提供・検証も必要です。
|
|
1533
|
+
|
|
1534
|
+
#### バックエンドの CORS
|
|
1535
|
+
|
|
1536
|
+
`OPTIONS` プリフライトを処理し、実リクエスト・エラー応答・session 初期化 API にも必要な CORS ヘッダーを返します。フロントエンドが `https://www.example.com` の例:
|
|
1537
|
+
|
|
1538
|
+
```http
|
|
1539
|
+
Access-Control-Allow-Origin: https://www.example.com
|
|
1540
|
+
Access-Control-Allow-Credentials: true
|
|
1541
|
+
Access-Control-Allow-Methods: GET, POST, OPTIONS
|
|
1542
|
+
Access-Control-Allow-Headers: Content-Type, X-CSRF-Token, Idempotency-Key, Authorization
|
|
1543
|
+
Vary: Origin
|
|
1544
|
+
```
|
|
1545
|
+
|
|
1546
|
+
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) を参照してください。
|
|
1547
|
+
|
|
1548
|
+
#### クライアント設定
|
|
1549
|
+
|
|
1550
|
+
| 設定 | 説明 |
|
|
1551
|
+
| --- | --- |
|
|
1552
|
+
| `baseUrl` | 業務 API の接頭辞、既定 `/api/authlink`;別オリジン時は完全 URL |
|
|
1553
|
+
| `allowedBackendOrigins` | 追加許可する正確な業務 API オリジンの配列 |
|
|
1554
|
+
| `credentials` | 既定 `same-origin`、`accessToken` 指定時 `omit`;別オリジン Cookie は `include` |
|
|
1555
|
+
| `csrfToken` | リクエストごとの同期/非同期取得関数;Cookie モードは必須 |
|
|
1556
|
+
| `csrfHeaderName` | 既定 `X-CSRF-Token`、フレームワークに合わせて変更可能 |
|
|
1557
|
+
| `accessToken` | サイトのログイン token 取得関数;`Bearer ` 接頭辞は付けない |
|
|
1558
|
+
| `headers` | 追加 `HeadersInit`、またはそれを返す同期/非同期関数 |
|
|
1559
|
+
| `authLinkOrigin` | QR 内の信頼するサービスオリジン。業務 API オリジンとは別 |
|
|
1560
|
+
| `fetch` | 任意の fetch 実装;接続先検証は維持 |
|
|
1561
|
+
|
|
1562
|
+
追加ヘッダーは SDK 管理の `Accept`、`Content-Type`、`Authorization`、`Idempotency-Key`、設定済み CSRF ヘッダーを上書きできません(`RESERVED_HEADER`)。`accessToken` と `csrfHeaderName` を使用してください。設定型 `ClientOptions` はルートエントリーからインポートできます。
|
|
1563
|
+
|
|
1564
|
+
未許可オリジンは `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` になります。
|
|
1565
|
+
|
|
1566
|
+
### 関数でダイアログを開く(React / Vue / JavaScript)
|
|
1567
|
+
|
|
1568
|
+
```ts
|
|
1569
|
+
import { openAuthLinkBind, openAuthLinkConfirm, requestKey } from '@auth-link/web';
|
|
1570
|
+
import { client } from './authlink-client';
|
|
1571
|
+
import '@auth-link/web/styles.css';
|
|
1572
|
+
|
|
1573
|
+
const ticket = await client.create('confirm', { idempotencyKey: requestKey() });
|
|
1574
|
+
const modal = openAuthLinkConfirm({
|
|
1575
|
+
ticket, client, locale: 'ja',
|
|
1576
|
+
onConfirmed: result => console.log(result.requestId),
|
|
1577
|
+
onClose: () => console.log('Closed'),
|
|
1578
|
+
});
|
|
1579
|
+
// 登録: openAuthLinkBind({ ticket: bindingTicket, client })
|
|
1580
|
+
// modal.close(); modal.setLocale('en');
|
|
1581
|
+
```
|
|
1582
|
+
|
|
1583
|
+
React / Vue コンポーネントもマウント時にダイアログを開きます。React の onClose、Vue の @close で ticket を消去してアンマウントしてください。SSR はダイアログも通信も生成しません。スマートフォンの画面幅、スクロール、閉じるボタン、Escape に対応し、ネイティブ dialog.showModal() が必要です。body 直下に表示するため、テーマ変数は :root または .authlink-dialog に設定します。
|
|
1584
|
+
|
|
1585
|
+
閉じてもサーバーのリクエストを拒否・取消しません。元の有効期限は維持されます。承認・拒否時は自動で閉じ、onConfirmed または onRejected を通知します。ユーザー操作の onClose は通知しません。関数で開いた場合はページ破棄時に modal.destroy() を呼んで通信と UI を解除してください。destroy() は onClose を通知しません。modal.setLocale() はリクエストを作り直さずに言語を切り替えます。
|
|
1586
|
+
|
|
616
1587
|
|
|
617
1588
|
### React
|
|
618
1589
|
|
|
1590
|
+
`showBound(requestId)` はサイトの表示更新用関数です。メッセージを更新し、ticket を消去してダイアログをアンマウントします。下記には拒否・期限切れ・閉じる処理も含まれます。`<AuthLinkPanel mode="bind" />` または `<AuthLinkPanel mode="confirm" />` で使います。
|
|
1591
|
+
|
|
619
1592
|
```tsx
|
|
1593
|
+
"use client";
|
|
1594
|
+
import { useRef, useState } from 'react';
|
|
1595
|
+
import { requestKey } from '@auth-link/web';
|
|
1596
|
+
import type { Mode, Ticket } from '@auth-link/web';
|
|
620
1597
|
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/react';
|
|
621
|
-
import type { Ticket, Confirmation } from '@auth-link/web';
|
|
622
1598
|
import { client } from './authlink-client';
|
|
623
1599
|
|
|
624
|
-
export function
|
|
625
|
-
const
|
|
626
|
-
|
|
1600
|
+
export function AuthLinkPanel({ mode }: { mode: Mode }) {
|
|
1601
|
+
const [ticket, setTicket] = useState<Ticket | null>(null);
|
|
1602
|
+
const [busy, setBusy] = useState(false);
|
|
1603
|
+
const [message, setMessage] = useState('');
|
|
1604
|
+
const key = useRef<string | null>(null);
|
|
1605
|
+
const creating = useRef(false);
|
|
1606
|
+
function finish(message: string) {
|
|
1607
|
+
setTicket(null);
|
|
1608
|
+
setMessage(message);
|
|
1609
|
+
}
|
|
1610
|
+
function showBound(requestId: string) {
|
|
1611
|
+
// UI feedback only. The backend has already verified and saved the binding.
|
|
1612
|
+
finish(`Phone bound (request ${requestId})`);
|
|
1613
|
+
}
|
|
1614
|
+
function showConfirmed(requestId: string) {
|
|
1615
|
+
finish(`Confirmed (request ${requestId})`);
|
|
1616
|
+
}
|
|
1617
|
+
const start = async () => {
|
|
1618
|
+
if (creating.current || ticket) return;
|
|
1619
|
+
creating.current = true;
|
|
1620
|
+
setBusy(true);
|
|
1621
|
+
setMessage('');
|
|
1622
|
+
try {
|
|
1623
|
+
key.current ??= requestKey();
|
|
1624
|
+
setTicket(await client.create(mode, { idempotencyKey: key.current }));
|
|
1625
|
+
key.current = null;
|
|
1626
|
+
} catch { setMessage('Request failed; retry the same creation.'); }
|
|
1627
|
+
finally { creating.current = false; setBusy(false); }
|
|
627
1628
|
};
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
1629
|
+
const Component = mode === 'bind' ? AuthLinkBind : AuthLinkConfirm;
|
|
1630
|
+
return <>
|
|
1631
|
+
{!ticket && <button type="button" disabled={busy} onClick={() => void start()}>Start verification</button>}
|
|
1632
|
+
{ticket && <Component ticket={ticket} client={client}
|
|
1633
|
+
onConfirmed={result => result.purpose === 'bind' ? showBound(result.requestId) : showConfirmed(result.requestId)}
|
|
1634
|
+
onClose={() => finish('Closed')}
|
|
1635
|
+
onRejected={() => finish('Request rejected on the phone')}
|
|
1636
|
+
onExpired={() => finish('Request expired; start again')}
|
|
1637
|
+
onError={error => setMessage(error.message)} />}
|
|
1638
|
+
<p role="status">{message}</p>
|
|
1639
|
+
</>;
|
|
632
1640
|
}
|
|
633
1641
|
```
|
|
634
1642
|
|
|
1643
|
+
バックエンドは結果を検証・消費・保存してから `confirmed` を返します。`showBound` は権限付与や紐付け保存を行いません。通知、サイトのアカウント状態 API の再取得、管理ページへの移動などに置き換えられます。ページ再読み込み後はサーバーから状態を取得し、コールバックや localStorage を認可に使わないでください。作成失敗時には同じ冪等キーを再利用します。
|
|
1644
|
+
|
|
1645
|
+
|
|
635
1646
|
`locale` を省略すると簡体字中国語です。日本語は `locale="ja"`、簡体字中国語は `locale="zh-CN"` を指定します。client と ticket はレンダー間で安定したオブジェクトにしてください。React エントリーは `"use client"` を保持し、SSR ではリクエストを作成しません。
|
|
636
1647
|
|
|
637
1648
|
### Vue
|
|
@@ -711,7 +1722,7 @@ React / Vue では表示中にも変更でき、リクエストやポーリン
|
|
|
711
1722
|
|
|
712
1723
|
### バックエンド API
|
|
713
1724
|
|
|
714
|
-
既定の接頭辞は `/api/authlink` です。両 API
|
|
1725
|
+
既定の接頭辞は `/api/authlink` です。両 API で Cookie + 設定した CSRF ヘッダー、または Bearer token による本人確認とリクエスト所有者を検証してください。作成時は `Idempotency-Key` も送信されます。サイトのユーザー ID は検証済みセッション/token から決定します。
|
|
715
1726
|
|
|
716
1727
|
```ts
|
|
717
1728
|
import type { Ticket, Result } from '@auth-link/web';
|
|
@@ -762,7 +1773,9 @@ import type { Ticket, Result } from '@auth-link/web';
|
|
|
762
1773
|
|
|
763
1774
|
### スタイルとエントリー
|
|
764
1775
|
|
|
765
|
-
`@auth-link/web/styles.css`
|
|
1776
|
+
`@auth-link/web/styles.css` を明示的に読み込みます。ダイアログは `document.body` に追加されるため、`:root` または `.authlink-dialog` で `--authlink-foreground`、`--authlink-background`、`--authlink-accent`、`--authlink-muted` を上書きします。クラス名の接頭辞は `authlink-` です。
|
|
1777
|
+
|
|
1778
|
+
React / Vue はダイアログの `className` に対応します。Vue は文字列・配列・オブジェクト形式の `class` も受け取り、`className` と結合します。再作成ボタンは親が渡した最新の `onRefresh` を呼び出します。
|
|
766
1779
|
|
|
767
1780
|
| エントリー | 内容 |
|
|
768
1781
|
| --- | --- |
|
|
@@ -775,7 +1788,7 @@ import type { Ticket, Result } from '@auth-link/web';
|
|
|
775
1788
|
|
|
776
1789
|
- 数字はアプリとの目視照合用です。数字だけで認証や承認はできません。
|
|
777
1790
|
- ブラウザーに生成 seed、端末秘密鍵、テナント秘密情報を渡しません。
|
|
778
|
-
- リクエストは最大 120 秒。コード更新で期限は延長されません。サービスとアプリはモバイルプロトコル
|
|
1791
|
+
- リクエストは最大 120 秒。コード更新で期限は延長されません。サービスとアプリはモバイルプロトコル 7 に対応する必要があります。
|
|
779
1792
|
- サーバー時刻と単調増加時計で残り時間を計算し、通信が止まっても期限切れの数字は隠します。更新境界で短い待ち時間が生じる場合があります。
|
|
780
1793
|
- アンマウントや ticket 変更で監視を中止します。インスタンス内のイベント重複防止とは別に、バックエンドで永続的な冪等処理が必要です。
|
|
781
1794
|
- フロントエンドのイベントは UI 更新用です。保護 API はバックエンドの信頼できる記録で判断します。
|
|
@@ -783,4 +1796,257 @@ import type { Ticket, Result } from '@auth-link/web';
|
|
|
783
1796
|
|
|
784
1797
|
### ライセンス
|
|
785
1798
|
|
|
786
|
-
|
|
1799
|
+
MIT。ライセンス全文は `LICENSE`、同梱ライブラリの帰属表示は `THIRD_PARTY_NOTICES.md` を参照してください。
|
|
1800
|
+
|
|
1801
|
+
### Go Vue CMS: ja
|
|
1802
|
+
|
|
1803
|
+
実際の Go CMS + Vue 3 の接続順序を示します。例のドメインは置き換え用で、ローカル設定・テスト用パスワード・テナント資格情報は含めません。ログイン、DB、業務 API はサイト側で実装し、Web SDK は表示と監視、Go SDK は AuthLink 呼び出しと応答検証を担当します。
|
|
1804
|
+
|
|
1805
|
+
#### 1. 3 つの origin と SDK
|
|
1806
|
+
|
|
1807
|
+
| 役割 | 例 | 設定 |
|
|
1808
|
+
| --- | --- | --- |
|
|
1809
|
+
| Vue | `https://cms.example.com` | `apiOrigin` は下記 Go バックエンド |
|
|
1810
|
+
| Go CMS API | `https://cms-api.example.com` | `baseUrl=https://cms-api.example.com/api/authlink` |
|
|
1811
|
+
| AuthLink API | `https://auth.example.com` | Go SDK の `Origin`;ブラウザーの `authLinkOrigin` |
|
|
1812
|
+
|
|
1813
|
+
テナントに登録するサイト origin は Vue の origin です。Go SDK の Origin と資格情報 JSON の API origin は AuthLink API を指します。ブラウザーの baseUrl は Go の業務 API です。TenantID/APIKey はバックエンドの非公開設定にのみ保存します。
|
|
1814
|
+
|
|
1815
|
+
```sh
|
|
1816
|
+
npm install @auth-link/web@latest vue
|
|
1817
|
+
# In your Go backend module, after unpacking the supplied Go SDK:
|
|
1818
|
+
go mod edit -replace=authlink.local/sdk=./third_party/authlink-go
|
|
1819
|
+
go mod edit -require=authlink.local/sdk@v0.0.0
|
|
1820
|
+
go mod tidy
|
|
1821
|
+
```
|
|
1822
|
+
|
|
1823
|
+
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})` で初期化します。
|
|
1824
|
+
|
|
1825
|
+
#### 2. サイトのログインと session
|
|
1826
|
+
|
|
1827
|
+
サイトのログイン API(参照 CMS は POST /api/login)が Secure・HttpOnly の session Cookie を発行します。Vue は credentials=include で GET /api/session を読み、authenticated=true と csrf を確認してから要求を作成します。未ログインならサイト自身のログインへ戻します。
|
|
1828
|
+
|
|
1829
|
+
この CMS の JSON フィールド名は **csrf**、SDK オプション名は **csrfToken** です。`csrfToken: () => session.value?.csrf ?? ''` で対応します。JSON の名前を SDK に合わせる必要はありません。Go が session ごとに生成・保存し、作成と結果照会の両方で X-CSRF-Token を検証します。テナントキーや照合数字を代用しません。
|
|
1830
|
+
|
|
1831
|
+
同じサイトの HTTPS サブドメイン同士は別 origin・同 site です。参照 API の Cookie は Domain を指定しない host-only、SameSite=Strict; Secure; HttpOnly; Path=/ です。別 site の場合は CORS に加えてブラウザーの Cookie 制限も考慮します。
|
|
1832
|
+
|
|
1833
|
+
#### 3. Go の CORS と業務ルート
|
|
1834
|
+
|
|
1835
|
+
```http
|
|
1836
|
+
Access-Control-Allow-Origin: https://cms.example.com
|
|
1837
|
+
Access-Control-Allow-Credentials: true
|
|
1838
|
+
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS
|
|
1839
|
+
Access-Control-Allow-Headers: Content-Type, X-CSRF-Token, Idempotency-Key
|
|
1840
|
+
Vary: Origin
|
|
1841
|
+
Cache-Control: no-store
|
|
1842
|
+
```
|
|
1843
|
+
|
|
1844
|
+
正確に許可した Vue origin にだけ返し、その origin のエラー応答にも付与します。OPTIONS は origin・method・headers を検証して 204 を返し、ログインや CSRF は要求しません。実リクエストでログイン、CSRF、所有者を検証します。任意 origin の反射や * は使いません。PUT は CMS の下書き編集用なので必要なルートに合わせて限定できます。
|
|
1845
|
+
|
|
1846
|
+
| サイト自身のルート | 入力 | 出力 |
|
|
1847
|
+
| --- | --- | --- |
|
|
1848
|
+
| `GET /api/session` | — | `{authenticated:true, csrf:"…", subject:"…", username:"…"}`;未ログイン: `{authenticated:false}` |
|
|
1849
|
+
| `POST /api/authlink/requests` | `{purpose:"bind"}` または `{purpose:"confirm",postId,version}`; `Idempotency-Key` | 公開 `Ticket` |
|
|
1850
|
+
| `POST /api/authlink/requests/{id}/result` | `{}`;現在の session + CSRF | 待機状態/displayCode または検証済み `confirmed` |
|
|
1851
|
+
| `POST /api/posts/{id}/publish` | `{requestId,version}`; 現在の session + CSRF | `{ok:true}` 保存済み確認結果と業務意図の検証後 |
|
|
1852
|
+
|
|
1853
|
+
これらのルートは Go CMS が実装します。postId/version と公開ルートはこの業務の契約で、AuthLink のプロトコル項目ではありません。
|
|
1854
|
+
|
|
1855
|
+
#### 4. 作成前に保存し、検証のコミット後に confirmed
|
|
1856
|
+
|
|
1857
|
+
```text
|
|
1858
|
+
Vue → Go /api/session → current session + csrf
|
|
1859
|
+
Vue → Go /api/authlink/requests → Go SDK CreateRequest → public ticket
|
|
1860
|
+
Vue dialog → Go /api/authlink/requests/{id}/result → Status + Consume
|
|
1861
|
+
Go commits verified receipt → Vue confirmed event
|
|
1862
|
+
Vue → Go /api/posts/{id}/publish → validate saved intent/receipt → publish
|
|
1863
|
+
```
|
|
1864
|
+
|
|
1865
|
+
安定したユーザー ID は認証済み session から取得します。用途、作成キー、記事の所有者と版を検証し、state と消費キーを別々に生成します。上流通信の前に CreateInput、ブラウザーの作成キー、ユーザー/session、記事公開の意図を保存します。通信失敗時は同一レコード・入力・キーを再利用します。session + 作成キーを一意にし、異なる用途・記事・版への再利用を拒否します。
|
|
1866
|
+
|
|
1867
|
+
ticket、requestId、元の expiresAt を保存し、任意の qrSvg を除いて公開 ticket を返します。結果 API は現在の session が所有する記録をロックし、保存済み確認結果があれば再利用します。Status が approved/consumed のときだけ、DB の値から Expected を組み立て Consume を実行します。検証済み確認結果、session の確認記録、監査を requestId/verificationId の一意制約付きトランザクションで保存し、コミット後に confirmed を返します。待機中は displayCode を有効期限を越えてキャッシュしません。
|
|
1868
|
+
|
|
1869
|
+
以下は SDK 呼び出し層であり、完全な HTTP サーバーではありません。DB、トランザクション、所有者検証は説明とコメントに従ってサイト側で実装します。
|
|
1870
|
+
|
|
1871
|
+
```go
|
|
1872
|
+
package cmsauth
|
|
1873
|
+
|
|
1874
|
+
import (
|
|
1875
|
+
"context"
|
|
1876
|
+
authlink "authlink.local/sdk"
|
|
1877
|
+
)
|
|
1878
|
+
|
|
1879
|
+
// Load this record from your database for the authenticated user/session.
|
|
1880
|
+
// Save Input (including State), CreateKey and ConsumeKey BEFORE calling Create.
|
|
1881
|
+
// Intent (post ID/version), ownership and unique constraints belong in your DB.
|
|
1882
|
+
type StoredRequest struct {
|
|
1883
|
+
Input authlink.CreateInput
|
|
1884
|
+
CreateKey string
|
|
1885
|
+
ConsumeKey string
|
|
1886
|
+
Ticket authlink.Ticket
|
|
1887
|
+
}
|
|
1888
|
+
|
|
1889
|
+
// On network retries, load the SAME record; do not regenerate State or keys.
|
|
1890
|
+
func Create(ctx context.Context, sdk *authlink.Client, saved StoredRequest) (authlink.Ticket, error) {
|
|
1891
|
+
return sdk.CreateRequest(ctx, saved.Input, saved.CreateKey)
|
|
1892
|
+
}
|
|
1893
|
+
|
|
1894
|
+
type PublicConfirmation struct {
|
|
1895
|
+
Status string `json:"status"`
|
|
1896
|
+
RequestID string `json:"requestId"`
|
|
1897
|
+
VerificationID string `json:"verificationId"`
|
|
1898
|
+
Purpose string `json:"purpose"`
|
|
1899
|
+
ExpiresAt string `json:"expiresAt"`
|
|
1900
|
+
AuthenticationPolicy string `json:"authenticationPolicy"`
|
|
1901
|
+
}
|
|
1902
|
+
|
|
1903
|
+
// Caller checks session/CSRF/ownership, locks the saved record and first returns
|
|
1904
|
+
// any already-saved receipt. For a new confirmed result, caller must persist
|
|
1905
|
+
// the receipt and confirmation in a DB transaction BEFORE returning HTTP 200.
|
|
1906
|
+
func Poll(ctx context.Context, sdk *authlink.Client, saved StoredRequest) (any, error) {
|
|
1907
|
+
status, err := sdk.Status(ctx, saved.Ticket.RequestID)
|
|
1908
|
+
if err != nil { return nil, err }
|
|
1909
|
+
if status.Status != "approved" && status.Status != "consumed" { return status, nil }
|
|
1910
|
+
result, err := sdk.Consume(ctx, authlink.Expected{
|
|
1911
|
+
RequestID: saved.Ticket.RequestID,
|
|
1912
|
+
ExternalUserID: saved.Input.ExternalUserID,
|
|
1913
|
+
Purpose: saved.Input.Purpose,
|
|
1914
|
+
State: saved.Input.State,
|
|
1915
|
+
ExpiresAt: saved.Ticket.ExpiresAt,
|
|
1916
|
+
}, saved.ConsumeKey)
|
|
1917
|
+
if err != nil { return nil, err }
|
|
1918
|
+
return PublicConfirmation{
|
|
1919
|
+
Status: "confirmed", RequestID: result.RequestID,
|
|
1920
|
+
VerificationID: result.VerificationID, Purpose: result.Purpose,
|
|
1921
|
+
ExpiresAt: saved.Ticket.ExpiresAt, AuthenticationPolicy: result.AuthenticationPolicy,
|
|
1922
|
+
}, nil
|
|
1923
|
+
}
|
|
1924
|
+
```
|
|
1925
|
+
|
|
1926
|
+
#### 5. Vue のライフサイクルと業務データ付き要求
|
|
1927
|
+
|
|
1928
|
+
完全なファイルは `examples/vue-cms.vue` にも同梱します。サイトのログイン後、信頼できる apiOrigin/authLinkOrigin と任意の保存済み下書き `post={id,version}` を渡してマウントします。親は認証 session の識別子を key に使います。ログアウト・再ログイン・アカウント切り替えでは先にアンマウントし、古い ticket・作成キー・未完了の公開処理を消去してから新規マウントします。
|
|
1929
|
+
|
|
1930
|
+
```vue
|
|
1931
|
+
<script setup lang="ts">
|
|
1932
|
+
import { markRaw, onMounted, onUnmounted, ref, shallowRef } from 'vue';
|
|
1933
|
+
import { createAuthLinkClient, requestKey, validateTicket } from '@auth-link/web';
|
|
1934
|
+
import type { Confirmation, Mode, Ticket } from '@auth-link/web';
|
|
1935
|
+
import { AuthLinkBind, AuthLinkConfirm } from '@auth-link/web/vue';
|
|
1936
|
+
import '@auth-link/web/styles.css';
|
|
1937
|
+
|
|
1938
|
+
type Post = { id: string; version: number };
|
|
1939
|
+
type Publication = Post & { requestId: string };
|
|
1940
|
+
// Supply trusted deployment configuration. Mount after site login and remount
|
|
1941
|
+
// with :key="session.subject" after login, logout or account/session changes.
|
|
1942
|
+
const props = defineProps<{ apiOrigin: string; authLinkOrigin: string; post?: Post }>();
|
|
1943
|
+
const session = ref<{ authenticated: boolean; csrf?: string } | null>(null);
|
|
1944
|
+
const ticket = shallowRef<Ticket | null>(null);
|
|
1945
|
+
const publication = shallowRef<Post | null>(null);
|
|
1946
|
+
const retryPublish = shallowRef<Publication | null>(null);
|
|
1947
|
+
const busy = ref(false), message = ref('');
|
|
1948
|
+
let creation: { signature: string; key: string } | null = null;
|
|
1949
|
+
const lifetime = new AbortController();
|
|
1950
|
+
const client = markRaw(createAuthLinkClient({
|
|
1951
|
+
baseUrl: `${props.apiOrigin}/api/authlink`,
|
|
1952
|
+
allowedBackendOrigins: [props.apiOrigin],
|
|
1953
|
+
credentials: 'include',
|
|
1954
|
+
csrfToken: () => session.value?.csrf ?? '',
|
|
1955
|
+
authLinkOrigin: props.authLinkOrigin,
|
|
1956
|
+
}));
|
|
1957
|
+
|
|
1958
|
+
async function api(path: string, body?: unknown, headers: Record<string, string> = {}) {
|
|
1959
|
+
const response = await fetch(`${props.apiOrigin}${path}`, {
|
|
1960
|
+
method: body === undefined ? 'GET' : 'POST',
|
|
1961
|
+
credentials: 'include', cache: 'no-store', redirect: 'error',
|
|
1962
|
+
signal: lifetime.signal,
|
|
1963
|
+
headers: body === undefined ? {} : {
|
|
1964
|
+
'Content-Type': 'application/json', 'X-CSRF-Token': session.value?.csrf ?? '', ...headers,
|
|
1965
|
+
},
|
|
1966
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
1967
|
+
});
|
|
1968
|
+
const value = await response.json();
|
|
1969
|
+
if (response.status === 401) {
|
|
1970
|
+
session.value = null; closeTicket(); retryPublish.value = null; creation = null;
|
|
1971
|
+
}
|
|
1972
|
+
if (!response.ok) throw new Error(value.code ?? 'REQUEST_FAILED');
|
|
1973
|
+
return value;
|
|
1974
|
+
}
|
|
1975
|
+
function closeTicket() { ticket.value = null; publication.value = null; }
|
|
1976
|
+
function showError(error: Error) { message.value = error.message; }
|
|
1977
|
+
function finish(text: string) { closeTicket(); message.value = text; }
|
|
1978
|
+
|
|
1979
|
+
async function start(purpose: Mode, post?: Post) {
|
|
1980
|
+
if (busy.value || ticket.value || !session.value?.authenticated) return;
|
|
1981
|
+
busy.value = true; message.value = ''; retryPublish.value = null;
|
|
1982
|
+
const intent = post ? { id: post.id, version: post.version } : null;
|
|
1983
|
+
const signature = JSON.stringify({ purpose, postId: intent?.id, version: intent?.version });
|
|
1984
|
+
try {
|
|
1985
|
+
if (creation?.signature !== signature) creation = { signature, key: requestKey() };
|
|
1986
|
+
// SDK create() sends only {purpose}. Business fields use your own API.
|
|
1987
|
+
const value = intent
|
|
1988
|
+
? validateTicket(await api('/api/authlink/requests', {
|
|
1989
|
+
purpose, postId: intent.id, version: intent.version,
|
|
1990
|
+
}, { 'Idempotency-Key': creation.key }), purpose, props.authLinkOrigin)
|
|
1991
|
+
: await client.create(purpose, { idempotencyKey: creation.key, signal: lifetime.signal });
|
|
1992
|
+
if (lifetime.signal.aborted) return;
|
|
1993
|
+
publication.value = intent; ticket.value = value; creation = null;
|
|
1994
|
+
} catch (error) {
|
|
1995
|
+
if (!lifetime.signal.aborted) showError(error as Error);
|
|
1996
|
+
// Retain creation.key for a retry of the SAME purpose/post/version.
|
|
1997
|
+
} finally { busy.value = false; }
|
|
1998
|
+
}
|
|
1999
|
+
async function publish() {
|
|
2000
|
+
const intent = retryPublish.value;
|
|
2001
|
+
if (!intent || busy.value) return;
|
|
2002
|
+
busy.value = true;
|
|
2003
|
+
try {
|
|
2004
|
+
await api(`/api/posts/${intent.id}/publish`, { version: intent.version, requestId: intent.requestId });
|
|
2005
|
+
retryPublish.value = null; message.value = 'Published. Reload your posts from the backend.';
|
|
2006
|
+
} catch (error) { if (!lifetime.signal.aborted) showError(error as Error); }
|
|
2007
|
+
finally { busy.value = false; }
|
|
2008
|
+
}
|
|
2009
|
+
async function confirmed(result: Confirmation) {
|
|
2010
|
+
const intent = publication.value;
|
|
2011
|
+
closeTicket();
|
|
2012
|
+
if (intent) { retryPublish.value = { ...intent, requestId: result.requestId }; await publish(); }
|
|
2013
|
+
else message.value = 'Verified. Reload account status from the backend.';
|
|
2014
|
+
}
|
|
2015
|
+
onMounted(async () => {
|
|
2016
|
+
try {
|
|
2017
|
+
const value = await api('/api/session');
|
|
2018
|
+
if (value.authenticated !== true || typeof value.csrf !== 'string' || !value.csrf) {
|
|
2019
|
+
throw new Error('LOGIN_REQUIRED');
|
|
2020
|
+
}
|
|
2021
|
+
session.value = value;
|
|
2022
|
+
} catch (error) { if (!lifetime.signal.aborted) showError(error as Error); }
|
|
2023
|
+
});
|
|
2024
|
+
onUnmounted(() => { lifetime.abort(); closeTicket(); creation = null; retryPublish.value = null; });
|
|
2025
|
+
</script>
|
|
2026
|
+
|
|
2027
|
+
<template>
|
|
2028
|
+
<button :disabled="busy || !!ticket || !session?.authenticated" @click="start('bind')">Bind phone</button>
|
|
2029
|
+
<button :disabled="busy || !!ticket || !session?.authenticated" @click="start('confirm')">Confirm</button>
|
|
2030
|
+
<button v-if="post" :disabled="busy || !!ticket || !session?.authenticated" @click="start('confirm', post)">Confirm publication</button>
|
|
2031
|
+
<button v-if="retryPublish" :disabled="busy || !!ticket" @click="publish">Retry the same publication</button>
|
|
2032
|
+
<AuthLinkBind v-if="ticket?.purpose === 'bind'" :ticket="ticket" :client="client" variant="B"
|
|
2033
|
+
@confirmed="confirmed" @close="finish('Closed')" @rejected="finish('Rejected')"
|
|
2034
|
+
@expired="finish('Expired; start a new request')" @error="showError" />
|
|
2035
|
+
<AuthLinkConfirm v-else-if="ticket?.purpose === 'confirm'" :ticket="ticket" :client="client" variant="B"
|
|
2036
|
+
@confirmed="confirmed" @close="finish('Closed')" @rejected="finish('Rejected')"
|
|
2037
|
+
@expired="finish('Expired; start a new request')" @error="showError" />
|
|
2038
|
+
<p role="status">{{ message }}</p>
|
|
2039
|
+
</template>
|
|
2040
|
+
```
|
|
2041
|
+
|
|
2042
|
+
client.create が送るのは purpose のみです。postId/version が必要なら業務 API に fetch で送り、`validateTicket(response, 'confirm', authLinkOrigin)` で検証した後、監視には公式 client を使います。同じ作成の失敗ではキーを保持し、用途・記事・版が変わったときだけ新規キーにします。ticket は shallowRef、client は markRaw で保持します。
|
|
2043
|
+
|
|
2044
|
+
マウント時は既存要求を監視し、mounted/watch で新規作成しません。閉じる・拒否・期限切れでは ticket を消去し、通信エラーでは同じ要求を再試行できるよう表示を維持します。confirmed 後は表示を閉じ、独立した公開 API を呼びます。失敗時は同じ requestId/記事/版で再試行し、実状態をバックエンドから再取得します。サイト自身のログインフォーム・記事一覧・エラー翻訳は例から省略しています。
|
|
2045
|
+
|
|
2046
|
+
#### 6. 公開トランザクションで再検証
|
|
2047
|
+
|
|
2048
|
+
ブラウザーの confirmed イベントは許可証ではありません。Go は現在の session の保存済み確認結果を読み、purpose=confirm、intent=publish、記事の所有者、同一 postId/version、下書き状態、初回適用時の有効期限を検証します。記事更新と applied の記録を一括コミットします。同じ適用済み操作の再試行は重複更新・監査なしで成功を返します。別記事や編集後の版には新たな確認が必要です。AuthLink 確認結果に action、transactionHash、記事本文を追加しません。
|
|
2049
|
+
|
|
2050
|
+
#### 検証順序
|
|
2051
|
+
|
|
2052
|
+
サイトログイン → session → バックエンド AccountStatus(参照 CMS は overview 経由)→ 未登録なら bind → スマートフォンで承認 → 消費と状態再取得 → 下書き保存 → 記事/版の confirm → 承認 → 確認結果保存 → 公開 → 再試行・異なる版・拒否・期限切れ。実端末での承認は利用者が行い、コンパイルや模擬 HTTP 検証とは区別します。
|