@pikku/core 0.12.90 → 0.12.92

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.
@@ -0,0 +1,203 @@
1
+ import { describe, test, after } from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { createServer, type Server } from 'node:http'
4
+
5
+ import { createHttpPersonas } from './http-personas.js'
6
+ import { establishOperatorSession } from './persona-sign-in.js'
7
+
8
+ const OPERATOR_TOKEN = 'operator.jwt.token'
9
+
10
+ /**
11
+ * Minimal deployed stage: the fabric plugin's sign-in, which resolves the
12
+ * account to act as in the same request, and an RPC route that reports back who
13
+ * it was addressed as.
14
+ */
15
+ const startStage = async (seeded: Array<{ id: string; email: string }>) => {
16
+ const users = [...seeded]
17
+ let created = 0
18
+ const server: Server = createServer((req, res) => {
19
+ const chunks: Buffer[] = []
20
+ req.on('data', (c) => chunks.push(c))
21
+ req.on('end', () => {
22
+ const body = chunks.length
23
+ ? JSON.parse(Buffer.concat(chunks).toString())
24
+ : {}
25
+ const url = new URL(req.url ?? '/', 'http://stage.invalid')
26
+
27
+ if (url.pathname === '/api/auth/sign-in/fabric') {
28
+ if (body.token !== OPERATOR_TOKEN) {
29
+ res.writeHead(401).end(JSON.stringify({ message: 'bad token' }))
30
+ return
31
+ }
32
+ let actAs: { userId: string } | undefined
33
+ if (body.actAs) {
34
+ let user = users.find((u) => u.email === body.actAs.email)
35
+ if (!user) {
36
+ if (!body.actAs.create) {
37
+ res
38
+ .writeHead(404)
39
+ .end(
40
+ JSON.stringify({
41
+ message: `No account on this stage for ${body.actAs.email}`,
42
+ })
43
+ )
44
+ return
45
+ }
46
+ created++
47
+ user = { id: `made-${created}`, email: body.actAs.email }
48
+ users.push(user)
49
+ }
50
+ actAs = { userId: user.id }
51
+ }
52
+ res.setHeader('set-cookie', ['session=operator; Path=/; HttpOnly'])
53
+ res
54
+ .writeHead(200, { 'content-type': 'application/json' })
55
+ .end(JSON.stringify({ token: 'operator', actAs }))
56
+ return
57
+ }
58
+
59
+ if (url.pathname.startsWith('/api/rpc/')) {
60
+ res.writeHead(200, { 'content-type': 'application/json' }).end(
61
+ JSON.stringify({
62
+ actingAs: req.headers['x-pikku-impersonate-user-id'] ?? null,
63
+ cookie: req.headers.cookie ?? '',
64
+ })
65
+ )
66
+ return
67
+ }
68
+
69
+ res.writeHead(404).end()
70
+ })
71
+ })
72
+ await new Promise<void>((resolve) => server.listen(0, resolve))
73
+ const port = (server.address() as { port: number }).port
74
+ return {
75
+ apiUrl: `http://127.0.0.1:${port}/api`,
76
+ server,
77
+ get createdCount() {
78
+ return created
79
+ },
80
+ }
81
+ }
82
+
83
+ const persona = (email: string) => ({
84
+ id: 'customer',
85
+ name: 'Customer',
86
+ email,
87
+ roles: ['client'],
88
+ goals: [],
89
+ tags: [],
90
+ runnable: true,
91
+ })
92
+
93
+ describe('operator persona sign-in', () => {
94
+ const servers: Server[] = []
95
+ after(() => servers.forEach((s) => s.close()))
96
+
97
+ test('acts as an existing account rather than signing in as it', async () => {
98
+ const stage = await startStage([
99
+ { id: 'user-7', email: 'customer@personas.invalid' },
100
+ ])
101
+ servers.push(stage.server)
102
+
103
+ const personas = createHttpPersonas({
104
+ apiUrl: stage.apiUrl,
105
+ operator: { token: OPERATOR_TOKEN },
106
+ personas: { customer: persona('customer@personas.invalid') },
107
+ })
108
+
109
+ const result = (await personas.customer!.invoke('whoami', {})) as {
110
+ actingAs: string | null
111
+ cookie: string
112
+ }
113
+ assert.equal(result.actingAs, 'user-7')
114
+ assert.match(result.cookie, /session=operator/)
115
+ assert.equal(stage.createdCount, 0)
116
+ })
117
+
118
+ test('refuses a persona the stage has no account for', async () => {
119
+ const stage = await startStage([])
120
+ servers.push(stage.server)
121
+
122
+ const personas = createHttpPersonas({
123
+ apiUrl: stage.apiUrl,
124
+ operator: { token: OPERATOR_TOKEN },
125
+ personas: { customer: persona('ghost@personas.invalid') },
126
+ })
127
+
128
+ await assert.rejects(
129
+ () => personas.customer!.invoke('whoami', {}),
130
+ /operator sign-in failed for 'customer' \(404\)/
131
+ )
132
+ assert.equal(stage.createdCount, 0)
133
+ })
134
+
135
+ test('provisions the account only when told to', async () => {
136
+ const stage = await startStage([])
137
+ servers.push(stage.server)
138
+
139
+ const personas = createHttpPersonas({
140
+ apiUrl: stage.apiUrl,
141
+ operator: { token: OPERATOR_TOKEN, createMissing: true },
142
+ personas: { customer: persona('fresh@personas.invalid') },
143
+ })
144
+
145
+ const result = (await personas.customer!.invoke('whoami', {})) as {
146
+ actingAs: string | null
147
+ }
148
+ assert.equal(result.actingAs, 'made-1')
149
+ assert.equal(stage.createdCount, 1)
150
+ })
151
+
152
+ test('mints the operator session from a token factory', async () => {
153
+ const stage = await startStage([
154
+ { id: 'user-9', email: 'lazy@personas.invalid' },
155
+ ])
156
+ servers.push(stage.server)
157
+
158
+ let minted = 0
159
+ const personas = createHttpPersonas({
160
+ apiUrl: stage.apiUrl,
161
+ operator: {
162
+ token: () => {
163
+ minted++
164
+ return OPERATOR_TOKEN
165
+ },
166
+ },
167
+ personas: { customer: persona('lazy@personas.invalid') },
168
+ })
169
+
170
+ await personas.customer!.invoke('whoami', {})
171
+ assert.equal(minted, 1)
172
+ })
173
+
174
+ test('resolves the account to act as without a second request', async () => {
175
+ const stage = await startStage([{ id: 'user-9', email: 'susan@acme.test' }])
176
+ servers.push(stage.server)
177
+
178
+ // Plain fetch keeps no cookies, which is the browser provider's situation:
179
+ // it plants them on a Playwright context only once this has returned. The
180
+ // handshake must not need a session of its own to resolve the persona.
181
+ const { userId } = await establishOperatorSession(
182
+ fetch,
183
+ stage.apiUrl,
184
+ persona('susan@acme.test'),
185
+ { token: OPERATOR_TOKEN }
186
+ )
187
+ assert.equal(userId, 'user-9')
188
+ })
189
+
190
+ test('a persona with neither credential is refused at construction', async () => {
191
+ const stage = await startStage([])
192
+ servers.push(stage.server)
193
+
194
+ assert.throws(
195
+ () =>
196
+ createHttpPersonas({
197
+ apiUrl: stage.apiUrl,
198
+ personas: { customer: persona('nobody@personas.invalid') },
199
+ }),
200
+ /has no way to sign in/
201
+ )
202
+ })
203
+ })
@@ -0,0 +1,212 @@
1
+ import type { ResolvedPersona } from './personas-service.js'
2
+ import type { ScenarioCookieJar } from '../wirings/workflow/scenario-cookie-jar.js'
3
+
4
+ /**
5
+ * The header `resolveImpersonatedSession` reads the target user id from.
6
+ *
7
+ * A wire value rather than a shared import: the reader lives in
8
+ * `@pikku/services-better-auth`, which depends on core, so core cannot import
9
+ * it back. The two agree by protocol, the way an HTTP header always does.
10
+ */
11
+ export const IMPERSONATE_USER_ID_HEADER = 'x-pikku-impersonate-user-id'
12
+
13
+ /**
14
+ * How a persona obtains a session on the target, and what every later request
15
+ * needs to carry to keep acting as them.
16
+ *
17
+ * Two answers exist because the two environments have opposite trust models,
18
+ * not because one is a fallback for the other. See {@link ActorSignIn} and
19
+ * {@link OperatorSignIn}.
20
+ */
21
+ export interface PersonaSignIn {
22
+ /**
23
+ * Establish a session in `jar`. Throws on failure with a message naming the
24
+ * persona, since a run that continues unauthenticated fails later and
25
+ * somewhere less informative.
26
+ */
27
+ login(jar: ScenarioCookieJar, persona: ResolvedPersona): Promise<void>
28
+ /** Headers every request after `login` must carry. */
29
+ headers(): Record<string, string>
30
+ }
31
+
32
+ const failed = async (
33
+ what: string,
34
+ personaId: string,
35
+ res: Response
36
+ ): Promise<Error> => {
37
+ const body = (await res.text().catch(() => '')).slice(0, 300)
38
+ return new Error(
39
+ `[scenario] ${what} failed for '${personaId}' (${res.status}): ${body}`
40
+ )
41
+ }
42
+
43
+ /**
44
+ * Sign a persona in through the Better Auth actor plugin — the local-development
45
+ * path.
46
+ *
47
+ * `POST /auth/sign-in/actor` upserts an `actor: true` row and mints a session
48
+ * for it. Passwordless by design and refused for any row not carrying that flag,
49
+ * so the secret can never reach a real user's account; the plugin still declines
50
+ * to serve the endpoint at all outside `pikku dev`.
51
+ */
52
+ export class ActorSignIn implements PersonaSignIn {
53
+ constructor(
54
+ private readonly apiUrl: string,
55
+ private readonly secret: string,
56
+ private readonly signInPath: string
57
+ ) {}
58
+
59
+ async login(jar: ScenarioCookieJar, persona: ResolvedPersona): Promise<void> {
60
+ const res = await jar.fetch(`${this.apiUrl}${this.signInPath}`, {
61
+ method: 'POST',
62
+ headers: { 'content-type': 'application/json' },
63
+ body: JSON.stringify({
64
+ email: persona.email,
65
+ name: persona.name,
66
+ secret: this.secret,
67
+ }),
68
+ })
69
+ if (!res.ok) {
70
+ throw await failed('persona sign-in', persona.id, res)
71
+ }
72
+ // What proves a session was established is this response setting a cookie,
73
+ // not the jar being non-empty — the target may have set one earlier.
74
+ if (res.headers.getSetCookie().length === 0) {
75
+ throw new Error(
76
+ `[scenario] persona sign-in for '${persona.id}' returned no session cookie`
77
+ )
78
+ }
79
+ }
80
+
81
+ headers(): Record<string, string> {
82
+ return {}
83
+ }
84
+ }
85
+
86
+ export interface OperatorSignInOptions {
87
+ /**
88
+ * The short-lived RS256 operator token, or a function that mints one. Prefer
89
+ * the function: tokens expire, and a long run re-logs-in after a 401.
90
+ */
91
+ token: string | (() => string | Promise<string>)
92
+ /**
93
+ * Create the persona's user row when the target has no account for that
94
+ * address.
95
+ *
96
+ * Off by default, which is the whole point of the deployed path: a persona is
97
+ * meant to be a real account somebody provisioned, and a test run that
98
+ * silently writes users into a live database is a side effect nobody asked
99
+ * for. Turn it on for throwaway stages.
100
+ */
101
+ createMissing?: boolean
102
+ /** Fabric operator sign-in path under apiUrl. Default `/auth/sign-in/fabric`. */
103
+ signInPath?: string
104
+ }
105
+
106
+ /** What an operator handshake yields: the session, and who to act as. */
107
+ export interface OperatorSessionResult {
108
+ /** `Set-Cookie` values the operator sign-in returned. */
109
+ setCookies: string[]
110
+ /** The target's own id for the persona, for the impersonation header. */
111
+ userId: string
112
+ }
113
+
114
+ /**
115
+ * Establish a Fabric operator session against `apiUrl` and resolve the target's
116
+ * own id for `persona`, which is what the impersonation header names.
117
+ *
118
+ * Takes the fetch to use rather than making one, because the two callers need
119
+ * the cookies to land in different places: an HTTP persona keeps them in its
120
+ * jar, a browser run plants them on a Playwright context. Both need the same
121
+ * handshake, and it is the kind of sequence that quietly diverges once it is
122
+ * written twice.
123
+ */
124
+ export const establishOperatorSession = async (
125
+ fetchImpl: typeof fetch,
126
+ apiUrl: string,
127
+ persona: ResolvedPersona,
128
+ options: OperatorSignInOptions,
129
+ extraHeaders: Record<string, string> = {}
130
+ ): Promise<OperatorSessionResult> => {
131
+ const signInPath = options.signInPath ?? '/auth/sign-in/fabric'
132
+ const token =
133
+ typeof options.token === 'function' ? await options.token() : options.token
134
+
135
+ const res = await fetchImpl(`${apiUrl}${signInPath}`, {
136
+ method: 'POST',
137
+ headers: { 'content-type': 'application/json', ...extraHeaders },
138
+ body: JSON.stringify({
139
+ token,
140
+ actAs: {
141
+ email: persona.email,
142
+ name: persona.name,
143
+ create: options.createMissing ?? false,
144
+ ...(persona.roles[0] ? { role: persona.roles[0] } : {}),
145
+ },
146
+ }),
147
+ })
148
+ if (!res.ok) {
149
+ throw await failed('operator sign-in', persona.id, res)
150
+ }
151
+ const setCookies = res.headers.getSetCookie?.() ?? []
152
+ if (setCookies.length === 0) {
153
+ throw new Error(
154
+ `[scenario] operator sign-in for '${persona.id}' returned no session cookie`
155
+ )
156
+ }
157
+
158
+ const body = (await res.json().catch(() => null)) as {
159
+ actAs?: { userId?: unknown }
160
+ } | null
161
+ const userId = body?.actAs?.userId
162
+ if (!userId) {
163
+ throw new Error(
164
+ `[scenario] operator sign-in for '${persona.id}' returned no user to act as — ` +
165
+ 'the target is running a @pikku/better-auth too old to resolve one'
166
+ )
167
+ }
168
+ return { setCookies, userId: String(userId) }
169
+ }
170
+
171
+ /**
172
+ * Sign a persona in on a DEPLOYED stage, by having a Fabric operator act as
173
+ * them — the path that needs no test credential to exist anywhere.
174
+ *
175
+ * `POST /auth/sign-in/fabric` verifies an RS256 token against the stage's
176
+ * `FABRIC_AUTH_PUBLIC_KEY` and mints a session for a synthetic operator row
177
+ * granted the umbrella `admin` scope. Impersonation is then a header on each
178
+ * request rather than a second session, and its gate is that scope — not
179
+ * `user.role`, which is why this works without touching the app's roles.
180
+ *
181
+ * Asymmetric throughout: the stage can verify an operator token and never mint
182
+ * one, so nothing in a deployed environment is worth stealing. That is the
183
+ * property the actor secret cannot have, and the reason these are two classes
184
+ * instead of one with a flag.
185
+ */
186
+ export class OperatorSignIn implements PersonaSignIn {
187
+ private userId: string | null = null
188
+
189
+ constructor(
190
+ private readonly apiUrl: string,
191
+ private readonly options: OperatorSignInOptions
192
+ ) {}
193
+
194
+ async login(jar: ScenarioCookieJar, persona: ResolvedPersona): Promise<void> {
195
+ const { userId } = await establishOperatorSession(
196
+ jar.fetch,
197
+ this.apiUrl,
198
+ persona,
199
+ this.options
200
+ )
201
+ this.userId = userId
202
+ }
203
+
204
+ headers(): Record<string, string> {
205
+ if (!this.userId) {
206
+ throw new Error(
207
+ '[scenario] operator session has no persona to act as — login() first'
208
+ )
209
+ }
210
+ return { [IMPERSONATE_USER_ID_HEADER]: this.userId }
211
+ }
212
+ }
@@ -45,6 +45,15 @@ export {
45
45
  createHttpPersonas,
46
46
  type HttpPersonasConfig,
47
47
  } from '../../services/http-personas.js'
48
+ export {
49
+ ActorSignIn,
50
+ OperatorSignIn,
51
+ establishOperatorSession,
52
+ IMPERSONATE_USER_ID_HEADER,
53
+ type PersonaSignIn,
54
+ type OperatorSignInOptions,
55
+ type OperatorSessionResult,
56
+ } from '../../services/persona-sign-in.js'
48
57
  export {
49
58
  postScenarioJson,
50
59
  readScenarioHttpResponse,
@@ -11,8 +11,19 @@ export const createCookieJar = (apiUrl: string): ScenarioCookieJar => {
11
11
  fetch: async (input, init) => {
12
12
  const headers = new Headers(init?.headers)
13
13
  headers.set('origin', origin)
14
- const held = [...jar].map(([name, value]) => `${name}=${value}`)
14
+ // The caller's own cookie header wins per name: a request that already
15
+ // carries a session is stating which one it means, and emitting the jar's
16
+ // copy alongside it sends the same name twice.
15
17
  const caller = headers.get('cookie')
18
+ const named = new Set(
19
+ (caller ?? '')
20
+ .split(';')
21
+ .map((pair) => pair.split('=')[0]?.trim())
22
+ .filter(Boolean)
23
+ )
24
+ const held = [...jar]
25
+ .filter(([name]) => !named.has(name))
26
+ .map(([name, value]) => `${name}=${value}`)
16
27
  if (held.length > 0 || caller) {
17
28
  headers.set('cookie', [caller, ...held].filter(Boolean).join('; '))
18
29
  }