@pikku/core 0.12.90 → 0.12.91
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 +21 -0
- package/dist/services/http-personas.d.ts +21 -7
- package/dist/services/http-personas.js +31 -28
- package/dist/services/persona-sign-in.d.ts +107 -0
- package/dist/services/persona-sign-in.js +179 -0
- package/dist/wirings/persona/index.d.ts +1 -0
- package/dist/wirings/persona/index.js +1 -0
- package/dist/wirings/workflow/scenario-cookie-jar.js +10 -1
- package/package.json +1 -1
- package/src/public-surface.json +4 -0
- package/src/services/http-personas.ts +52 -33
- package/src/services/persona-sign-in.test.ts +209 -0
- package/src/services/persona-sign-in.ts +284 -0
- package/src/wirings/persona/index.ts +9 -0
- package/src/wirings/workflow/scenario-cookie-jar.ts +12 -1
- package/tsconfig.tsbuildinfo +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,24 @@
|
|
|
1
|
+
## 0.12.91
|
|
2
|
+
|
|
3
|
+
### Patch Changes
|
|
4
|
+
|
|
5
|
+
- 09aff02: Let personas run against a deployed stage.
|
|
6
|
+
|
|
7
|
+
A persona could only ever sign in through the actor plugin, which is
|
|
8
|
+
passwordless and therefore a local-development mechanism — so the scenario
|
|
9
|
+
suite had no way to reach staging or production, including the parts of it
|
|
10
|
+
that never assert anything about a logged-in user.
|
|
11
|
+
|
|
12
|
+
`HttpPersonasConfig` now takes `operator` as an alternative to `secret`. Given
|
|
13
|
+
Fabric operator credentials, a persona signs in at `/auth/sign-in/fabric` and
|
|
14
|
+
acts as its account through the `x-pikku-impersonate-user-id` header, which is
|
|
15
|
+
gated on the umbrella `admin` scope rather than `user.role`. Nothing on the
|
|
16
|
+
deployed side holds a test credential: the stage verifies operator tokens and
|
|
17
|
+
cannot mint them.
|
|
18
|
+
|
|
19
|
+
Provisioning stays opt-in (`createMissing`), so pointing a run at a live
|
|
20
|
+
environment never quietly writes user rows into it.
|
|
21
|
+
|
|
1
22
|
## 0.12.90
|
|
2
23
|
|
|
3
24
|
### Patch Changes
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ScenarioPersona, ResolvedPersona, ScenarioPersonas, ScenarioInvokeOptions, ScenarioHttpResponse } from './personas-service.js';
|
|
2
2
|
import type { ConverseOptions, ActorFlowVerdict } from '../wirings/actor-flow/actor-flow.types.js';
|
|
3
|
+
import { type OperatorSignInOptions } from './persona-sign-in.js';
|
|
3
4
|
export interface HttpPersonasConfig {
|
|
4
5
|
/**
|
|
5
6
|
* Base API URL of the target app, INCLUDING the HTTP prefix — e.g.
|
|
@@ -11,8 +12,19 @@ export interface HttpPersonasConfig {
|
|
|
11
12
|
/**
|
|
12
13
|
* The impersonation secret. Sign-in only ever works for user rows flagged
|
|
13
14
|
* `actor: true` — knowing the secret never impersonates real users.
|
|
15
|
+
*
|
|
16
|
+
* The local-development credential. A deployed stage has none, and passes
|
|
17
|
+
* {@link HttpPersonasConfig.operator} instead.
|
|
18
|
+
*/
|
|
19
|
+
secret?: string;
|
|
20
|
+
/**
|
|
21
|
+
* Fabric operator credentials, for signing personas into a DEPLOYED stage.
|
|
22
|
+
*
|
|
23
|
+
* Mutually exclusive with {@link HttpPersonasConfig.secret}: the operator
|
|
24
|
+
* path acts as the persona through an admin session rather than logging in as
|
|
25
|
+
* them, so no test credential has to exist on the target at all.
|
|
14
26
|
*/
|
|
15
|
-
|
|
27
|
+
operator?: OperatorSignInOptions;
|
|
16
28
|
/** Persona id → the declaration with its address filled in. */
|
|
17
29
|
personas: Record<string, ResolvedPersona>;
|
|
18
30
|
/** Sign-in path under apiUrl. Default: the actor plugin's `/auth/sign-in/actor`. */
|
|
@@ -29,12 +41,13 @@ export interface HttpPersonasConfig {
|
|
|
29
41
|
model?: string;
|
|
30
42
|
}
|
|
31
43
|
/**
|
|
32
|
-
* Default HTTP-backed persona. Signs in lazily on first invoke
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
44
|
+
* Default HTTP-backed persona. Signs in lazily on first invoke, holds the
|
|
45
|
+
* session cookies for its lifetime, and re-logs-in once on a 401 mid-run (long
|
|
46
|
+
* health-check runs can outlive a session).
|
|
47
|
+
*
|
|
48
|
+
* How it signs in depends on the target, and the two ways are not
|
|
49
|
+
* interchangeable — see {@link ActorSignIn} for local development and
|
|
50
|
+
* {@link OperatorSignIn} for a deployed stage.
|
|
38
51
|
*/
|
|
39
52
|
export declare class HttpPersona implements ScenarioPersona {
|
|
40
53
|
readonly name: string;
|
|
@@ -48,6 +61,7 @@ export declare class HttpPersona implements ScenarioPersona {
|
|
|
48
61
|
* established.
|
|
49
62
|
*/
|
|
50
63
|
private signedIn;
|
|
64
|
+
private signIn;
|
|
51
65
|
constructor(name: string, persona: ResolvedPersona, config: HttpPersonasConfig);
|
|
52
66
|
get email(): string;
|
|
53
67
|
invoke(rpcName: string, data: unknown): Promise<unknown>;
|
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
import { readScenarioHttpResponse } from './personas-service.js';
|
|
2
2
|
import { runConversation } from '../wirings/actor-flow/run-conversation.js';
|
|
3
3
|
import { createCookieJar, } from '../wirings/workflow/scenario-cookie-jar.js';
|
|
4
|
+
import { ActorSignIn, OperatorSignIn, } from './persona-sign-in.js';
|
|
4
5
|
import { getSingletonServices } from '../pikku-state.js';
|
|
5
6
|
import { AIProviderNotConfiguredError } from '../errors/errors.js';
|
|
6
7
|
/**
|
|
7
|
-
* Default HTTP-backed persona. Signs in lazily on first invoke
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
8
|
+
* Default HTTP-backed persona. Signs in lazily on first invoke, holds the
|
|
9
|
+
* session cookies for its lifetime, and re-logs-in once on a 401 mid-run (long
|
|
10
|
+
* health-check runs can outlive a session).
|
|
11
|
+
*
|
|
12
|
+
* How it signs in depends on the target, and the two ways are not
|
|
13
|
+
* interchangeable — see {@link ActorSignIn} for local development and
|
|
14
|
+
* {@link OperatorSignIn} for a deployed stage.
|
|
13
15
|
*/
|
|
14
16
|
export class HttpPersona {
|
|
15
17
|
name;
|
|
@@ -23,11 +25,21 @@ export class HttpPersona {
|
|
|
23
25
|
* established.
|
|
24
26
|
*/
|
|
25
27
|
signedIn = false;
|
|
28
|
+
signIn;
|
|
26
29
|
constructor(name, persona, config) {
|
|
27
30
|
this.name = name;
|
|
28
31
|
this.persona = persona;
|
|
29
32
|
this.config = config;
|
|
30
33
|
this.jar = createCookieJar(config.apiUrl);
|
|
34
|
+
if (config.operator) {
|
|
35
|
+
this.signIn = new OperatorSignIn(config.apiUrl, config.operator);
|
|
36
|
+
}
|
|
37
|
+
else if (config.secret) {
|
|
38
|
+
this.signIn = new ActorSignIn(config.apiUrl, config.secret, config.signInPath ?? '/auth/sign-in/actor');
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
throw new Error(`[scenario] persona '${name}' has no way to sign in — set 'secret' for a dev target or 'operator' for a deployed one`);
|
|
42
|
+
}
|
|
31
43
|
}
|
|
32
44
|
get email() {
|
|
33
45
|
return this.persona.email;
|
|
@@ -101,7 +113,9 @@ export class HttpPersona {
|
|
|
101
113
|
await this.login();
|
|
102
114
|
}
|
|
103
115
|
const sessionPath = this.config.sessionPath ?? '/auth/get-session';
|
|
104
|
-
const res = await this.jar.fetch(`${this.config.apiUrl}${sessionPath}
|
|
116
|
+
const res = await this.jar.fetch(`${this.config.apiUrl}${sessionPath}`, {
|
|
117
|
+
headers: this.signIn.headers(),
|
|
118
|
+
});
|
|
105
119
|
if (!res.ok) {
|
|
106
120
|
return null;
|
|
107
121
|
}
|
|
@@ -154,7 +168,10 @@ export class HttpPersona {
|
|
|
154
168
|
const url = `${this.config.apiUrl}${rpcPath}/${subPath}`;
|
|
155
169
|
const send = () => this.jar.fetch(url, {
|
|
156
170
|
method: 'POST',
|
|
157
|
-
headers: {
|
|
171
|
+
headers: {
|
|
172
|
+
'content-type': 'application/json',
|
|
173
|
+
...this.signIn.headers(),
|
|
174
|
+
},
|
|
158
175
|
body: JSON.stringify(body),
|
|
159
176
|
});
|
|
160
177
|
let res = await send();
|
|
@@ -176,7 +193,11 @@ export class HttpPersona {
|
|
|
176
193
|
const rpcPath = this.config.rpcPath ?? '/rpc';
|
|
177
194
|
return this.jar.fetch(`${this.config.apiUrl}${rpcPath}/${rpcName}`, {
|
|
178
195
|
method: 'POST',
|
|
179
|
-
headers: {
|
|
196
|
+
headers: {
|
|
197
|
+
'content-type': 'application/json',
|
|
198
|
+
...this.signIn.headers(),
|
|
199
|
+
...extraHeaders,
|
|
200
|
+
},
|
|
180
201
|
body: JSON.stringify({ data }),
|
|
181
202
|
});
|
|
182
203
|
}
|
|
@@ -186,25 +207,7 @@ export class HttpPersona {
|
|
|
186
207
|
this.signedIn = false;
|
|
187
208
|
}
|
|
188
209
|
async login() {
|
|
189
|
-
|
|
190
|
-
const res = await this.jar.fetch(`${this.config.apiUrl}${signInPath}`, {
|
|
191
|
-
method: 'POST',
|
|
192
|
-
headers: { 'content-type': 'application/json' },
|
|
193
|
-
body: JSON.stringify({
|
|
194
|
-
email: this.persona.email,
|
|
195
|
-
name: this.persona.name,
|
|
196
|
-
secret: this.config.secret,
|
|
197
|
-
}),
|
|
198
|
-
});
|
|
199
|
-
if (!res.ok) {
|
|
200
|
-
const body = (await res.text().catch(() => '')).slice(0, 300);
|
|
201
|
-
throw new Error(`[scenario] persona sign-in failed for '${this.name}' (${res.status}): ${body}`);
|
|
202
|
-
}
|
|
203
|
-
// What proves a session was established is this response setting a cookie,
|
|
204
|
-
// not the jar being non-empty — the target may have set one earlier.
|
|
205
|
-
if (res.headers.getSetCookie().length === 0) {
|
|
206
|
-
throw new Error(`[scenario] persona sign-in for '${this.name}' returned no session cookie`);
|
|
207
|
-
}
|
|
210
|
+
await this.signIn.login(this.jar, this.persona);
|
|
208
211
|
this.signedIn = true;
|
|
209
212
|
}
|
|
210
213
|
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import type { ResolvedPersona } from './personas-service.js';
|
|
2
|
+
import type { ScenarioCookieJar } from '../wirings/workflow/scenario-cookie-jar.js';
|
|
3
|
+
/**
|
|
4
|
+
* The header `resolveImpersonatedSession` reads the target user id from.
|
|
5
|
+
*
|
|
6
|
+
* A wire value rather than a shared import: the reader lives in
|
|
7
|
+
* `@pikku/services-better-auth`, which depends on core, so core cannot import
|
|
8
|
+
* it back. The two agree by protocol, the way an HTTP header always does.
|
|
9
|
+
*/
|
|
10
|
+
export declare const IMPERSONATE_USER_ID_HEADER = "x-pikku-impersonate-user-id";
|
|
11
|
+
/**
|
|
12
|
+
* How a persona obtains a session on the target, and what every later request
|
|
13
|
+
* needs to carry to keep acting as them.
|
|
14
|
+
*
|
|
15
|
+
* Two answers exist because the two environments have opposite trust models,
|
|
16
|
+
* not because one is a fallback for the other. See {@link ActorSignIn} and
|
|
17
|
+
* {@link OperatorSignIn}.
|
|
18
|
+
*/
|
|
19
|
+
export interface PersonaSignIn {
|
|
20
|
+
/**
|
|
21
|
+
* Establish a session in `jar`. Throws on failure with a message naming the
|
|
22
|
+
* persona, since a run that continues unauthenticated fails later and
|
|
23
|
+
* somewhere less informative.
|
|
24
|
+
*/
|
|
25
|
+
login(jar: ScenarioCookieJar, persona: ResolvedPersona): Promise<void>;
|
|
26
|
+
/** Headers every request after `login` must carry. */
|
|
27
|
+
headers(): Record<string, string>;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Sign a persona in through the Better Auth actor plugin — the local-development
|
|
31
|
+
* path.
|
|
32
|
+
*
|
|
33
|
+
* `POST /auth/sign-in/actor` upserts an `actor: true` row and mints a session
|
|
34
|
+
* for it. Passwordless by design and refused for any row not carrying that flag,
|
|
35
|
+
* so the secret can never reach a real user's account; the plugin still declines
|
|
36
|
+
* to serve the endpoint at all outside `pikku dev`.
|
|
37
|
+
*/
|
|
38
|
+
export declare class ActorSignIn implements PersonaSignIn {
|
|
39
|
+
private readonly apiUrl;
|
|
40
|
+
private readonly secret;
|
|
41
|
+
private readonly signInPath;
|
|
42
|
+
constructor(apiUrl: string, secret: string, signInPath: string);
|
|
43
|
+
login(jar: ScenarioCookieJar, persona: ResolvedPersona): Promise<void>;
|
|
44
|
+
headers(): Record<string, string>;
|
|
45
|
+
}
|
|
46
|
+
export interface OperatorSignInOptions {
|
|
47
|
+
/**
|
|
48
|
+
* The short-lived RS256 operator token, or a function that mints one. Prefer
|
|
49
|
+
* the function: tokens expire, and a long run re-logs-in after a 401.
|
|
50
|
+
*/
|
|
51
|
+
token: string | (() => string | Promise<string>);
|
|
52
|
+
/**
|
|
53
|
+
* Create the persona's user row when the target has no account for that
|
|
54
|
+
* address.
|
|
55
|
+
*
|
|
56
|
+
* Off by default, which is the whole point of the deployed path: a persona is
|
|
57
|
+
* meant to be a real account somebody provisioned, and a test run that
|
|
58
|
+
* silently writes users into a live database is a side effect nobody asked
|
|
59
|
+
* for. Turn it on for throwaway stages.
|
|
60
|
+
*/
|
|
61
|
+
createMissing?: boolean;
|
|
62
|
+
/** Admin endpoint prefix under apiUrl. Default `/auth/admin`. */
|
|
63
|
+
adminPath?: string;
|
|
64
|
+
/** Fabric operator sign-in path under apiUrl. Default `/auth/sign-in/fabric`. */
|
|
65
|
+
signInPath?: string;
|
|
66
|
+
}
|
|
67
|
+
/** What an operator handshake yields: the session, and who to act as. */
|
|
68
|
+
export interface OperatorSessionResult {
|
|
69
|
+
/** `Set-Cookie` values the operator sign-in returned. */
|
|
70
|
+
setCookies: string[];
|
|
71
|
+
/** The target's own id for the persona, for the impersonation header. */
|
|
72
|
+
userId: string;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Establish a Fabric operator session against `apiUrl` and resolve the target's
|
|
76
|
+
* own id for `persona`, which is what the impersonation header names.
|
|
77
|
+
*
|
|
78
|
+
* Takes the fetch to use rather than making one, because the two callers need
|
|
79
|
+
* the cookies to land in different places: an HTTP persona keeps them in its
|
|
80
|
+
* jar, a browser run plants them on a Playwright context. Both need the same
|
|
81
|
+
* handshake, and it is the kind of sequence that quietly diverges once it is
|
|
82
|
+
* written twice.
|
|
83
|
+
*/
|
|
84
|
+
export declare const establishOperatorSession: (fetchImpl: typeof fetch, apiUrl: string, persona: ResolvedPersona, options: OperatorSignInOptions, extraHeaders?: Record<string, string>) => Promise<OperatorSessionResult>;
|
|
85
|
+
/**
|
|
86
|
+
* Sign a persona in on a DEPLOYED stage, by having a Fabric operator act as
|
|
87
|
+
* them — the path that needs no test credential to exist anywhere.
|
|
88
|
+
*
|
|
89
|
+
* `POST /auth/sign-in/fabric` verifies an RS256 token against the stage's
|
|
90
|
+
* `FABRIC_AUTH_PUBLIC_KEY` and mints a session for a synthetic operator row
|
|
91
|
+
* granted the umbrella `admin` scope. Impersonation is then a header on each
|
|
92
|
+
* request rather than a second session, and its gate is that scope — not
|
|
93
|
+
* `user.role`, which is why this works without touching the app's roles.
|
|
94
|
+
*
|
|
95
|
+
* Asymmetric throughout: the stage can verify an operator token and never mint
|
|
96
|
+
* one, so nothing in a deployed environment is worth stealing. That is the
|
|
97
|
+
* property the actor secret cannot have, and the reason these are two classes
|
|
98
|
+
* instead of one with a flag.
|
|
99
|
+
*/
|
|
100
|
+
export declare class OperatorSignIn implements PersonaSignIn {
|
|
101
|
+
private readonly apiUrl;
|
|
102
|
+
private readonly options;
|
|
103
|
+
private userId;
|
|
104
|
+
constructor(apiUrl: string, options: OperatorSignInOptions);
|
|
105
|
+
login(jar: ScenarioCookieJar, persona: ResolvedPersona): Promise<void>;
|
|
106
|
+
headers(): Record<string, string>;
|
|
107
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The header `resolveImpersonatedSession` reads the target user id from.
|
|
3
|
+
*
|
|
4
|
+
* A wire value rather than a shared import: the reader lives in
|
|
5
|
+
* `@pikku/services-better-auth`, which depends on core, so core cannot import
|
|
6
|
+
* it back. The two agree by protocol, the way an HTTP header always does.
|
|
7
|
+
*/
|
|
8
|
+
export const IMPERSONATE_USER_ID_HEADER = 'x-pikku-impersonate-user-id';
|
|
9
|
+
const failed = async (what, personaId, res) => {
|
|
10
|
+
const body = (await res.text().catch(() => '')).slice(0, 300);
|
|
11
|
+
return new Error(`[scenario] ${what} failed for '${personaId}' (${res.status}): ${body}`);
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Sign a persona in through the Better Auth actor plugin — the local-development
|
|
15
|
+
* path.
|
|
16
|
+
*
|
|
17
|
+
* `POST /auth/sign-in/actor` upserts an `actor: true` row and mints a session
|
|
18
|
+
* for it. Passwordless by design and refused for any row not carrying that flag,
|
|
19
|
+
* so the secret can never reach a real user's account; the plugin still declines
|
|
20
|
+
* to serve the endpoint at all outside `pikku dev`.
|
|
21
|
+
*/
|
|
22
|
+
export class ActorSignIn {
|
|
23
|
+
apiUrl;
|
|
24
|
+
secret;
|
|
25
|
+
signInPath;
|
|
26
|
+
constructor(apiUrl, secret, signInPath) {
|
|
27
|
+
this.apiUrl = apiUrl;
|
|
28
|
+
this.secret = secret;
|
|
29
|
+
this.signInPath = signInPath;
|
|
30
|
+
}
|
|
31
|
+
async login(jar, persona) {
|
|
32
|
+
const res = await jar.fetch(`${this.apiUrl}${this.signInPath}`, {
|
|
33
|
+
method: 'POST',
|
|
34
|
+
headers: { 'content-type': 'application/json' },
|
|
35
|
+
body: JSON.stringify({
|
|
36
|
+
email: persona.email,
|
|
37
|
+
name: persona.name,
|
|
38
|
+
secret: this.secret,
|
|
39
|
+
}),
|
|
40
|
+
});
|
|
41
|
+
if (!res.ok) {
|
|
42
|
+
throw await failed('persona sign-in', persona.id, res);
|
|
43
|
+
}
|
|
44
|
+
// What proves a session was established is this response setting a cookie,
|
|
45
|
+
// not the jar being non-empty — the target may have set one earlier.
|
|
46
|
+
if (res.headers.getSetCookie().length === 0) {
|
|
47
|
+
throw new Error(`[scenario] persona sign-in for '${persona.id}' returned no session cookie`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
headers() {
|
|
51
|
+
return {};
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Establish a Fabric operator session against `apiUrl` and resolve the target's
|
|
56
|
+
* own id for `persona`, which is what the impersonation header names.
|
|
57
|
+
*
|
|
58
|
+
* Takes the fetch to use rather than making one, because the two callers need
|
|
59
|
+
* the cookies to land in different places: an HTTP persona keeps them in its
|
|
60
|
+
* jar, a browser run plants them on a Playwright context. Both need the same
|
|
61
|
+
* handshake, and it is the kind of sequence that quietly diverges once it is
|
|
62
|
+
* written twice.
|
|
63
|
+
*/
|
|
64
|
+
export const establishOperatorSession = async (fetchImpl, apiUrl, persona, options, extraHeaders = {}) => {
|
|
65
|
+
const signInPath = options.signInPath ?? '/auth/sign-in/fabric';
|
|
66
|
+
const token = typeof options.token === 'function' ? await options.token() : options.token;
|
|
67
|
+
const res = await fetchImpl(`${apiUrl}${signInPath}`, {
|
|
68
|
+
method: 'POST',
|
|
69
|
+
headers: { 'content-type': 'application/json', ...extraHeaders },
|
|
70
|
+
body: JSON.stringify({ token }),
|
|
71
|
+
});
|
|
72
|
+
if (!res.ok) {
|
|
73
|
+
throw await failed('operator sign-in', persona.id, res);
|
|
74
|
+
}
|
|
75
|
+
const setCookies = res.headers.getSetCookie?.() ?? [];
|
|
76
|
+
if (setCookies.length === 0) {
|
|
77
|
+
throw new Error(`[scenario] operator sign-in for '${persona.id}' returned no session cookie`);
|
|
78
|
+
}
|
|
79
|
+
// The lookup runs on the session this handshake just established, and a
|
|
80
|
+
// plain `fetch` keeps no cookies — the browser path in particular hands the
|
|
81
|
+
// jar's contents to Playwright only after this returns. Forwarding them
|
|
82
|
+
// explicitly is what keeps the admin calls authenticated for every caller.
|
|
83
|
+
const session = setCookies
|
|
84
|
+
.map((raw) => raw.split(';')[0])
|
|
85
|
+
.filter((pair) => Boolean(pair))
|
|
86
|
+
.join('; ');
|
|
87
|
+
const userId = await resolveUserId(fetchImpl, apiUrl, persona, options, {
|
|
88
|
+
...extraHeaders,
|
|
89
|
+
cookie: session,
|
|
90
|
+
});
|
|
91
|
+
return { setCookies, userId };
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* The target's own id for this persona's address, since impersonation names a
|
|
95
|
+
* user id and a persona only knows an email.
|
|
96
|
+
*
|
|
97
|
+
* Looked up before creating, so a persona that already exists is never
|
|
98
|
+
* duplicated and the run reads as "act as this person" rather than "make one".
|
|
99
|
+
*/
|
|
100
|
+
const resolveUserId = async (fetchImpl, apiUrl, persona, options, extraHeaders) => {
|
|
101
|
+
const adminPath = options.adminPath ?? '/auth/admin';
|
|
102
|
+
const query = new URLSearchParams({
|
|
103
|
+
filterField: 'email',
|
|
104
|
+
filterValue: persona.email,
|
|
105
|
+
filterOperator: 'eq',
|
|
106
|
+
limit: '1',
|
|
107
|
+
});
|
|
108
|
+
const found = await fetchImpl(`${apiUrl}${adminPath}/list-users?${query}`, {
|
|
109
|
+
headers: { accept: 'application/json', ...extraHeaders },
|
|
110
|
+
});
|
|
111
|
+
if (!found.ok) {
|
|
112
|
+
throw await failed('persona lookup', persona.id, found);
|
|
113
|
+
}
|
|
114
|
+
const listed = (await found.json().catch(() => null));
|
|
115
|
+
const existing = listed?.users?.find((u) => u.email === persona.email);
|
|
116
|
+
if (existing?.id) {
|
|
117
|
+
return String(existing.id);
|
|
118
|
+
}
|
|
119
|
+
if (!options.createMissing) {
|
|
120
|
+
throw new Error(`[scenario] no account on the target for persona '${persona.id}' (${persona.email}) — ` +
|
|
121
|
+
'provision it, or set createMissing on the operator credentials');
|
|
122
|
+
}
|
|
123
|
+
const created = await fetchImpl(`${apiUrl}${adminPath}/create-user`, {
|
|
124
|
+
method: 'POST',
|
|
125
|
+
headers: { 'content-type': 'application/json', ...extraHeaders },
|
|
126
|
+
body: JSON.stringify({
|
|
127
|
+
email: persona.email,
|
|
128
|
+
name: persona.name,
|
|
129
|
+
// Never used and never returned: the run impersonates rather than signs
|
|
130
|
+
// in, so the account is reachable only by someone already holding an
|
|
131
|
+
// operator token. A derivable password would undo exactly that.
|
|
132
|
+
password: globalThis.crypto.randomUUID(),
|
|
133
|
+
...(persona.roles[0] ? { role: persona.roles[0] } : {}),
|
|
134
|
+
}),
|
|
135
|
+
});
|
|
136
|
+
if (!created.ok) {
|
|
137
|
+
throw await failed('persona creation', persona.id, created);
|
|
138
|
+
}
|
|
139
|
+
const body = (await created.json().catch(() => null));
|
|
140
|
+
const id = body?.user?.id;
|
|
141
|
+
if (!id) {
|
|
142
|
+
throw new Error(`[scenario] creating persona '${persona.id}' returned no user id`);
|
|
143
|
+
}
|
|
144
|
+
return String(id);
|
|
145
|
+
};
|
|
146
|
+
/**
|
|
147
|
+
* Sign a persona in on a DEPLOYED stage, by having a Fabric operator act as
|
|
148
|
+
* them — the path that needs no test credential to exist anywhere.
|
|
149
|
+
*
|
|
150
|
+
* `POST /auth/sign-in/fabric` verifies an RS256 token against the stage's
|
|
151
|
+
* `FABRIC_AUTH_PUBLIC_KEY` and mints a session for a synthetic operator row
|
|
152
|
+
* granted the umbrella `admin` scope. Impersonation is then a header on each
|
|
153
|
+
* request rather than a second session, and its gate is that scope — not
|
|
154
|
+
* `user.role`, which is why this works without touching the app's roles.
|
|
155
|
+
*
|
|
156
|
+
* Asymmetric throughout: the stage can verify an operator token and never mint
|
|
157
|
+
* one, so nothing in a deployed environment is worth stealing. That is the
|
|
158
|
+
* property the actor secret cannot have, and the reason these are two classes
|
|
159
|
+
* instead of one with a flag.
|
|
160
|
+
*/
|
|
161
|
+
export class OperatorSignIn {
|
|
162
|
+
apiUrl;
|
|
163
|
+
options;
|
|
164
|
+
userId = null;
|
|
165
|
+
constructor(apiUrl, options) {
|
|
166
|
+
this.apiUrl = apiUrl;
|
|
167
|
+
this.options = options;
|
|
168
|
+
}
|
|
169
|
+
async login(jar, persona) {
|
|
170
|
+
const { userId } = await establishOperatorSession(jar.fetch, this.apiUrl, persona, this.options);
|
|
171
|
+
this.userId = userId;
|
|
172
|
+
}
|
|
173
|
+
headers() {
|
|
174
|
+
if (!this.userId) {
|
|
175
|
+
throw new Error('[scenario] operator session has no persona to act as — login() first');
|
|
176
|
+
}
|
|
177
|
+
return { [IMPERSONATE_USER_ID_HEADER]: this.userId };
|
|
178
|
+
}
|
|
179
|
+
}
|
|
@@ -17,4 +17,5 @@ export type { CorePersona, CorePersonas, PersonaAccountMeta, PersonaDefinitions,
|
|
|
17
17
|
* Lambda deploy would load outright.
|
|
18
18
|
*/
|
|
19
19
|
export { HttpPersona, createHttpPersonas, type HttpPersonasConfig, } from '../../services/http-personas.js';
|
|
20
|
+
export { ActorSignIn, OperatorSignIn, establishOperatorSession, IMPERSONATE_USER_ID_HEADER, type PersonaSignIn, type OperatorSignInOptions, type OperatorSessionResult, } from '../../services/persona-sign-in.js';
|
|
20
21
|
export { postScenarioJson, readScenarioHttpResponse, } from '../../services/personas-service.js';
|
|
@@ -13,4 +13,5 @@ export { personaEmail, personaEmails } from './persona-email.js';
|
|
|
13
13
|
* Lambda deploy would load outright.
|
|
14
14
|
*/
|
|
15
15
|
export { HttpPersona, createHttpPersonas, } from '../../services/http-personas.js';
|
|
16
|
+
export { ActorSignIn, OperatorSignIn, establishOperatorSession, IMPERSONATE_USER_ID_HEADER, } from '../../services/persona-sign-in.js';
|
|
16
17
|
export { postScenarioJson, readScenarioHttpResponse, } from '../../services/personas-service.js';
|
|
@@ -5,8 +5,17 @@ export const createCookieJar = (apiUrl) => {
|
|
|
5
5
|
fetch: async (input, init) => {
|
|
6
6
|
const headers = new Headers(init?.headers);
|
|
7
7
|
headers.set('origin', origin);
|
|
8
|
-
|
|
8
|
+
// The caller's own cookie header wins per name: a request that already
|
|
9
|
+
// carries a session is stating which one it means, and emitting the jar's
|
|
10
|
+
// copy alongside it sends the same name twice.
|
|
9
11
|
const caller = headers.get('cookie');
|
|
12
|
+
const named = new Set((caller ?? '')
|
|
13
|
+
.split(';')
|
|
14
|
+
.map((pair) => pair.split('=')[0]?.trim())
|
|
15
|
+
.filter(Boolean));
|
|
16
|
+
const held = [...jar]
|
|
17
|
+
.filter(([name]) => !named.has(name))
|
|
18
|
+
.map(([name, value]) => `${name}=${value}`);
|
|
10
19
|
if (held.length > 0 || caller) {
|
|
11
20
|
headers.set('cookie', [caller, ...held].filter(Boolean).join('; '));
|
|
12
21
|
}
|
package/package.json
CHANGED
package/src/public-surface.json
CHANGED
|
@@ -272,9 +272,13 @@
|
|
|
272
272
|
"validateAndBuildSystemRoleDefinitionsMeta"
|
|
273
273
|
],
|
|
274
274
|
"./persona": [
|
|
275
|
+
"ActorSignIn",
|
|
275
276
|
"HttpPersona",
|
|
277
|
+
"IMPERSONATE_USER_ID_HEADER",
|
|
278
|
+
"OperatorSignIn",
|
|
276
279
|
"createHttpPersonas",
|
|
277
280
|
"definePersonas",
|
|
281
|
+
"establishOperatorSession",
|
|
278
282
|
"isRunnablePersona",
|
|
279
283
|
"personaEmail",
|
|
280
284
|
"personaEmails",
|