@spawn-llc/auth 0.2.1 → 0.3.1
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 +38 -0
- package/IDENTITY.md +8 -2
- package/README.md +43 -6
- package/dist/{chunk-ZIYU4K3F.js → chunk-XZJS2F5Q.js} +5 -1
- package/dist/config.d.ts +44 -1
- package/dist/config.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/nextjs/index.d.ts +56 -6
- package/dist/nextjs/index.js +13 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,43 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.1
|
|
4
|
+
|
|
5
|
+
**Fix: the `config.matcher` recommendation from 0.3.0 does not build under Next 16.** Next requires
|
|
6
|
+
`config.matcher` entries to be inline string literals it can statically parse — `export const config
|
|
7
|
+
= authProxyConfig` (an imported object) fails the build with "the exported `config` field needs to
|
|
8
|
+
be a static object". 0.3.0 shipped and documented exactly that broken pattern.
|
|
9
|
+
|
|
10
|
+
- **Removed `authProxyConfig`.** It could not be used for its only purpose. Apps paste the matcher
|
|
11
|
+
literal inline instead.
|
|
12
|
+
- **Added the `AuthMatcher` type** (`typeof AUTH_MATCHER`). Pin the inlined literal with
|
|
13
|
+
`satisfies { readonly matcher: readonly [AuthMatcher] }` so `tsc` fails if the copy ever drifts
|
|
14
|
+
from the shared `AUTH_MATCHER`. `AUTH_MATCHER` itself is unchanged.
|
|
15
|
+
- **Docs:** `proxy.ts` is now the one canonical filename (Next 16 deprecates `middleware.ts`,
|
|
16
|
+
including for apps that wrap the proxy — `safeAuthProxy` is a `proxy.ts` default export too).
|
|
17
|
+
|
|
18
|
+
## 0.3.0
|
|
19
|
+
|
|
20
|
+
**Thicken the package so apps need no local auth layer or copy-pasted wiring.** Everything the apps
|
|
21
|
+
were reaching around for now lives here, and the docs stop recommending the unsafe matcher.
|
|
22
|
+
|
|
23
|
+
- **`AUTH_MATCHER` + `authProxyConfig` (from `@spawn-llc/auth/config`).** The one hardened
|
|
24
|
+
proxy/middleware matcher, defined once instead of copy-pasted per app. It closes the "F1" bypass
|
|
25
|
+
where a dynamic API segment ending in an image extension (`PATCH /api/thing/{id}.png`) escaped the
|
|
26
|
+
gate. Use `export const config = authProxyConfig`. The README/IDENTITY examples previously showed a
|
|
27
|
+
matcher that excluded `/api` entirely and left that bypass open — fixed.
|
|
28
|
+
- **`safeAuthProxy({ onUnconfigured })` (from `@spawn-llc/auth/nextjs`).** Fails **closed** when the
|
|
29
|
+
WORKOS_* secrets are absent, delegating to an app-supplied fallback (redirect / 404 / next). Folds
|
|
30
|
+
the three different hand-rolled "unconfigured" branches (`admin`, `landing`, `sites`) into one
|
|
31
|
+
shared code path. `authProxy()` is unchanged.
|
|
32
|
+
- **`requireApiUser()` (from `@spawn-llc/auth/nextjs`).** The API-handler counterpart to
|
|
33
|
+
`requireUser()`: returns the `User`, or a `401` JSON `NextResponse` when signed out (never a
|
|
34
|
+
redirect, which a `fetch()` caller can't parse). Replaces the per-app `lib/api-auth.ts` wrappers.
|
|
35
|
+
- **`appPublicPaths(extra)` (from `@spawn-llc/auth/config`).** Shared defaults plus an app's in-code
|
|
36
|
+
public routes, so an app with app-specific public paths (a Slack webhook, a cron tick) no longer
|
|
37
|
+
needs a local config wrapper package.
|
|
38
|
+
- **Convention:** `proxy.ts` + `export default authProxy()` is canonical; use `middleware.ts` only
|
|
39
|
+
when genuinely wrapping the proxy (e.g. `safeAuthProxy`, host routing).
|
|
40
|
+
|
|
3
41
|
## 0.2.1
|
|
4
42
|
|
|
5
43
|
**Fix: the session readers now force dynamic rendering before any early return.**
|
package/IDENTITY.md
CHANGED
|
@@ -51,8 +51,14 @@ app → own /login /signup /verify /reset routes renderi
|
|
|
51
51
|
1. `pnpm add @spawn-llc/auth @spawn-llc/design-system`.
|
|
52
52
|
2. Env from the "Spawn" application: `WORKOS_API_KEY`, `WORKOS_CLIENT_ID`, `WORKOS_COOKIE_PASSWORD`,
|
|
53
53
|
`NEXT_PUBLIC_WORKOS_REDIRECT_URI=<app>/callback`; add that redirect URI in the WorkOS dashboard.
|
|
54
|
-
3. `proxy.ts`
|
|
55
|
-
|
|
54
|
+
3. `proxy.ts` (Next 16's name — `middleware.ts` is deprecated) → `export default authProxy()` plus a
|
|
55
|
+
`config` whose `matcher` is the inline hardened literal, pinned with
|
|
56
|
+
`satisfies { readonly matcher: readonly [AuthMatcher] }` (Next requires an inline literal, so it
|
|
57
|
+
can't be an imported object; the `AuthMatcher` type fails `tsc` if the copy drifts from
|
|
58
|
+
`AUTH_MATCHER`). `app/callback/route.ts` → `export const GET = handleCallback()`. If the app must
|
|
59
|
+
stay up on preview deploys with no secrets, make the `proxy.ts` default export
|
|
60
|
+
`safeAuthProxy({ onUnconfigured })`. Gate API handlers with `requireApiUser()` (401 JSON, never a
|
|
61
|
+
redirect); pages/layouts with `requireUser()`.
|
|
56
62
|
4. Build `/login`, `/signup`, `/verify`, `/reset` rendering the DS screens, wired to the headless
|
|
57
63
|
flows via `"use server"` actions.
|
|
58
64
|
5. Internal-only tool? Set `ALLOWED_EMAIL_DOMAINS=spawnpartners.com`.
|
package/README.md
CHANGED
|
@@ -23,19 +23,56 @@ internal tools), `AUTH_PUBLIC_PATHS`.
|
|
|
23
23
|
- **`@spawn-llc/auth`** — core, edge-safe: the `IdentityGateway` (orgs / members / roles / invites) +
|
|
24
24
|
`createIdentityGateway()`, domain types (`Role`, `Session`, `Member`, `Invite`), and policy
|
|
25
25
|
(`isWorkosConfigured`, `isAllowedEmail`, `isPublicPath`).
|
|
26
|
-
- **`@spawn-llc/auth/config`** — the edge-safe policy alone (import from middleware; no SDK)
|
|
26
|
+
- **`@spawn-llc/auth/config`** — the edge-safe policy alone (import from middleware; no SDK): the
|
|
27
|
+
gate + `isPublicPath` / `appPublicPaths` and the shared hardened matcher (`AUTH_MATCHER` + its
|
|
28
|
+
`AuthMatcher` literal type for pinning an app's inlined `config.matcher`).
|
|
27
29
|
- **`@spawn-llc/auth/nextjs`** — the Next server surface: the session seam
|
|
28
|
-
(`currentUser` / `requireUser` / `session` / `signOut` / `switchOrganization`),
|
|
29
|
-
`handleCallback()`, and the headless flows
|
|
30
|
-
`
|
|
30
|
+
(`currentUser` / `requireUser` / `requireApiUser` / `session` / `signOut` / `switchOrganization`),
|
|
31
|
+
`authProxy()` / `safeAuthProxy()`, `handleCallback()`, and the headless flows
|
|
32
|
+
(`signInWithPassword`, `signUp`, `verifyEmail`, `requestPasswordReset`, `resetPassword`,
|
|
33
|
+
`startOAuth`).
|
|
31
34
|
|
|
32
35
|
## Wire an app (Next.js)
|
|
33
36
|
|
|
37
|
+
Next 16 calls this file `proxy.ts` (the old `middleware.ts` name is deprecated). Next requires
|
|
38
|
+
`config.matcher` to be an **inline** string literal — a `const`/imported object fails the build — so
|
|
39
|
+
paste the matcher and pin it to the shared `AuthMatcher` type, which fails `tsc` if it ever drifts:
|
|
40
|
+
|
|
34
41
|
```ts
|
|
35
|
-
// proxy.ts (
|
|
42
|
+
// proxy.ts (refresh the session on every route; gate in-app via requireUser())
|
|
36
43
|
import { authProxy } from "@spawn-llc/auth/nextjs";
|
|
44
|
+
import type { AuthMatcher } from "@spawn-llc/auth/config";
|
|
37
45
|
export default authProxy();
|
|
38
|
-
export const config = {
|
|
46
|
+
export const config = {
|
|
47
|
+
matcher: ["/((?!_next/static|_next/image|favicon\\.ico|(?!(?:.*/)?api/).*\\.(?:svg|png|jpg|jpeg|gif|webp|ico)$).*)"],
|
|
48
|
+
} satisfies { readonly matcher: readonly [AuthMatcher] };
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Need to fail closed when the WORKOS_* secrets are absent (a preview deploy)? Keep the same `proxy.ts`
|
|
52
|
+
but wrap with `safeAuthProxy({ onUnconfigured })` as the default export:
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
// proxy.ts (fail closed when identity is unconfigured)
|
|
56
|
+
import { safeAuthProxy } from "@spawn-llc/auth/nextjs";
|
|
57
|
+
import { isPublicPath } from "@spawn-llc/auth/config";
|
|
58
|
+
import { NextResponse } from "next/server";
|
|
59
|
+
export default safeAuthProxy({
|
|
60
|
+
onUnconfigured: (req) =>
|
|
61
|
+
isPublicPath(req.nextUrl.pathname)
|
|
62
|
+
? NextResponse.next()
|
|
63
|
+
: NextResponse.redirect(new URL("/login", req.url)),
|
|
64
|
+
});
|
|
65
|
+
// (same `config` block as above)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
// app/(any)/api/route.ts — gate a route handler (401 JSON, never a redirect)
|
|
70
|
+
import { requireApiUser } from "@spawn-llc/auth/nextjs";
|
|
71
|
+
export async function GET() {
|
|
72
|
+
const user = await requireApiUser();
|
|
73
|
+
if (user instanceof Response) return user; // 401 when signed out
|
|
74
|
+
// ...use `user`
|
|
75
|
+
}
|
|
39
76
|
```
|
|
40
77
|
|
|
41
78
|
```ts
|
|
@@ -7,6 +7,10 @@ function publicPaths() {
|
|
|
7
7
|
function isPublicPath(pathname, paths = publicPaths()) {
|
|
8
8
|
return paths.some((p) => pathname === p || pathname.startsWith(`${p}/`));
|
|
9
9
|
}
|
|
10
|
+
function appPublicPaths(extra) {
|
|
11
|
+
return [...publicPaths(), ...extra];
|
|
12
|
+
}
|
|
13
|
+
var AUTH_MATCHER = "/((?!_next/static|_next/image|favicon\\.ico|(?!(?:.*/)?api/).*\\.(?:svg|png|jpg|jpeg|gif|webp|ico)$).*)";
|
|
10
14
|
function isWorkosConfigured() {
|
|
11
15
|
return Boolean(
|
|
12
16
|
process.env.WORKOS_API_KEY && (process.env.WORKOS_CLIENT_ID || process.env.NEXT_PUBLIC_WORKOS_CLIENT_ID) && process.env.WORKOS_COOKIE_PASSWORD
|
|
@@ -42,4 +46,4 @@ function workosClientId() {
|
|
|
42
46
|
return id;
|
|
43
47
|
}
|
|
44
48
|
|
|
45
|
-
export { DEFAULT_PUBLIC_PATHS, allowedEmailDomains, assertEmailDomainGate, isAllowedEmail, isPublicPath, isWorkosConfigured, publicPaths, requiresEmailDomainGate, workosClientId };
|
|
49
|
+
export { AUTH_MATCHER, DEFAULT_PUBLIC_PATHS, allowedEmailDomains, appPublicPaths, assertEmailDomainGate, isAllowedEmail, isPublicPath, isWorkosConfigured, publicPaths, requiresEmailDomainGate, workosClientId };
|
package/dist/config.d.ts
CHANGED
|
@@ -8,6 +8,49 @@ declare const DEFAULT_PUBLIC_PATHS: readonly ["/login", "/signup", "/verify", "/
|
|
|
8
8
|
/** The public paths for this app: the defaults plus anything in `AUTH_PUBLIC_PATHS` (comma-sep). */
|
|
9
9
|
declare function publicPaths(): string[];
|
|
10
10
|
declare function isPublicPath(pathname: string, paths?: string[]): boolean;
|
|
11
|
+
/**
|
|
12
|
+
* The public paths for an app that declares extra ones IN CODE (not via `AUTH_PUBLIC_PATHS`):
|
|
13
|
+
* the shared defaults plus the caller's list. Lets an app keep app-specific public routes (a
|
|
14
|
+
* Slack webhook, a cron tick, an unsubscribe link) alongside the login-flow defaults without a
|
|
15
|
+
* local wrapper package. Pair with `isPublicPath(pathname, appPublicPaths([...]))`.
|
|
16
|
+
*/
|
|
17
|
+
declare function appPublicPaths(extra: string[]): string[];
|
|
18
|
+
/**
|
|
19
|
+
* The canonical proxy/middleware matcher — the ONE hardened regex every app should use, so the
|
|
20
|
+
* pattern is defined once here instead of copy-pasted per app. Runs the session-refresh proxy on
|
|
21
|
+
* everything except Next internals and genuine static assets.
|
|
22
|
+
*
|
|
23
|
+
* The image-extension carve-out is scoped with a negative lookahead for an "api/" path segment, so
|
|
24
|
+
* it can only ever match real static files (e.g. "/favicon.svg", "/og.png") — NEVER a route whose
|
|
25
|
+
* dynamic "[id]" segment happens to end in an image extension. Without that guard,
|
|
26
|
+
* "PATCH /api/thing/{id}.png" escaped the gate entirely: the extension satisfied the exclusion, yet
|
|
27
|
+
* Next still resolved the handler and ran it unauthenticated. API routes now always hit the proxy.
|
|
28
|
+
* Apps whose routes need in-request gating still call requireUser() / requireApiUser() in the
|
|
29
|
+
* handler — the matcher refreshes the cookie, it does not protect.
|
|
30
|
+
*/
|
|
31
|
+
declare const AUTH_MATCHER = "/((?!_next/static|_next/image|favicon\\.ico|(?!(?:.*/)?api/).*\\.(?:svg|png|jpg|jpeg|gif|webp|ico)$).*)";
|
|
32
|
+
/**
|
|
33
|
+
* The literal type of {@link AUTH_MATCHER}, for pinning an app's inlined matcher to the shared
|
|
34
|
+
* source without any runtime import.
|
|
35
|
+
*
|
|
36
|
+
* Next requires `config.matcher` entries to be INLINE string literals it can statically parse at
|
|
37
|
+
* build time — a `const`/imported reference (`export const config = someObject`) fails the build
|
|
38
|
+
* with "the exported `config` field needs to be a static object". So an app cannot consume a
|
|
39
|
+
* ready-made config object; it must paste the literal. To stop that copy from silently drifting,
|
|
40
|
+
* pin it with `satisfies`:
|
|
41
|
+
*
|
|
42
|
+
* import { authProxy } from "@spawn-llc/auth/nextjs";
|
|
43
|
+
* import type { AuthMatcher } from "@spawn-llc/auth/config";
|
|
44
|
+
* export default authProxy();
|
|
45
|
+
* export const config = {
|
|
46
|
+
* matcher: [AUTH_MATCHER_LITERAL], // paste the value of AUTH_MATCHER inline (see README)
|
|
47
|
+
* } satisfies { readonly matcher: readonly [AuthMatcher] };
|
|
48
|
+
*
|
|
49
|
+
* `tsc` then fails if the pasted literal ever diverges from `AUTH_MATCHER`. The import is type-only,
|
|
50
|
+
* so nothing lands in the bundle. (The literal is spelled out in README.md / IDENTITY.md — it is
|
|
51
|
+
* omitted from this doc-comment because the regex contains a comment-terminating sequence.)
|
|
52
|
+
*/
|
|
53
|
+
type AuthMatcher = typeof AUTH_MATCHER;
|
|
11
54
|
/**
|
|
12
55
|
* WorkOS (the engine) is "configured" once its three required secrets are present. When it is NOT
|
|
13
56
|
* configured, the seam fails CLOSED (no session → redirect to sign-in) rather than letting requests
|
|
@@ -39,4 +82,4 @@ declare function isAllowedEmail(email: string | null | undefined): boolean;
|
|
|
39
82
|
/** The WorkOS client id, from either the server or the public var. */
|
|
40
83
|
declare function workosClientId(): string;
|
|
41
84
|
|
|
42
|
-
export { DEFAULT_PUBLIC_PATHS, allowedEmailDomains, assertEmailDomainGate, isAllowedEmail, isPublicPath, isWorkosConfigured, publicPaths, requiresEmailDomainGate, workosClientId };
|
|
85
|
+
export { AUTH_MATCHER, type AuthMatcher, DEFAULT_PUBLIC_PATHS, allowedEmailDomains, appPublicPaths, assertEmailDomainGate, isAllowedEmail, isPublicPath, isWorkosConfigured, publicPaths, requiresEmailDomainGate, workosClientId };
|
package/dist/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { DEFAULT_PUBLIC_PATHS, allowedEmailDomains, assertEmailDomainGate, isAllowedEmail, isPublicPath, isWorkosConfigured, publicPaths, requiresEmailDomainGate, workosClientId } from './chunk-
|
|
1
|
+
export { AUTH_MATCHER, DEFAULT_PUBLIC_PATHS, allowedEmailDomains, appPublicPaths, assertEmailDomainGate, isAllowedEmail, isPublicPath, isWorkosConfigured, publicPaths, requiresEmailDomainGate, workosClientId } from './chunk-XZJS2F5Q.js';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { R as Role } from './domain-CmEhGW2N.js';
|
|
2
2
|
export { I as Invite, M as Member, O as OrgMembership, S as Session, U as User } from './domain-CmEhGW2N.js';
|
|
3
|
-
export { DEFAULT_PUBLIC_PATHS, allowedEmailDomains, isAllowedEmail, isPublicPath, isWorkosConfigured, publicPaths, workosClientId } from './config.js';
|
|
3
|
+
export { AUTH_MATCHER, AuthMatcher, DEFAULT_PUBLIC_PATHS, allowedEmailDomains, appPublicPaths, isAllowedEmail, isPublicPath, isWorkosConfigured, publicPaths, workosClientId } from './config.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* The identity/tenancy port. WorkOS owns organizations, memberships (+ roles) and invitations; this
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { DEFAULT_PUBLIC_PATHS, allowedEmailDomains, isAllowedEmail, isPublicPath, isWorkosConfigured, publicPaths, workosClientId } from './chunk-
|
|
1
|
+
export { AUTH_MATCHER, DEFAULT_PUBLIC_PATHS, allowedEmailDomains, appPublicPaths, isAllowedEmail, isPublicPath, isWorkosConfigured, publicPaths, workosClientId } from './chunk-XZJS2F5Q.js';
|
|
2
2
|
|
|
3
3
|
// src/identity/workos-gateway.ts
|
|
4
4
|
var ROLES = ["owner", "admin", "member"];
|
package/dist/nextjs/index.d.ts
CHANGED
|
@@ -1,10 +1,27 @@
|
|
|
1
|
-
import { U as User, S as Session } from '../domain-CmEhGW2N.js';
|
|
2
1
|
import * as next_server from 'next/server';
|
|
2
|
+
import { NextResponse, NextMiddleware, NextRequest, NextFetchEvent } from 'next/server';
|
|
3
|
+
import { U as User, S as Session } from '../domain-CmEhGW2N.js';
|
|
4
|
+
export { AUTH_MATCHER, AuthMatcher } from '../config.js';
|
|
3
5
|
|
|
4
6
|
/** The signed-in Spawn user, or null. Applies the optional email-domain gate. */
|
|
5
7
|
declare function currentUser(): Promise<User | null>;
|
|
6
8
|
/** The signed-in user; redirects to `/login` when absent. */
|
|
7
9
|
declare function requireUser(redirectTo?: string): Promise<User>;
|
|
10
|
+
/**
|
|
11
|
+
* The API-route counterpart to `requireUser()`. Returns the signed-in `User`, or a `401` JSON
|
|
12
|
+
* `NextResponse` when there is no valid session.
|
|
13
|
+
*
|
|
14
|
+
* Why not just `requireUser()` in an API handler: `requireUser()` redirects to `/login`, which is
|
|
15
|
+
* right for a browser navigation but wrong for a `fetch()` — the caller gets a `200` HTML login
|
|
16
|
+
* page and a JSON parse error instead of a clean `401`. Route handlers should branch on the type:
|
|
17
|
+
*
|
|
18
|
+
* const user = await requireApiUser();
|
|
19
|
+
* if (user instanceof NextResponse) return user; // 401
|
|
20
|
+
* // ...use `user`
|
|
21
|
+
*
|
|
22
|
+
* Applies the same email-domain gate + dynamic-render marking as `currentUser()`.
|
|
23
|
+
*/
|
|
24
|
+
declare function requireApiUser(): Promise<User | NextResponse>;
|
|
8
25
|
/** The full Spawn session (user + active org + role), or null. */
|
|
9
26
|
declare function session(): Promise<Session | null>;
|
|
10
27
|
/** The signed-in email BEFORE the domain gate, if any — lets a login page show a wrong-domain denial. */
|
|
@@ -20,10 +37,13 @@ declare function userDisplayName(user: User): string;
|
|
|
20
37
|
* The app middleware/proxy. Because Spawn renders its OWN auth screens (headless), this only
|
|
21
38
|
* **refreshes** the WorkOS session cookie on each request — it does NOT redirect to any hosted page.
|
|
22
39
|
* Route protection is done in-app: authed layouts call `requireUser()`, which redirects
|
|
23
|
-
* unauthenticated visitors to `/login` (a Spawn screen). Use as the app's `proxy.ts` default export
|
|
40
|
+
* unauthenticated visitors to `/login` (a Spawn screen). Use as the app's `proxy.ts` default export
|
|
41
|
+
* (Next 16's name; `middleware.ts` is deprecated). Next requires `config.matcher` to be an inline
|
|
42
|
+
* string literal, so paste the matcher and pin it to the shared `AuthMatcher` type — see
|
|
43
|
+
* {@link AuthMatcher} in `../config` for the exact snippet.
|
|
24
44
|
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
45
|
+
* When an app needs its own fail-closed behavior for the WORKOS-unconfigured case (a preview deploy
|
|
46
|
+
* with no secrets), wrap with `safeAuthProxy` — still from `proxy.ts`.
|
|
27
47
|
*
|
|
28
48
|
* Pass `{ enforce: true }` only if you want middleware-level gating to WorkOS's hosted UI instead
|
|
29
49
|
* of your own screens (not the Spawn default).
|
|
@@ -43,7 +63,37 @@ declare function userDisplayName(user: User): string;
|
|
|
43
63
|
declare function authProxy(options?: {
|
|
44
64
|
enforce?: boolean;
|
|
45
65
|
unauthenticatedPaths?: string[];
|
|
46
|
-
}):
|
|
66
|
+
}): NextMiddleware;
|
|
67
|
+
/**
|
|
68
|
+
* `authProxy()`, but fail CLOSED when WorkOS is not configured.
|
|
69
|
+
*
|
|
70
|
+
* `authProxy()` assumes the WORKOS_* secrets are present; a build/preview deploy without them would
|
|
71
|
+
* otherwise refresh nothing and let every request through. Rather than each app hand-rolling that
|
|
72
|
+
* guard three different ways (redirect / 404 / boot-assert), `safeAuthProxy` owns the plumbing:
|
|
73
|
+
* when identity is configured it delegates to `authProxy(options)`; when it is NOT, it calls the
|
|
74
|
+
* app-supplied `onUnconfigured` handler so the app keeps its own fallback (redirect to `/login`,
|
|
75
|
+
* 404 the gated area, `NextResponse.next()` for a public-only preview, …).
|
|
76
|
+
*
|
|
77
|
+
* // proxy.ts
|
|
78
|
+
* import { safeAuthProxy } from "@spawn-llc/auth/nextjs";
|
|
79
|
+
* import { isPublicPath } from "@spawn-llc/auth/config";
|
|
80
|
+
* import { NextResponse } from "next/server";
|
|
81
|
+
* export default safeAuthProxy({
|
|
82
|
+
* onUnconfigured: (req) =>
|
|
83
|
+
* isPublicPath(req.nextUrl.pathname)
|
|
84
|
+
* ? NextResponse.next()
|
|
85
|
+
* : NextResponse.redirect(new URL("/login", req.url)),
|
|
86
|
+
* });
|
|
87
|
+
* // export const config = { matcher: [...] } satisfies { readonly matcher: readonly [AuthMatcher] }
|
|
88
|
+
*
|
|
89
|
+
* The configured/unconfigured decision is made ONCE, when the middleware is constructed (module
|
|
90
|
+
* load) — identity config does not change between requests within a running process.
|
|
91
|
+
*/
|
|
92
|
+
declare function safeAuthProxy(options: {
|
|
93
|
+
onUnconfigured: (request: NextRequest, event: NextFetchEvent) => ReturnType<NextMiddleware>;
|
|
94
|
+
enforce?: boolean;
|
|
95
|
+
unauthenticatedPaths?: string[];
|
|
96
|
+
}): NextMiddleware;
|
|
47
97
|
|
|
48
98
|
/**
|
|
49
99
|
* The OAuth callback handler for the app's `/callback` route:
|
|
@@ -133,4 +183,4 @@ declare function startOAuth(input: {
|
|
|
133
183
|
redirectUri?: string;
|
|
134
184
|
}): Promise<string>;
|
|
135
185
|
|
|
136
|
-
export { type FlowResult, type OAuthProvider, authProxy, currentUser, handleCallback, rejectedEmail, requestPasswordReset, requireUser, resetPassword, session, signInWithPassword, signOut, signUp, startOAuth, switchOrganization, userDisplayName, verifyEmail };
|
|
186
|
+
export { type FlowResult, type OAuthProvider, authProxy, currentUser, handleCallback, rejectedEmail, requestPasswordReset, requireApiUser, requireUser, resetPassword, safeAuthProxy, session, signInWithPassword, signOut, signUp, startOAuth, switchOrganization, userDisplayName, verifyEmail };
|
package/dist/nextjs/index.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import { isWorkosConfigured, isAllowedEmail, publicPaths, workosClientId } from '../chunk-
|
|
1
|
+
import { isWorkosConfigured, isAllowedEmail, publicPaths, workosClientId } from '../chunk-XZJS2F5Q.js';
|
|
2
|
+
export { AUTH_MATCHER } from '../chunk-XZJS2F5Q.js';
|
|
2
3
|
import { headers, cookies } from 'next/headers';
|
|
3
4
|
import { redirect } from 'next/navigation';
|
|
5
|
+
import { NextResponse } from 'next/server';
|
|
4
6
|
import { authkitMiddleware, handleAuth, getWorkOS, saveSession } from '@workos-inc/authkit-nextjs';
|
|
5
7
|
|
|
6
8
|
async function markDynamic() {
|
|
@@ -19,6 +21,11 @@ async function requireUser(redirectTo = "/login") {
|
|
|
19
21
|
if (!user) redirect(redirectTo);
|
|
20
22
|
return user;
|
|
21
23
|
}
|
|
24
|
+
async function requireApiUser() {
|
|
25
|
+
const user = await currentUser();
|
|
26
|
+
if (user) return user;
|
|
27
|
+
return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
|
|
28
|
+
}
|
|
22
29
|
async function session() {
|
|
23
30
|
await markDynamic();
|
|
24
31
|
if (!isWorkosConfigured()) return null;
|
|
@@ -68,6 +75,10 @@ function authProxy(options) {
|
|
|
68
75
|
}
|
|
69
76
|
return authkitMiddleware();
|
|
70
77
|
}
|
|
78
|
+
function safeAuthProxy(options) {
|
|
79
|
+
const proxy = isWorkosConfigured() ? authProxy({ enforce: options.enforce, unauthenticatedPaths: options.unauthenticatedPaths }) : null;
|
|
80
|
+
return (request, event) => proxy ? proxy(request, event) : options.onUnconfigured(request, event);
|
|
81
|
+
}
|
|
71
82
|
function handleCallback(options) {
|
|
72
83
|
return handleAuth({ returnPathname: options?.returnPathname ?? "/" });
|
|
73
84
|
}
|
|
@@ -266,4 +277,4 @@ async function startOAuth(input) {
|
|
|
266
277
|
});
|
|
267
278
|
}
|
|
268
279
|
|
|
269
|
-
export { authProxy, currentUser, handleCallback, rejectedEmail, requestPasswordReset, requireUser, resetPassword, session, signInWithPassword, signOut, signUp, startOAuth, switchOrganization, userDisplayName, verifyEmail };
|
|
280
|
+
export { authProxy, currentUser, handleCallback, rejectedEmail, requestPasswordReset, requireApiUser, requireUser, resetPassword, safeAuthProxy, session, signInWithPassword, signOut, signUp, startOAuth, switchOrganization, userDisplayName, verifyEmail };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spawn-llc/auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "Spawn shared identity — headless auth for the whole Spawn suite. One WorkOS project (named \"Spawn\") backs every app; this is the only place that touches it. WorkOS is an invisible engine.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|