@useauthio/react 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/dist/index.cjs +70 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +29 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.js +70 -11
- package/dist/index.js.map +1 -1
- package/package.json +2 -3
- package/src/provider.tsx +78 -2
- package/src/sign-in.ts +14 -7
- package/src/types.ts +29 -0
- package/src/version.ts +1 -1
- package/vendor/authio-node/LICENSE +0 -21
- package/vendor/authio-node/README.md +0 -116
- package/vendor/authio-node/dist/index.cjs +0 -230
- package/vendor/authio-node/dist/index.d.cts +0 -150
- package/vendor/authio-node/dist/index.d.ts +0 -150
- package/vendor/authio-node/dist/index.js +0 -201
- package/vendor/authio-node/package.json +0 -31
package/src/provider.tsx
CHANGED
|
@@ -128,6 +128,15 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
|
|
|
128
128
|
|
|
129
129
|
const schedulerRef = useRef<RefreshScheduler | null>(null);
|
|
130
130
|
|
|
131
|
+
// Optional in-memory refresh token. React's canonical refresh path is the
|
|
132
|
+
// same-origin BFF HttpOnly cookie (performRefresh posts with
|
|
133
|
+
// credentials: "include"). But a pure SPA completing a magic-link/passkey
|
|
134
|
+
// sign-in via handleSignInResult may receive a refresh token directly
|
|
135
|
+
// (e.g. from the callback redirect URL) with no cookie available; we hold
|
|
136
|
+
// it here, memory-only (never web-storage), and send it in the refresh
|
|
137
|
+
// body as a fallback. Mirrors @useauthio/vue's state.ts.
|
|
138
|
+
const refreshTokenRef = useRef<string | null>(null);
|
|
139
|
+
|
|
131
140
|
const [user, setUser] = useState<AuthioUser | null>(null);
|
|
132
141
|
const [status, setStatus] = useState<AuthioStatus>(
|
|
133
142
|
skipInitialRefresh ? "unauthenticated" : "loading",
|
|
@@ -148,10 +157,13 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
|
|
|
148
157
|
projectId: p.projectId,
|
|
149
158
|
path: "/v1/auth/refresh",
|
|
150
159
|
method: "POST",
|
|
151
|
-
body:
|
|
160
|
+
body: refreshTokenRef.current
|
|
161
|
+
? { refresh_token: refreshTokenRef.current }
|
|
162
|
+
: {},
|
|
152
163
|
credentials: "include",
|
|
153
164
|
fetchImpl: p.fetchImpl,
|
|
154
165
|
});
|
|
166
|
+
if (env.refresh_token) refreshTokenRef.current = env.refresh_token;
|
|
155
167
|
const token = env.access_token;
|
|
156
168
|
if (!token) {
|
|
157
169
|
p.emit({
|
|
@@ -218,6 +230,7 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
|
|
|
218
230
|
run: performRefresh,
|
|
219
231
|
onGiveUp: () => {
|
|
220
232
|
storageRef.current!.clear();
|
|
233
|
+
refreshTokenRef.current = null;
|
|
221
234
|
setAccessToken(null);
|
|
222
235
|
setUser(null);
|
|
223
236
|
setStatus("unauthenticated");
|
|
@@ -377,6 +390,7 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
|
|
|
377
390
|
// baseline anyway.
|
|
378
391
|
} finally {
|
|
379
392
|
storageRef.current!.clear();
|
|
393
|
+
refreshTokenRef.current = null;
|
|
380
394
|
schedulerRef.current?.clear();
|
|
381
395
|
setAccessToken(null);
|
|
382
396
|
setUser(null);
|
|
@@ -390,6 +404,58 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
|
|
|
390
404
|
[performRefresh],
|
|
391
405
|
);
|
|
392
406
|
|
|
407
|
+
const handleSignInResult = useCallback(
|
|
408
|
+
async (input: {
|
|
409
|
+
accessToken: string;
|
|
410
|
+
refreshToken?: string | null;
|
|
411
|
+
user?: AuthioUser | null;
|
|
412
|
+
}): Promise<void> => {
|
|
413
|
+
const p = propsRef.current;
|
|
414
|
+
const verification = await verifierRef
|
|
415
|
+
.current!(input.accessToken)
|
|
416
|
+
.catch(() => null);
|
|
417
|
+
if (!verification) {
|
|
418
|
+
p.emit({
|
|
419
|
+
kind: "token_rejected",
|
|
420
|
+
timestamp: Date.now(),
|
|
421
|
+
reason: "handoff_verification_failed",
|
|
422
|
+
});
|
|
423
|
+
// Leave the session unauthenticated and surface the rejection so
|
|
424
|
+
// the caller can show an error rather than silently swallowing it.
|
|
425
|
+
storageRef.current!.clear();
|
|
426
|
+
refreshTokenRef.current = null;
|
|
427
|
+
setAccessToken(null);
|
|
428
|
+
setUser(null);
|
|
429
|
+
setStatus("unauthenticated");
|
|
430
|
+
throw new AuthioError({
|
|
431
|
+
code: "token_rejected",
|
|
432
|
+
message: "Authio rejected the handed-off access token signature.",
|
|
433
|
+
status: 0,
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
if (input.refreshToken) refreshTokenRef.current = input.refreshToken;
|
|
437
|
+
p.emit({
|
|
438
|
+
kind: "token_verified",
|
|
439
|
+
timestamp: Date.now(),
|
|
440
|
+
subject: verification.subject,
|
|
441
|
+
});
|
|
442
|
+
storageRef.current!.set(input.accessToken);
|
|
443
|
+
setAccessToken(input.accessToken);
|
|
444
|
+
if (input.user) setUser(input.user);
|
|
445
|
+
setStatus("authenticated");
|
|
446
|
+
p.emit({
|
|
447
|
+
kind: "sign_in_completed",
|
|
448
|
+
timestamp: Date.now(),
|
|
449
|
+
method: "magic_link",
|
|
450
|
+
});
|
|
451
|
+
const exp = verification.expiresAt ?? readJwtExp(input.accessToken);
|
|
452
|
+
if (exp !== null && exp !== undefined) {
|
|
453
|
+
schedulerRef.current?.scheduleAt(exp);
|
|
454
|
+
}
|
|
455
|
+
},
|
|
456
|
+
[],
|
|
457
|
+
);
|
|
458
|
+
|
|
393
459
|
const value = useMemo<AuthioContextValue>(
|
|
394
460
|
() => ({
|
|
395
461
|
user,
|
|
@@ -399,8 +465,18 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
|
|
|
399
465
|
signIn,
|
|
400
466
|
signOut,
|
|
401
467
|
refresh,
|
|
468
|
+
handleSignInResult,
|
|
402
469
|
}),
|
|
403
|
-
[
|
|
470
|
+
[
|
|
471
|
+
user,
|
|
472
|
+
status,
|
|
473
|
+
accessToken,
|
|
474
|
+
getAccessToken,
|
|
475
|
+
signIn,
|
|
476
|
+
signOut,
|
|
477
|
+
refresh,
|
|
478
|
+
handleSignInResult,
|
|
479
|
+
],
|
|
404
480
|
);
|
|
405
481
|
|
|
406
482
|
return (
|
package/src/sign-in.ts
CHANGED
|
@@ -55,7 +55,9 @@ export async function signInWithMagicLink(
|
|
|
55
55
|
path: "/v1/auth/magic-link/send",
|
|
56
56
|
method: "POST",
|
|
57
57
|
body: {
|
|
58
|
-
|
|
58
|
+
// auth-core's magic-link send reads the recipient as `destination`
|
|
59
|
+
// (email or E.164), NOT `email`. See magiclink.go magicLinkSendReq.
|
|
60
|
+
destination: opts.email,
|
|
59
61
|
redirect_uri: opts.redirectUri,
|
|
60
62
|
},
|
|
61
63
|
signal: opts.signal,
|
|
@@ -200,17 +202,22 @@ export async function signInWithPasskey(
|
|
|
200
202
|
const assertion = credential as PublicKeyCredential & {
|
|
201
203
|
response: AuthenticatorAssertionResponse;
|
|
202
204
|
};
|
|
203
|
-
|
|
205
|
+
// auth-core's passkey login/verify expects the standard WebAuthn JSON
|
|
206
|
+
// (camelCase) wrapped under a top-level `credential` key — it parses
|
|
207
|
+
// req.Credential with go-webauthn's ParseCredentialRequestResponseBody
|
|
208
|
+
// and rejects unknown top-level fields (DisallowUnknownFields). See
|
|
209
|
+
// passkey.go passkeyLoginVerify + the P1 passkey conformance flow.
|
|
210
|
+
const webauthnCredential = {
|
|
204
211
|
id: assertion.id,
|
|
205
|
-
|
|
212
|
+
rawId: bufferToBase64Url(assertion.rawId),
|
|
206
213
|
type: assertion.type,
|
|
207
214
|
response: {
|
|
208
|
-
|
|
209
|
-
|
|
215
|
+
clientDataJSON: bufferToBase64Url(assertion.response.clientDataJSON),
|
|
216
|
+
authenticatorData: bufferToBase64Url(
|
|
210
217
|
assertion.response.authenticatorData,
|
|
211
218
|
),
|
|
212
219
|
signature: bufferToBase64Url(assertion.response.signature),
|
|
213
|
-
|
|
220
|
+
userHandle: assertion.response.userHandle
|
|
214
221
|
? bufferToBase64Url(assertion.response.userHandle)
|
|
215
222
|
: null,
|
|
216
223
|
},
|
|
@@ -221,7 +228,7 @@ export async function signInWithPasskey(
|
|
|
221
228
|
projectId: opts.projectId,
|
|
222
229
|
path: "/v1/auth/passkey/login/verify",
|
|
223
230
|
method: "POST",
|
|
224
|
-
body:
|
|
231
|
+
body: { credential: webauthnCredential },
|
|
225
232
|
credentials: "include",
|
|
226
233
|
signal: opts.signal,
|
|
227
234
|
fetchImpl: opts.fetch,
|
package/src/types.ts
CHANGED
|
@@ -58,6 +58,35 @@ export interface AuthioContextValue {
|
|
|
58
58
|
* authenticated), `false` on failure (state is unauthenticated).
|
|
59
59
|
*/
|
|
60
60
|
refresh: () => Promise<boolean>;
|
|
61
|
+
/**
|
|
62
|
+
* Hand a freshly-obtained `(accessToken, refreshToken?, user?)` triple to
|
|
63
|
+
* the SDK — e.g. after a magic-link callback redirect lands on your SPA
|
|
64
|
+
* with `?access_token=…&refresh_token=…` in the URL, or after
|
|
65
|
+
* `signInWithPasskey()` resolves. Verifies the access token against the
|
|
66
|
+
* live JWKS, adopts it into provider state (status → `authenticated`),
|
|
67
|
+
* persists it per the `storage` mode, and (re-)arms the silent-refresh
|
|
68
|
+
* scheduler.
|
|
69
|
+
*
|
|
70
|
+
* This is the client-side token-handoff a pure SPA needs when it does
|
|
71
|
+
* NOT have a same-origin BFF refresh cookie to bootstrap from. Throws
|
|
72
|
+
* `AuthioError` (code `token_rejected`) when the token fails
|
|
73
|
+
* verification; state is left `unauthenticated`.
|
|
74
|
+
*
|
|
75
|
+
* ```tsx
|
|
76
|
+
* const { handleSignInResult } = useAuthio();
|
|
77
|
+
* // on your /auth/callback page:
|
|
78
|
+
* const p = new URLSearchParams(window.location.search);
|
|
79
|
+
* const accessToken = p.get("access_token");
|
|
80
|
+
* if (accessToken) {
|
|
81
|
+
* await handleSignInResult({ accessToken, refreshToken: p.get("refresh_token") });
|
|
82
|
+
* }
|
|
83
|
+
* ```
|
|
84
|
+
*/
|
|
85
|
+
handleSignInResult: (input: {
|
|
86
|
+
accessToken: string;
|
|
87
|
+
refreshToken?: string | null;
|
|
88
|
+
user?: AuthioUser | null;
|
|
89
|
+
}) => Promise<void>;
|
|
61
90
|
}
|
|
62
91
|
|
|
63
92
|
/** Result of a single JWT verification attempt. */
|
package/src/version.ts
CHANGED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2026 Authio
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
@@ -1,116 +0,0 @@
|
|
|
1
|
-
<p align="center">
|
|
2
|
-
<picture>
|
|
3
|
-
<source media="(prefers-color-scheme: dark)" srcset=".github/logo-dark.png">
|
|
4
|
-
<img alt="Authio" src=".github/logo-light.png" width="220">
|
|
5
|
-
</picture>
|
|
6
|
-
</p>
|
|
7
|
-
|
|
8
|
-
# @useauthio/node
|
|
9
|
-
|
|
10
|
-
Server-side TypeScript SDK for Authio. Use it from any Node.js / Bun / Deno backend (Express, Fastify, Hono, NestJS, Next.js Route Handlers, ...) to verify sessions, manage users, organizations, memberships, invitations, and connections.
|
|
11
|
-
|
|
12
|
-
## Install
|
|
13
|
-
|
|
14
|
-
```bash
|
|
15
|
-
pnpm add @useauthio/node
|
|
16
|
-
# or: npm i @useauthio/node / yarn add @useauthio/node
|
|
17
|
-
```
|
|
18
|
-
|
|
19
|
-
## Quick start
|
|
20
|
-
|
|
21
|
-
```ts
|
|
22
|
-
import { Authio } from "@useauthio/node";
|
|
23
|
-
|
|
24
|
-
const authio = new Authio({ apiKey: process.env.AUTHIO_SECRET_KEY! });
|
|
25
|
-
|
|
26
|
-
export async function handler(req: Request) {
|
|
27
|
-
const session = await authio.sessions.verify(
|
|
28
|
-
req.headers.get("cookie") ?? "",
|
|
29
|
-
);
|
|
30
|
-
if (!session) return new Response("Unauthorized", { status: 401 });
|
|
31
|
-
|
|
32
|
-
// session.userId is always set; session.orgId is set only after the
|
|
33
|
-
// user has selected an organization (multi-org users may have many).
|
|
34
|
-
const memberships = await authio.users.listMemberships(session.userId);
|
|
35
|
-
return Response.json({ user: session.userId, memberships });
|
|
36
|
-
}
|
|
37
|
-
```
|
|
38
|
-
|
|
39
|
-
## Multi-org-aware
|
|
40
|
-
|
|
41
|
-
`session.orgId` represents the currently-active organization for the request. A session is *user-scoped* — `session.userId` is the same regardless of which org the user is in. To switch:
|
|
42
|
-
|
|
43
|
-
```ts
|
|
44
|
-
await authio.sessions.switchOrg(sessionId, { organizationId: "org_..." });
|
|
45
|
-
```
|
|
46
|
-
|
|
47
|
-
This mints a new session bound to a different org without re-authenticating the user.
|
|
48
|
-
|
|
49
|
-
## Refresh tokens (BFF cookie auto-renewal)
|
|
50
|
-
|
|
51
|
-
Authio mints two tokens at sign-in:
|
|
52
|
-
|
|
53
|
-
- A **short-lived access JWT** (`access_token`, ~15 min) — what your `verify()` call checks.
|
|
54
|
-
- A **long-lived refresh token** (`refresh_token`, default 30 days, capped per org-policy `refresh_window_min`) — used to mint a new access JWT silently.
|
|
55
|
-
|
|
56
|
-
A typical BFF (Next.js / Express / Hono) stashes the access token in a short-lived cookie and the refresh token in a long-lived cookie, then rotates the access cookie before it expires using `Authio.sessions.refresh`:
|
|
57
|
-
|
|
58
|
-
```ts
|
|
59
|
-
import { Authio, AuthioError } from "@useauthio/node";
|
|
60
|
-
|
|
61
|
-
const authio = new Authio({ apiKey: process.env.AUTHIO_SECRET_KEY! });
|
|
62
|
-
|
|
63
|
-
// Inside your /api/auth/refresh handler (or middleware):
|
|
64
|
-
async function silentRenew(req: Request, res: Response) {
|
|
65
|
-
try {
|
|
66
|
-
const env = await authio.sessions.refresh({
|
|
67
|
-
refreshToken: req.cookies["authio_refresh"],
|
|
68
|
-
});
|
|
69
|
-
res.cookie("authio_session", env.access_token, {
|
|
70
|
-
httpOnly: true,
|
|
71
|
-
secure: true,
|
|
72
|
-
sameSite: "none",
|
|
73
|
-
maxAge: 15 * 60 * 1000,
|
|
74
|
-
});
|
|
75
|
-
res.cookie("authio_refresh", env.refresh_token, {
|
|
76
|
-
httpOnly: true,
|
|
77
|
-
secure: true,
|
|
78
|
-
sameSite: "none",
|
|
79
|
-
maxAge: 30 * 24 * 60 * 60 * 1000,
|
|
80
|
-
});
|
|
81
|
-
} catch (err) {
|
|
82
|
-
if (err instanceof AuthioError) {
|
|
83
|
-
// Auth-core enforces three lifecycle knobs from the org-policy
|
|
84
|
-
// engine. Surface stable codes back to your caller so
|
|
85
|
-
// they can render the right "your admin requires re-auth" copy:
|
|
86
|
-
// policy_violation_session_idle — idle gap > policy
|
|
87
|
-
// policy_violation_session_absolute — session past absolute max
|
|
88
|
-
// policy_violation_session_refresh_window — past refresh window
|
|
89
|
-
// invalid_refresh_token — revoked / unknown / raced
|
|
90
|
-
res.clearCookie("authio_session");
|
|
91
|
-
res.clearCookie("authio_refresh");
|
|
92
|
-
res.redirect(`/sign-in?err=${encodeURIComponent(err.code)}`);
|
|
93
|
-
return;
|
|
94
|
-
}
|
|
95
|
-
throw err;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
```
|
|
99
|
-
|
|
100
|
-
The OLD refresh token is single-use — auth-core's rotation is atomic, so a stolen refresh can be replayed at most once. The session row's `expires_at` is also clamped to `issued_at + refresh_window_min` when an org-policy is configured, so refresh chains can never outlive the policy.
|
|
101
|
-
|
|
102
|
-
## Session lifecycle policy
|
|
103
|
-
|
|
104
|
-
Customers can configure three knobs per organization on the dashboard `/orgs/<id>/security` page:
|
|
105
|
-
|
|
106
|
-
| Knob | Meaning | Typical value |
|
|
107
|
-
|---|---|---|
|
|
108
|
-
| `session_idle_timeout_min` | Max gap from last activity before forcing re-auth | 30 (high-security) / 480 (consumer) |
|
|
109
|
-
| `session_absolute_max_min` | Absolute max session lifetime since sign-in | 1440 (24h) / 14400 (10d) |
|
|
110
|
-
| `refresh_window_min` | Cap on the rolling refresh-token chain | 720 (12h) / 10080 (7d) |
|
|
111
|
-
|
|
112
|
-
A zero value on any knob means "inherit the project default". The strictest non-zero gate wins on every refresh.
|
|
113
|
-
|
|
114
|
-
## License
|
|
115
|
-
|
|
116
|
-
MIT
|
|
@@ -1,230 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
-
var __export = (target, all) => {
|
|
7
|
-
for (var name in all)
|
|
8
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
-
};
|
|
10
|
-
var __copyProps = (to, from, except, desc) => {
|
|
11
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
-
for (let key of __getOwnPropNames(from))
|
|
13
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
-
}
|
|
16
|
-
return to;
|
|
17
|
-
};
|
|
18
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
-
|
|
20
|
-
// src/index.ts
|
|
21
|
-
var index_exports = {};
|
|
22
|
-
__export(index_exports, {
|
|
23
|
-
Authio: () => Authio,
|
|
24
|
-
AuthioError: () => AuthioError,
|
|
25
|
-
JwtVerifier: () => JwtVerifier
|
|
26
|
-
});
|
|
27
|
-
module.exports = __toCommonJS(index_exports);
|
|
28
|
-
|
|
29
|
-
// src/errors.ts
|
|
30
|
-
var AuthioError = class extends Error {
|
|
31
|
-
code;
|
|
32
|
-
status;
|
|
33
|
-
requestId;
|
|
34
|
-
constructor(opts) {
|
|
35
|
-
super(opts.message);
|
|
36
|
-
this.name = "AuthioError";
|
|
37
|
-
this.code = opts.code;
|
|
38
|
-
this.status = opts.status;
|
|
39
|
-
this.requestId = opts.requestId;
|
|
40
|
-
}
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
// src/jwks.ts
|
|
44
|
-
var import_jose = require("jose");
|
|
45
|
-
var JwtVerifier = class {
|
|
46
|
-
constructor(apiUrl, issuer, audience) {
|
|
47
|
-
this.apiUrl = apiUrl;
|
|
48
|
-
this.issuer = issuer;
|
|
49
|
-
this.audience = audience;
|
|
50
|
-
this.jwks = (0, import_jose.createRemoteJWKSet)(
|
|
51
|
-
new URL(this.apiUrl.replace(/\/$/, "") + "/v1/auth/.well-known/jwks.json"),
|
|
52
|
-
{
|
|
53
|
-
cooldownDuration: 3e4,
|
|
54
|
-
cacheMaxAge: 6e5
|
|
55
|
-
}
|
|
56
|
-
);
|
|
57
|
-
}
|
|
58
|
-
apiUrl;
|
|
59
|
-
issuer;
|
|
60
|
-
audience;
|
|
61
|
-
jwks;
|
|
62
|
-
async verify(token) {
|
|
63
|
-
const { payload } = await (0, import_jose.jwtVerify)(token, this.jwks, {
|
|
64
|
-
issuer: this.issuer,
|
|
65
|
-
audience: this.audience,
|
|
66
|
-
algorithms: ["EdDSA"]
|
|
67
|
-
});
|
|
68
|
-
if (!payload.sub) {
|
|
69
|
-
throw new Error("authio: token missing sub claim");
|
|
70
|
-
}
|
|
71
|
-
return payload;
|
|
72
|
-
}
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
// src/client.ts
|
|
76
|
-
var DEFAULT_API_URL = "https://api.authio.com";
|
|
77
|
-
var DEFAULT_ISSUER = "https://api.authio.com";
|
|
78
|
-
var DEFAULT_AUDIENCE = "authio";
|
|
79
|
-
var Authio = class {
|
|
80
|
-
constructor(options) {
|
|
81
|
-
this.options = options;
|
|
82
|
-
if (!options.apiKey) {
|
|
83
|
-
throw new Error(
|
|
84
|
-
"Authio: apiKey is required. Pass it directly or set AUTHIO_SECRET_KEY."
|
|
85
|
-
);
|
|
86
|
-
}
|
|
87
|
-
const apiUrl = options.apiUrl ?? DEFAULT_API_URL;
|
|
88
|
-
this.verifier = new JwtVerifier(
|
|
89
|
-
apiUrl,
|
|
90
|
-
options.jwtIssuer ?? DEFAULT_ISSUER,
|
|
91
|
-
options.jwtAudience ?? DEFAULT_AUDIENCE
|
|
92
|
-
);
|
|
93
|
-
this.sessions = new SessionsAPI(this, this.verifier);
|
|
94
|
-
}
|
|
95
|
-
options;
|
|
96
|
-
users = new UsersAPI(this);
|
|
97
|
-
organizations = new OrganizationsAPI(this);
|
|
98
|
-
memberships = new MembershipsAPI(this);
|
|
99
|
-
sessions;
|
|
100
|
-
verifier;
|
|
101
|
-
async request(method, path, body) {
|
|
102
|
-
const url = (this.options.apiUrl ?? DEFAULT_API_URL) + path;
|
|
103
|
-
const fetchFn = this.options.fetch ?? globalThis.fetch;
|
|
104
|
-
const res = await fetchFn(url, {
|
|
105
|
-
method,
|
|
106
|
-
headers: {
|
|
107
|
-
"content-type": "application/json",
|
|
108
|
-
"user-agent": "authio-node/0.1.0",
|
|
109
|
-
authorization: `Bearer ${this.options.apiKey}`
|
|
110
|
-
},
|
|
111
|
-
body: body ? JSON.stringify(body) : void 0
|
|
112
|
-
});
|
|
113
|
-
if (!res.ok) {
|
|
114
|
-
const data = await res.json().catch(() => ({}));
|
|
115
|
-
throw new AuthioError({
|
|
116
|
-
code: data.code ?? "request_failed",
|
|
117
|
-
message: data.message ?? `Request failed with status ${res.status}`,
|
|
118
|
-
status: res.status,
|
|
119
|
-
requestId: data.request_id
|
|
120
|
-
});
|
|
121
|
-
}
|
|
122
|
-
if (res.status === 204) return void 0;
|
|
123
|
-
return await res.json();
|
|
124
|
-
}
|
|
125
|
-
};
|
|
126
|
-
var UsersAPI = class {
|
|
127
|
-
constructor(client) {
|
|
128
|
-
this.client = client;
|
|
129
|
-
}
|
|
130
|
-
client;
|
|
131
|
-
get(userId) {
|
|
132
|
-
return this.client.request("GET", `/v1/users/${userId}`);
|
|
133
|
-
}
|
|
134
|
-
listMemberships(userId) {
|
|
135
|
-
return this.client.request(
|
|
136
|
-
"GET",
|
|
137
|
-
`/v1/users/${userId}/memberships`
|
|
138
|
-
);
|
|
139
|
-
}
|
|
140
|
-
};
|
|
141
|
-
var OrganizationsAPI = class {
|
|
142
|
-
constructor(client) {
|
|
143
|
-
this.client = client;
|
|
144
|
-
}
|
|
145
|
-
client;
|
|
146
|
-
list() {
|
|
147
|
-
return this.client.request("GET", "/v1/organizations");
|
|
148
|
-
}
|
|
149
|
-
create(input) {
|
|
150
|
-
return this.client.request("POST", "/v1/organizations", input);
|
|
151
|
-
}
|
|
152
|
-
get(orgId) {
|
|
153
|
-
return this.client.request("GET", `/v1/organizations/${orgId}`);
|
|
154
|
-
}
|
|
155
|
-
};
|
|
156
|
-
var MembershipsAPI = class {
|
|
157
|
-
constructor(client) {
|
|
158
|
-
this.client = client;
|
|
159
|
-
}
|
|
160
|
-
client;
|
|
161
|
-
listForOrganization(orgId) {
|
|
162
|
-
return this.client.request(
|
|
163
|
-
"GET",
|
|
164
|
-
`/v1/organizations/${orgId}/memberships`
|
|
165
|
-
);
|
|
166
|
-
}
|
|
167
|
-
add(orgId, input) {
|
|
168
|
-
return this.client.request(
|
|
169
|
-
"POST",
|
|
170
|
-
`/v1/organizations/${orgId}/memberships`,
|
|
171
|
-
{ user_id: input.userId, role: input.role }
|
|
172
|
-
);
|
|
173
|
-
}
|
|
174
|
-
remove(orgId, membershipId) {
|
|
175
|
-
return this.client.request(
|
|
176
|
-
"DELETE",
|
|
177
|
-
`/v1/organizations/${orgId}/memberships/${membershipId}`
|
|
178
|
-
);
|
|
179
|
-
}
|
|
180
|
-
};
|
|
181
|
-
var SessionsAPI = class {
|
|
182
|
-
constructor(client, verifier) {
|
|
183
|
-
this.client = client;
|
|
184
|
-
this.verifier = verifier;
|
|
185
|
-
}
|
|
186
|
-
client;
|
|
187
|
-
verifier;
|
|
188
|
-
/**
|
|
189
|
-
* Verify an Authio access token (JWT). Returns the typed Session, or
|
|
190
|
-
* null when the token is invalid/expired.
|
|
191
|
-
*
|
|
192
|
-
* `session.userId` is always set; `session.orgId` may be null when the
|
|
193
|
-
* user has authenticated but not yet selected an organization (multi-org
|
|
194
|
-
* users coming straight out of /v1/auth/passkey/login/verify).
|
|
195
|
-
*/
|
|
196
|
-
async verify(accessToken) {
|
|
197
|
-
if (!accessToken) return null;
|
|
198
|
-
try {
|
|
199
|
-
const claims = await this.verifier.verify(accessToken);
|
|
200
|
-
return {
|
|
201
|
-
sessionId: claims.sid ?? "",
|
|
202
|
-
userId: claims.sub,
|
|
203
|
-
orgId: claims.act_org ? claims.act_org : null,
|
|
204
|
-
role: claims.act_role ? claims.act_role : null,
|
|
205
|
-
expiresAt: claims.exp ? new Date(claims.exp * 1e3).toISOString() : (/* @__PURE__ */ new Date()).toISOString()
|
|
206
|
-
};
|
|
207
|
-
} catch {
|
|
208
|
-
return null;
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
/** Pivot a session into a different organization without re-authentication. */
|
|
212
|
-
switchOrg(_sessionId, input) {
|
|
213
|
-
return this.client.request(
|
|
214
|
-
"POST",
|
|
215
|
-
"/v1/sessions/switch-org",
|
|
216
|
-
{ organization_id: input.organizationId }
|
|
217
|
-
);
|
|
218
|
-
}
|
|
219
|
-
revoke(sessionId) {
|
|
220
|
-
return this.client.request("POST", "/v1/sessions/revoke", {
|
|
221
|
-
session_id: sessionId
|
|
222
|
-
});
|
|
223
|
-
}
|
|
224
|
-
};
|
|
225
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
226
|
-
0 && (module.exports = {
|
|
227
|
-
Authio,
|
|
228
|
-
AuthioError,
|
|
229
|
-
JwtVerifier
|
|
230
|
-
});
|