@reflagged/shell 1.2.0 → 1.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/README.md CHANGED
@@ -46,9 +46,39 @@ import { loadAppConfig } from '@reflagged/shell/config'
46
46
  import { OIDC_COOKIE, loadOidcEnv } from '@reflagged/shell/auth/oidc-config'
47
47
  import { verifySessionCookie } from '@reflagged/shell/auth/oidc-cookie'
48
48
  import { refreshAccessToken } from '@reflagged/shell/auth/oidc-refresh'
49
- import { nextauthStrategy } from '@reflagged/shell/auth/nextauth-strategy'
49
+ import { nextauthStrategy, createOidcStrategy } from '@reflagged/shell/auth/nextauth-strategy'
50
50
  ```
51
51
 
52
+ ### Mapping the platform's role onto your own (`roleForNewUser`)
53
+
54
+ `nextauthStrategy` is `createOidcStrategy()` with no options — the role a
55
+ newly created account gets is `RFLGD_DEFAULT_USER_ROLE` (or `admin` for the
56
+ very first account). Call `createOidcStrategy` directly to decide that role
57
+ yourself from the platform's view of the person, using the workspace role
58
+ the platform put in the session:
59
+
60
+ ```ts
61
+ import { createOidcStrategy, type NewUserContext } from '@reflagged/shell/auth/nextauth-strategy'
62
+
63
+ function roleForNewUser({ orgRole, isFirstUser }: NewUserContext): string {
64
+ if (isFirstUser) return 'admin'
65
+ // org_role is three-valued, not two: 'owner' | 'admin' | 'member' when a
66
+ // membership row exists (both 'owner' and 'admin' administer the
67
+ // workspace), or a *platform* role — 'superadmin' | 'reflagged_admin' |
68
+ // 'tenant_admin' | 'member' — when it does not. Check for 'owner' as well
69
+ // as 'admin': the person who books an instance is always created as
70
+ // 'owner', never 'admin'.
71
+ return orgRole === 'owner' || orgRole === 'admin' ? 'workspace-admin' : 'member'
72
+ }
73
+
74
+ export const oidcStrategy = createOidcStrategy({ roleForNewUser })
75
+ ```
76
+
77
+ This callback runs only when an account is created, never on later
78
+ sign-ins — see `NewUserContext`'s doc comments in
79
+ `src/lib/auth/nextauth-strategy.ts` for the full contract, including the
80
+ `isFirstUser` branch and the `null` case for standalone operation.
81
+
52
82
  ### Per-app route files + middleware
53
83
 
54
84
  Each app keeps thin wrappers that re-export the handlers:
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@reflagged/shell",
3
- "version": "1.2.0",
3
+ "version": "1.3.1",
4
4
  "description": "Shared app shell for Reflagged services — OIDC auth, SSO, app switcher",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "files": [
8
8
  "src",
9
+ "!src/**/*.test.ts",
9
10
  "tsconfig.json",
10
11
  "README.md"
11
12
  ],
@@ -29,28 +30,30 @@
29
30
  "./components/ServiceIcon": "./src/components/ServiceIcon.tsx"
30
31
  },
31
32
  "scripts": {
32
- "typecheck": "tsc --noEmit"
33
+ "typecheck": "tsc --noEmit",
34
+ "test": "vitest run"
33
35
  },
34
36
  "dependencies": {
35
37
  "jose": "^5.10.0",
36
38
  "oauth4webapi": "^3.6.0"
37
39
  },
38
40
  "peerDependencies": {
41
+ "lucide-react": ">=0.400.0",
39
42
  "next": "^15.4.0",
40
43
  "payload": "^3.79.0",
41
44
  "react": "^19.2.0",
42
- "react-dom": "^19.2.0",
43
- "lucide-react": ">=0.400.0"
45
+ "react-dom": "^19.2.0"
44
46
  },
45
47
  "devDependencies": {
46
48
  "@types/react": "^19.2.0",
47
49
  "@types/react-dom": "^19.2.0",
50
+ "lucide-react": "^0.500.0",
48
51
  "next": "^15.4.0",
49
52
  "payload": "^3.79.0",
50
53
  "react": "^19.2.0",
51
54
  "react-dom": "^19.2.0",
52
55
  "typescript": "^5.7.0",
53
- "lucide-react": "^0.500.0"
56
+ "vitest": "^3.2.0"
54
57
  },
55
58
  "peerDependenciesMeta": {
56
59
  "lucide-react": {
@@ -5,46 +5,123 @@ import { loadAppConfig } from '../../config'
5
5
  import { OIDC_COOKIE } from './oidc-config'
6
6
  import { verifySessionCookie } from './oidc-cookie'
7
7
 
8
- export const nextauthStrategy: AuthStrategy = {
9
- name: 'rflgd-oidc',
10
- authenticate: async ({ payload, headers }) => {
11
- const secret = process.env.AUTH_SECRET
12
- if (!secret) return { user: null }
13
-
14
- const cookieHeader = headers.get('cookie') ?? ''
15
- const cookieStart = `${OIDC_COOKIE}=`
16
- const segment = cookieHeader
17
- .split(';')
18
- .map((c) => c.trim())
19
- .find((c) => c.startsWith(cookieStart))
20
- if (!segment) return { user: null }
21
-
22
- const token = segment.slice(cookieStart.length)
23
- const session = await verifySessionCookie(secret, token)
24
- if (!session?.email) return { user: null }
25
-
26
- const existing = await payload.find({
27
- collection: 'users',
28
- where: { email: { equals: session.email } },
29
- limit: 1,
30
- overrideAccess: true,
31
- })
32
-
33
- let user = existing.docs[0]
34
- if (!user) {
35
- const config = loadAppConfig()
36
- const isFirst = (await payload.count({ collection: 'users', overrideAccess: true })).totalDocs === 0
37
- user = await payload.create({
8
+ /** What the platform knows about a person signing in for the first time. */
9
+ export type NewUserContext = {
10
+ /**
11
+ * Role in the current workspace, when a membership row exists for it:
12
+ * 'owner' | 'admin' | 'member'. When no membership row exists, the
13
+ * platform substitutes a *platform* role instead — 'superadmin' |
14
+ * 'reflagged_admin' | 'tenant_admin' | 'member' — a second, unrelated
15
+ * vocabulary in the same field (rflgd-base `src/lib/oidc/provider.ts:163`,
16
+ * `org_role: orgRole ?? userRole ?? null`). Only `null` without any claims
17
+ * at all. Callers that special-case 'admin' should check 'owner' too —
18
+ * rflgd-base always creates the booking person's membership with
19
+ * 'owner', never 'admin' (`src/lib/access/service-access.ts:20` treats
20
+ * both as equally privileged).
21
+ */
22
+ orgRole: string | null
23
+ /** Role on the platform itself, null without claims. */
24
+ platformRole: string | null
25
+ email: string
26
+ /** True when this account is the first in the instance. */
27
+ isFirstUser: boolean
28
+ }
29
+
30
+ /** Maps the platform's view of a person onto one of this app's own roles. */
31
+ export type RoleForNewUser = (ctx: NewUserContext) => string
32
+
33
+ /**
34
+ * The role a newly created account receives.
35
+ *
36
+ * Without a callback this is exactly what it always was: the first account
37
+ * administers, everyone after it gets RFLGD_DEFAULT_USER_ROLE. With a
38
+ * callback the decision belongs entirely to the app, `isFirstUser` included —
39
+ * which is why it is in the context. An app that forgets that branch can end
40
+ * up with an instance that has no administrator.
41
+ *
42
+ * The return value is not checked. Which roles exist is the app's knowledge;
43
+ * an unknown value is rejected by Payload against the field configuration and
44
+ * the account is not created. That is the same path on which this package's
45
+ * own default 'user' once locked instances out.
46
+ */
47
+ export function resolveNewUserRole(
48
+ ctx: NewUserContext,
49
+ roleForNewUser?: RoleForNewUser,
50
+ ): string {
51
+ if (roleForNewUser) return roleForNewUser(ctx)
52
+ return ctx.isFirstUser ? 'admin' : loadAppConfig().defaultRole
53
+ }
54
+
55
+ /**
56
+ * Payload auth strategy for the platform's single sign-on.
57
+ *
58
+ * Creates an account on first sign-in when none exists for the address. The
59
+ * role it gets is `resolveNewUserRole`'s decision — see there.
60
+ */
61
+ export function createOidcStrategy(options?: {
62
+ roleForNewUser?: RoleForNewUser
63
+ }): AuthStrategy {
64
+ return {
65
+ name: 'rflgd-oidc',
66
+ authenticate: async ({ payload, headers }) => {
67
+ const secret = process.env.AUTH_SECRET
68
+ if (!secret) return { user: null }
69
+
70
+ const cookieHeader = headers.get('cookie') ?? ''
71
+ const cookieStart = `${OIDC_COOKIE}=`
72
+ const segment = cookieHeader
73
+ .split(';')
74
+ .map((c) => c.trim())
75
+ .find((c) => c.startsWith(cookieStart))
76
+ if (!segment) return { user: null }
77
+
78
+ const token = segment.slice(cookieStart.length)
79
+ const session = await verifySessionCookie(secret, token)
80
+ if (!session?.email) return { user: null }
81
+
82
+ const existing = await payload.find({
38
83
  collection: 'users',
39
- data: {
40
- email: session.email,
41
- password: randomBytes(32).toString('hex'),
42
- role: isFirst ? 'admin' : config.defaultRole,
43
- },
84
+ where: { email: { equals: session.email } },
85
+ limit: 1,
44
86
  overrideAccess: true,
45
87
  })
46
- }
47
88
 
48
- return { user: { ...user, collection: 'users' } }
49
- },
89
+ let user = existing.docs[0]
90
+ if (!user) {
91
+ const isFirstUser =
92
+ (await payload.count({ collection: 'users', overrideAccess: true })).totalDocs === 0
93
+ const role = resolveNewUserRole(
94
+ {
95
+ orgRole: session.orgRole ?? null,
96
+ platformRole: session.platformRole ?? null,
97
+ email: session.email,
98
+ isFirstUser,
99
+ },
100
+ options?.roleForNewUser,
101
+ )
102
+ user = await payload.create({
103
+ collection: 'users',
104
+ data: {
105
+ email: session.email,
106
+ password: randomBytes(32).toString('hex'),
107
+ // `role` comes from the environment or the app and is therefore a
108
+ // `string`. The host application narrows `users.role` to the
109
+ // options of its own collection — this package cannot know that
110
+ // type. The value is checked by Payload against the field
111
+ // configuration on write; an unknown one is rejected there.
112
+ role: role as never,
113
+ },
114
+ overrideAccess: true,
115
+ })
116
+ }
117
+
118
+ return { user: { ...user, collection: 'users' } }
119
+ },
120
+ }
50
121
  }
122
+
123
+ /**
124
+ * The strategy without options — the export every consumer used before this
125
+ * package learned about role translation. Kept so nothing has to change.
126
+ */
127
+ export const nextauthStrategy: AuthStrategy = createOidcStrategy()