@steve31415/baselib 3.66.0 → 3.68.0
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/dist/auth.d.ts +26 -3
- package/dist/auth.js +104 -38
- package/dist/connector.d.ts +2 -1
- package/dist/connector.js +4 -6
- package/dist/db.d.ts +26 -5
- package/dist/db.js +39 -5
- package/dist/email.d.ts +22 -5
- package/dist/email.js +33 -8
- package/dist/hub/server.d.ts +3 -2
- package/dist/hub/server.js +1 -0
- package/dist/oauth-resource.d.ts +2 -2
- package/dist/oauth-resource.js +11 -6
- package/package.json +1 -1
package/dist/auth.d.ts
CHANGED
|
@@ -3,11 +3,17 @@ import { type Logger } from './log-core.js';
|
|
|
3
3
|
import { ServiceCaller, S2sOptions } from './s2s.js';
|
|
4
4
|
export declare const DEFAULT_AUTH_URL = "https://auth.apps.snewman.net";
|
|
5
5
|
export declare const SESSION_COOKIE = "pw_session";
|
|
6
|
+
/** The cookie of a guest session. Only a `guestAccess` mount ever reads it. */
|
|
7
|
+
export declare const GUEST_COOKIE = "pw_guest";
|
|
6
8
|
/** The `code` in a 403 JSON body when a signed-in user is refused by the
|
|
7
9
|
* app's userAccess policy (as opposed to any other 403). */
|
|
8
10
|
export declare const ACCESS_DENIED_CODE = "app_access_denied";
|
|
9
|
-
/** A user's fleet role, assigned in auth's users table.
|
|
10
|
-
|
|
11
|
+
/** A user's fleet role, assigned in auth's users table. A 'guest' is not a
|
|
12
|
+
* fleet user: an app that admits guests vouched for them at sign-in, and
|
|
13
|
+
* only a `guestAccess` mount ever yields one. */
|
|
14
|
+
export type UserRole = 'owner' | 'invited' | 'guest';
|
|
15
|
+
/** The roles a full (fleet) session can carry: every role but 'guest'. */
|
|
16
|
+
export type FullRole = Exclude<UserRole, 'guest'>;
|
|
11
17
|
/** Which signed-in users an app admits. 'owner' (the default): only the
|
|
12
18
|
* fleet owner(s). 'invited': any active fleet user. */
|
|
13
19
|
export type UserAccessPolicy = 'owner' | 'invited';
|
|
@@ -17,6 +23,10 @@ export interface AuthedUser {
|
|
|
17
23
|
name?: string;
|
|
18
24
|
userId?: string;
|
|
19
25
|
role: UserRole;
|
|
26
|
+
/** The Google Workspace domain the auth service verified for this session
|
|
27
|
+
* (whoami's `domain`). Absent for a personal account, and once the
|
|
28
|
+
* verification is too old for auth to report it. */
|
|
29
|
+
domain?: string;
|
|
20
30
|
}
|
|
21
31
|
export type Identity = AuthedUser | ServiceCaller;
|
|
22
32
|
declare module 'hono' {
|
|
@@ -45,7 +55,20 @@ export interface RequireIdentityOptions extends S2sOptions {
|
|
|
45
55
|
* sessions and the test bypass alike; service callers are governed by
|
|
46
56
|
* grants, not by this. */
|
|
47
57
|
userAccess?: UserAccessPolicy;
|
|
58
|
+
/** Admits guest sessions on this mount, in addition to whatever
|
|
59
|
+
* `userAccess` admits. Default false: the `pw_guest` cookie is never
|
|
60
|
+
* read, no guest lookup is ever made, and a guest is simply not signed
|
|
61
|
+
* in. With true, a request without a signed-in fleet session that
|
|
62
|
+
* carries a `pw_guest` cookie is resolved through whoami's guest answer
|
|
63
|
+
* and admitted with role 'guest' whatever `userAccess` says — so every
|
|
64
|
+
* route under the mount must decide for itself what a guest may reach. */
|
|
65
|
+
guestAccess?: boolean;
|
|
48
66
|
}
|
|
49
|
-
/** The one place the policy is evaluated.
|
|
67
|
+
/** The one place the policy is evaluated. It names the roles it admits, so
|
|
68
|
+
* a 'guest' is refused under every policy: the guest path of a
|
|
69
|
+
* `guestAccess` mount is the only way one is admitted. */
|
|
50
70
|
export declare function userAllowed(policy: UserAccessPolicy, user: Pick<AuthedUser, 'role'>): boolean;
|
|
71
|
+
/** A full session's role from an untrusted value. Anything else — 'guest'
|
|
72
|
+
* included — is undefined, which every caller treats as "no usable role". */
|
|
73
|
+
export declare function parseFullRole(value: unknown): FullRole | undefined;
|
|
51
74
|
export declare function requireIdentity(opts: RequireIdentityOptions): import("hono").MiddlewareHandler<any, string, {}, Response>;
|
package/dist/auth.js
CHANGED
|
@@ -4,9 +4,10 @@
|
|
|
4
4
|
// Resolves who is calling, in order:
|
|
5
5
|
// 1. Test bypass (AUTH_MODE=test): X-Test-S2S-Caller → service caller;
|
|
6
6
|
// X-Test-User header or TEST_USER env → user, with the fleet role from
|
|
7
|
-
// X-Test-User-Role / TEST_USER_ROLE (default 'invited')
|
|
8
|
-
//
|
|
9
|
-
//
|
|
7
|
+
// X-Test-User-Role / TEST_USER_ROLE (default 'invited') and the domain
|
|
8
|
+
// from X-Test-User-Domain / TEST_USER_DOMAIN. Credential verification
|
|
9
|
+
// is bypassed; authorization (grants, the userAccess policy, guest
|
|
10
|
+
// admission, app-level checks) still runs.
|
|
10
11
|
// 2. Authorization: Bearer → service-to-service OIDC (s2s.ts).
|
|
11
12
|
// 3. pw_session cookie → whoami call to the auth service, cached
|
|
12
13
|
// in-instance (10 min hits / 30 s misses — the old-world numbers),
|
|
@@ -14,6 +15,10 @@
|
|
|
14
15
|
// Every call (never a cache hit) logs one INFO 'session check' event
|
|
15
16
|
// saying why the cache could not answer and what the call cost the
|
|
16
17
|
// waiting request (~/migration/research/whoami-latency-2026-10-30.md).
|
|
18
|
+
// 4. Only on a mount with `guestAccess: true`, and only when step 3 found
|
|
19
|
+
// no signed-in user (no pw_session cookie, or whoami answered 401):
|
|
20
|
+
// pw_guest cookie → whoami?guest=1, cached, single-flighted and logged
|
|
21
|
+
// like step 3 under keys of its own.
|
|
17
22
|
//
|
|
18
23
|
// Then the user-access policy: by default an app admits only users whose
|
|
19
24
|
// auth role is 'owner'; `userAccess: 'invited'` admits any active fleet
|
|
@@ -21,11 +26,18 @@
|
|
|
21
26
|
// so a port that forgets the question is closed, not open. Service callers
|
|
22
27
|
// are governed by grants, not by this policy.
|
|
23
28
|
//
|
|
29
|
+
// Guests (role 'guest') are people outside the fleet whom one app let in —
|
|
30
|
+
// a Notes page shared with them. The auth service gives them a session of
|
|
31
|
+
// its own kind in its own cookie, so the policy above never sees one and
|
|
32
|
+
// never admits one: an app that has not set `guestAccess` treats a guest as
|
|
33
|
+
// signed out, and one that has must decide per route what a guest reaches.
|
|
34
|
+
//
|
|
24
35
|
// Unauthenticated: APIs get 401 JSON, pages redirect to the auth service's
|
|
25
36
|
// login with a return URL. Denied users get 403 (JSON with a stable `code`
|
|
26
37
|
// on APIs, a plain "not enabled" page otherwise). Auth-service *failures*
|
|
27
|
-
// (network, 5xx, a whoami answer with no role
|
|
28
|
-
// redirect — a redirect on failure loops
|
|
38
|
+
// (network, 5xx, a whoami answer with no role or with a role its cookie
|
|
39
|
+
// cannot carry) return 503 and never redirect — a redirect on failure loops
|
|
40
|
+
// forever (old-world lesson).
|
|
29
41
|
import { createHash } from 'node:crypto';
|
|
30
42
|
import { createMiddleware } from 'hono/factory';
|
|
31
43
|
import { authMode } from './config.js';
|
|
@@ -34,14 +46,20 @@ import { RateLimiter, resolveS2sCaller } from './s2s.js';
|
|
|
34
46
|
import { fleetAddressState, fleetFetch } from './fleet-dns.js';
|
|
35
47
|
export const DEFAULT_AUTH_URL = 'https://auth.apps.snewman.net';
|
|
36
48
|
export const SESSION_COOKIE = 'pw_session';
|
|
49
|
+
/** The cookie of a guest session. Only a `guestAccess` mount ever reads it. */
|
|
50
|
+
export const GUEST_COOKIE = 'pw_guest';
|
|
37
51
|
/** The `code` in a 403 JSON body when a signed-in user is refused by the
|
|
38
52
|
* app's userAccess policy (as opposed to any other 403). */
|
|
39
53
|
export const ACCESS_DENIED_CODE = 'app_access_denied';
|
|
40
|
-
/** The one place the policy is evaluated.
|
|
54
|
+
/** The one place the policy is evaluated. It names the roles it admits, so
|
|
55
|
+
* a 'guest' is refused under every policy: the guest path of a
|
|
56
|
+
* `guestAccess` mount is the only way one is admitted. */
|
|
41
57
|
export function userAllowed(policy, user) {
|
|
42
|
-
return policy === 'invited'
|
|
58
|
+
return user.role === 'owner' || (policy === 'invited' && user.role === 'invited');
|
|
43
59
|
}
|
|
44
|
-
|
|
60
|
+
/** A full session's role from an untrusted value. Anything else — 'guest'
|
|
61
|
+
* included — is undefined, which every caller treats as "no usable role". */
|
|
62
|
+
export function parseFullRole(value) {
|
|
45
63
|
return value === 'owner' || value === 'invited' ? value : undefined;
|
|
46
64
|
}
|
|
47
65
|
export function requireIdentity(opts) {
|
|
@@ -51,7 +69,9 @@ export function requireIdentity(opts) {
|
|
|
51
69
|
const hitMs = opts.cacheTtl?.hitMs ?? 600_000;
|
|
52
70
|
const missMs = opts.cacheTtl?.missMs ?? 30_000;
|
|
53
71
|
const policy = opts.userAccess ?? 'owner';
|
|
72
|
+
const guestAccess = opts.guestAccess === true;
|
|
54
73
|
const limiter = new RateLimiter(opts.rateLimitPerMin ?? 600);
|
|
74
|
+
// Both keyed by cacheKey(): a session kind plus the request's cookies.
|
|
55
75
|
const cache = new Map();
|
|
56
76
|
// The whoami call in flight per cache key (single-flight).
|
|
57
77
|
const inFlight = new Map();
|
|
@@ -85,8 +105,12 @@ export function requireIdentity(opts) {
|
|
|
85
105
|
return c.html(accessDeniedPage({ host: c.req.header('host') ?? 'This app', email: user.email, authUrl }), 403);
|
|
86
106
|
};
|
|
87
107
|
return createMiddleware(async (c, next) => {
|
|
88
|
-
|
|
89
|
-
|
|
108
|
+
// A user from a guest session is admitted as a guest whatever the
|
|
109
|
+
// policy says, and as nothing else; every other user goes through the
|
|
110
|
+
// policy, which never admits a guest.
|
|
111
|
+
const admit = (user, session = 'full') => {
|
|
112
|
+
const allowed = session === 'guest' ? user.role === 'guest' : userAllowed(policy, user);
|
|
113
|
+
if (!allowed)
|
|
90
114
|
return accessDenied(c, user);
|
|
91
115
|
c.set('identity', user);
|
|
92
116
|
c.set('user', user);
|
|
@@ -98,8 +122,17 @@ export function requireIdentity(opts) {
|
|
|
98
122
|
const email = c.req.header('x-test-user') ?? process.env.TEST_USER;
|
|
99
123
|
if (!email)
|
|
100
124
|
return unauthenticated(c);
|
|
101
|
-
const role =
|
|
102
|
-
|
|
125
|
+
const role = c.req.header('x-test-user-role') ?? process.env.TEST_USER_ROLE;
|
|
126
|
+
const domain = c.req.header('x-test-user-domain') ?? process.env.TEST_USER_DOMAIN;
|
|
127
|
+
const user = { type: 'user', email, ...(domain ? { domain } : {}) };
|
|
128
|
+
if (role === 'guest') {
|
|
129
|
+
// As in production: a mount that does not admit guests sees no
|
|
130
|
+
// session at all for one.
|
|
131
|
+
if (!guestAccess)
|
|
132
|
+
return unauthenticated(c);
|
|
133
|
+
return admit({ ...user, role }, 'guest');
|
|
134
|
+
}
|
|
135
|
+
return admit({ ...user, role: parseFullRole(role) ?? 'invited' });
|
|
103
136
|
}
|
|
104
137
|
// Service-to-service path.
|
|
105
138
|
if (c.req.header('authorization') || c.req.header('x-test-s2s-caller')) {
|
|
@@ -115,46 +148,62 @@ export function requireIdentity(opts) {
|
|
|
115
148
|
c.set('identity', resolved.caller);
|
|
116
149
|
return next();
|
|
117
150
|
}
|
|
118
|
-
// Browser session path.
|
|
151
|
+
// Browser session path. The fleet session is asked first; the guest
|
|
152
|
+
// session only on a guestAccess mount, and only for a request with no
|
|
153
|
+
// signed-in fleet session (no pw_session cookie, or one whoami refused).
|
|
119
154
|
const cookieHeader = c.req.header('cookie') ?? '';
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
155
|
+
const sessions = [];
|
|
156
|
+
if (/(?:^|;\s*)pw_session=/.test(cookieHeader))
|
|
157
|
+
sessions.push('full');
|
|
158
|
+
if (guestAccess && /(?:^|;\s*)pw_guest=/.test(cookieHeader))
|
|
159
|
+
sessions.push('guest');
|
|
160
|
+
for (const session of sessions) {
|
|
161
|
+
const outcome = await lookup(c, session, cookieHeader);
|
|
162
|
+
if (outcome.kind === 'user')
|
|
163
|
+
return admit(outcome.user, session);
|
|
164
|
+
// A fault ends the request: a fleet lookup that failed is never
|
|
165
|
+
// answered from the guest session instead.
|
|
166
|
+
if (outcome.kind === 'unavailable')
|
|
167
|
+
return c.json({ error: 'auth service unavailable' }, 503);
|
|
168
|
+
}
|
|
169
|
+
return unauthenticated(c);
|
|
170
|
+
});
|
|
171
|
+
// Guest answers live under keys no fleet key can equal (a bare hash), so
|
|
172
|
+
// an answer for one kind of session is never served for the other.
|
|
173
|
+
function cacheKey(session, cookieHeader) {
|
|
174
|
+
const hash = createHash('sha256').update(cookieHeader).digest('hex');
|
|
175
|
+
return session === 'guest' ? `guest:${hash}` : hash;
|
|
176
|
+
}
|
|
177
|
+
// What whoami says about one of a request's sessions: from the cache, or
|
|
178
|
+
// from one call. Nothing here awaits before the flight is registered.
|
|
179
|
+
async function lookup(c, session, cookieHeader) {
|
|
180
|
+
const key = cacheKey(session, cookieHeader);
|
|
123
181
|
const cached = cache.get(key);
|
|
124
182
|
if (cached && cached.expires > Date.now()) {
|
|
125
183
|
hitsSinceLastCall++;
|
|
126
|
-
|
|
127
|
-
return unauthenticated(c);
|
|
128
|
-
return admit(cached.user);
|
|
184
|
+
return cached.user ? { kind: 'user', user: cached.user } : { kind: 'unauthenticated' };
|
|
129
185
|
}
|
|
130
186
|
// Single-flight: a request that misses while a call for the same cookie
|
|
131
187
|
// is already in flight shares that call's answer instead of making its
|
|
132
188
|
// own (30% of calls were such duplicates). Every request still gets an
|
|
133
189
|
// answer fetched during its own lifetime, so what is admitted does not
|
|
134
|
-
// change; the answer is applied per request
|
|
190
|
+
// change; the answer is applied per request by the caller.
|
|
135
191
|
const flight = inFlight.get(key);
|
|
136
192
|
if (flight) {
|
|
137
193
|
flight.joiners.count++;
|
|
138
|
-
return
|
|
194
|
+
return flight.outcome;
|
|
139
195
|
}
|
|
140
196
|
const joiners = { count: 0 };
|
|
141
|
-
const outcome = callWhoami(c, key, cached, cookieHeader, joiners).finally(() => inFlight.delete(key));
|
|
197
|
+
const outcome = callWhoami(c, session, key, cached, cookieHeader, joiners).finally(() => inFlight.delete(key));
|
|
142
198
|
inFlight.set(key, { outcome, joiners });
|
|
143
|
-
return
|
|
144
|
-
|
|
145
|
-
if (outcome.kind === 'user')
|
|
146
|
-
return admit(outcome.user);
|
|
147
|
-
if (outcome.kind === 'unauthenticated')
|
|
148
|
-
return unauthenticated(c);
|
|
149
|
-
return c.json({ error: 'auth service unavailable' }, 503);
|
|
150
|
-
}
|
|
151
|
-
});
|
|
199
|
+
return outcome;
|
|
200
|
+
}
|
|
152
201
|
// One whoami call, whose answer every request that joined it shares. The
|
|
153
202
|
// waiting request pays its full latency. One INFO event per call (a few
|
|
154
203
|
// hundred a day fleet-wide; never per hit or per joined request), with a
|
|
155
204
|
// fixed vocabulary of keys and nothing from the cookie but how many
|
|
156
205
|
// cookies the header carries (a changing header defeats the cache).
|
|
157
|
-
async function callWhoami(c, key, cached, cookieHeader, joiners) {
|
|
206
|
+
async function callWhoami(c, session, key, cached, cookieHeader, joiners) {
|
|
158
207
|
const started = Date.now();
|
|
159
208
|
const cacheState = !cached ? 'absent' : cached.user ? 'expired-user' : 'expired-unauthenticated';
|
|
160
209
|
// Whether this call must look up the auth host's address (absent) or has
|
|
@@ -162,6 +211,7 @@ export function requireIdentity(opts) {
|
|
|
162
211
|
// background); undefined for a non-fleet authUrl.
|
|
163
212
|
const authAddress = fleetAddressState(authHost);
|
|
164
213
|
const callFields = {
|
|
214
|
+
guest: session === 'guest',
|
|
165
215
|
cacheState,
|
|
166
216
|
...(cached ? { entryAgeMs: started - cached.filled } : {}),
|
|
167
217
|
hitsSinceLastCall,
|
|
@@ -190,7 +240,10 @@ export function requireIdentity(opts) {
|
|
|
190
240
|
};
|
|
191
241
|
let res;
|
|
192
242
|
try {
|
|
193
|
-
|
|
243
|
+
// auth answers from pw_guest only when asked to; from pw_session otherwise.
|
|
244
|
+
res = await whoamiFetch(`${authUrl}/api/whoami${session === 'guest' ? '?guest=1' : ''}`, {
|
|
245
|
+
headers: { cookie: cookieHeader },
|
|
246
|
+
});
|
|
194
247
|
}
|
|
195
248
|
catch (err) {
|
|
196
249
|
callEnded(0);
|
|
@@ -200,15 +253,28 @@ export function requireIdentity(opts) {
|
|
|
200
253
|
callEnded(res.status);
|
|
201
254
|
if (res.ok) {
|
|
202
255
|
const data = (await res.json());
|
|
203
|
-
|
|
256
|
+
// Each kind of session carries its own roles: the guest session only
|
|
257
|
+
// 'guest', the fleet session never.
|
|
258
|
+
const role = session === 'guest' ? (data.role === 'guest' ? 'guest' : undefined) : parseFullRole(data.role);
|
|
204
259
|
if (!role) {
|
|
205
260
|
// An auth service from before roles existed (a rollback), or a
|
|
206
|
-
// protocol change
|
|
207
|
-
//
|
|
208
|
-
|
|
261
|
+
// protocol change — a guest answering for the fleet cookie, a fleet
|
|
262
|
+
// user for the guest cookie: a fault, not an "invited" answer. Fail
|
|
263
|
+
// closed, loudly, and without caching so recovery is instant.
|
|
264
|
+
opts.logger?.error(session === 'guest' ? 'guest whoami answer has the wrong role' : 'whoami answer has no role', {
|
|
265
|
+
email: data.email,
|
|
266
|
+
role: data.role,
|
|
267
|
+
});
|
|
209
268
|
return { kind: 'unavailable' };
|
|
210
269
|
}
|
|
211
|
-
const user = {
|
|
270
|
+
const user = {
|
|
271
|
+
type: 'user',
|
|
272
|
+
email: data.email,
|
|
273
|
+
name: data.name,
|
|
274
|
+
userId: data.user_id,
|
|
275
|
+
role,
|
|
276
|
+
...(typeof data.domain === 'string' && data.domain ? { domain: data.domain } : {}),
|
|
277
|
+
};
|
|
212
278
|
const now = Date.now();
|
|
213
279
|
cache.set(key, { expires: now + hitMs, filled: now, user });
|
|
214
280
|
return { kind: 'user', user };
|
package/dist/connector.d.ts
CHANGED
|
@@ -20,7 +20,8 @@ export declare const CONNECTOR_HEADERS: {
|
|
|
20
20
|
/** The headers that carry `user` to an app (the front door's side). */
|
|
21
21
|
export declare function connectorIdentityHeaders(user: ConnectorUser): Record<string, string>;
|
|
22
22
|
/** The identity the headers assert, or null when any required one is
|
|
23
|
-
* missing or malformed
|
|
23
|
+
* missing or malformed — a role other than owner or invited included, so
|
|
24
|
+
* no guest is ever asserted. Header values are what the front door set; an
|
|
24
25
|
* attacker who can set them has already passed the s2s check. */
|
|
25
26
|
export declare function parseConnectorIdentityHeaders(header: (name: string) => string | undefined): ConnectorUser | null;
|
|
26
27
|
export interface ForwardedConnectorOptions {
|
package/dist/connector.js
CHANGED
|
@@ -20,7 +20,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
|
20
20
|
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
21
21
|
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
|
|
22
22
|
import { createMiddleware } from 'hono/factory';
|
|
23
|
-
import { ACCESS_DENIED_CODE, userAllowed } from './auth.js';
|
|
23
|
+
import { ACCESS_DENIED_CODE, parseFullRole, userAllowed } from './auth.js';
|
|
24
24
|
import { serializeError } from './log-core.js';
|
|
25
25
|
import { insufficientScope } from './oauth-resource.js';
|
|
26
26
|
import { RateLimiter, resolveS2sCaller } from './s2s.js';
|
|
@@ -46,15 +46,13 @@ export function connectorIdentityHeaders(user) {
|
|
|
46
46
|
...(user.name ? { [CONNECTOR_HEADERS.name]: user.name } : {}),
|
|
47
47
|
};
|
|
48
48
|
}
|
|
49
|
-
function parseRole(value) {
|
|
50
|
-
return value === 'owner' || value === 'invited' ? value : undefined;
|
|
51
|
-
}
|
|
52
49
|
/** The identity the headers assert, or null when any required one is
|
|
53
|
-
* missing or malformed
|
|
50
|
+
* missing or malformed — a role other than owner or invited included, so
|
|
51
|
+
* no guest is ever asserted. Header values are what the front door set; an
|
|
54
52
|
* attacker who can set them has already passed the s2s check. */
|
|
55
53
|
export function parseConnectorIdentityHeaders(header) {
|
|
56
54
|
const email = header(CONNECTOR_HEADERS.user);
|
|
57
|
-
const role =
|
|
55
|
+
const role = parseFullRole(header(CONNECTOR_HEADERS.role));
|
|
58
56
|
const clientId = header(CONNECTOR_HEADERS.client);
|
|
59
57
|
const grantId = header(CONNECTOR_HEADERS.grant);
|
|
60
58
|
const scope = header(CONNECTOR_HEADERS.scope);
|
package/dist/db.d.ts
CHANGED
|
@@ -49,8 +49,8 @@ export interface PoolOptions {
|
|
|
49
49
|
/** Receives idle-client errors (see logPoolErrors). Without one they go to
|
|
50
50
|
* stderr — on the Cloud Logging backstop, but not in Axiom. */
|
|
51
51
|
logger?: Logger;
|
|
52
|
-
/** Tuning for `probeIdleCheckouts` (defaults IDLE_PROBE_AFTER_MS
|
|
53
|
-
* IDLE_PROBE_TIMEOUT_MS); tests shorten them. */
|
|
52
|
+
/** Tuning for `probeIdleCheckouts` (defaults IDLE_PROBE_AFTER_MS,
|
|
53
|
+
* IDLE_PROBE_TIMEOUT_MS and LOSS_PROBE_WINDOW_MS); tests shorten them. */
|
|
54
54
|
idleProbe?: IdleProbeOptions;
|
|
55
55
|
}
|
|
56
56
|
/** Why a fleet-wide statement timeout (mirror, 2026-09-08): a transaction an
|
|
@@ -117,6 +117,18 @@ export declare const IDLE_PROBE_AFTER_MS = 10000;
|
|
|
117
117
|
/** How long the probe waits. A healthy `select 1` takes a millisecond or
|
|
118
118
|
* two; a half-open socket would otherwise wait for TCP to give up. */
|
|
119
119
|
export declare const IDLE_PROBE_TIMEOUT_MS = 3000;
|
|
120
|
+
/** After a pool loses a connection, every reused client is probed for this
|
|
121
|
+
* long, however briefly it sat idle. A connection cut rarely kills one
|
|
122
|
+
* socket: since 2026-11-13 Cloud Run cuts all of an instance's connections
|
|
123
|
+
* on the instance's side (12-hour instance cuts, the twice-daily windows;
|
|
124
|
+
* KNOWN_LOG_PATTERNS fleet entry "database pool: idle client error"), and
|
|
125
|
+
* each pooled socket learns of it only when next written to. Without this,
|
|
126
|
+
* every checkout in the first seconds after a cut could draw a dead
|
|
127
|
+
* sibling (mirror 2026-11-17 10:17Z: four job workers in 180 ms; chime's
|
|
128
|
+
* LISTEN bridge, its reconnect and its retry). 30 s covers the pile-up
|
|
129
|
+
* seen (all within 10 s of the first loss) with room; each loss restarts
|
|
130
|
+
* it, and it costs one `select 1` per checkout only inside it. */
|
|
131
|
+
export declare const LOSS_PROBE_WINDOW_MS = 30000;
|
|
120
132
|
/** Keep a pg connection's death from killing the process, and log every
|
|
121
133
|
* way a pool loses or fails to get a connection as one WARN family:
|
|
122
134
|
* `kind=db-connection-loss`, `meta.phase`:
|
|
@@ -165,9 +177,14 @@ export declare function logPoolErrors(pool: pg.Pool, logger?: Logger, options?:
|
|
|
165
177
|
export interface IdleProbeOptions {
|
|
166
178
|
afterIdleMs?: number;
|
|
167
179
|
timeoutMs?: number;
|
|
180
|
+
/** How long after a connection loss every reused client is probed
|
|
181
|
+
* (default LOSS_PROBE_WINDOW_MS). */
|
|
182
|
+
afterLossMs?: number;
|
|
168
183
|
}
|
|
169
184
|
/** Hand out no pooled client that died while idle. A client idle for
|
|
170
|
-
* `afterIdleMs` or more
|
|
185
|
+
* `afterIdleMs` or more, or any reused client within `afterLossMs` of the
|
|
186
|
+
* pool's last connection loss (a cut kills the siblings too; see
|
|
187
|
+
* LOSS_PROBE_WINDOW_MS), runs `select 1` (bounded by `timeoutMs`) before
|
|
171
188
|
* the borrower gets it; if that fails the client is discarded, one WARN
|
|
172
189
|
* (`kind=db-connection-loss`, `phase=idle`, `detectedAt=checkout`) is
|
|
173
190
|
* logged, and the checkout is retried, ending at a fresh connection at
|
|
@@ -175,8 +192,12 @@ export interface IdleProbeOptions {
|
|
|
175
192
|
* ran on the dead client. What stays unretried, as before: a connection
|
|
176
193
|
* that dies after the probe, mid-statement or mid-transaction (the
|
|
177
194
|
* borrower sees the error; whether a lone statement took effect is
|
|
178
|
-
* unknowable),
|
|
179
|
-
*
|
|
195
|
+
* unknowable), a failed new connection (`phase=connect`), and the
|
|
196
|
+
* first checkout to meet a cut (nothing has been lost yet to warn of it).
|
|
197
|
+
* New clients, and recently used ones outside the window, are not probed;
|
|
198
|
+
* a probe the window caused logs `sinceLossMs` on its WARN. Losses are
|
|
199
|
+
* seen through `logPoolErrors` (idle and checked-out) and this probe
|
|
200
|
+
* itself, so a hand-built pool needs both to get the full window. Both connect forms are covered
|
|
180
201
|
* (`pool.query` checks out in callback form). `createPool` attaches this;
|
|
181
202
|
* exported for a pool an app built itself. Idempotent per pool. */
|
|
182
203
|
export declare function probeIdleCheckouts(pool: pg.Pool, logger?: Logger, options?: IdleProbeOptions): void;
|
package/dist/db.js
CHANGED
|
@@ -125,6 +125,18 @@ export const IDLE_PROBE_AFTER_MS = 10_000;
|
|
|
125
125
|
* two; a half-open socket would otherwise wait for TCP to give up. */
|
|
126
126
|
export const IDLE_PROBE_TIMEOUT_MS = 3_000;
|
|
127
127
|
const IDLE_PROBE_SQL = 'select 1 /* baselib idle probe */';
|
|
128
|
+
/** After a pool loses a connection, every reused client is probed for this
|
|
129
|
+
* long, however briefly it sat idle. A connection cut rarely kills one
|
|
130
|
+
* socket: since 2026-11-13 Cloud Run cuts all of an instance's connections
|
|
131
|
+
* on the instance's side (12-hour instance cuts, the twice-daily windows;
|
|
132
|
+
* KNOWN_LOG_PATTERNS fleet entry "database pool: idle client error"), and
|
|
133
|
+
* each pooled socket learns of it only when next written to. Without this,
|
|
134
|
+
* every checkout in the first seconds after a cut could draw a dead
|
|
135
|
+
* sibling (mirror 2026-11-17 10:17Z: four job workers in 180 ms; chime's
|
|
136
|
+
* LISTEN bridge, its reconnect and its retry). 30 s covers the pile-up
|
|
137
|
+
* seen (all within 10 s of the first loss) with room; each loss restarts
|
|
138
|
+
* it, and it costs one `select 1` per checkout only inside it. */
|
|
139
|
+
export const LOSS_PROBE_WINDOW_MS = 30_000;
|
|
128
140
|
const CONNECTION_LOSS_KIND = 'db-connection-loss';
|
|
129
141
|
const ACQUIRE_FAILED_MESSAGE = {
|
|
130
142
|
connect: 'database pool: new connection failed',
|
|
@@ -147,10 +159,17 @@ const instrumented = new WeakSet();
|
|
|
147
159
|
// Clients under an idle probe: their death is reported once, by the probe,
|
|
148
160
|
// as an idle loss rather than a checked-out one.
|
|
149
161
|
const probing = new WeakSet();
|
|
162
|
+
// When each pool last lost a client's connection (an idle error, a
|
|
163
|
+
// checked-out loss, a probe finding one dead): `probeIdleCheckouts` probes
|
|
164
|
+
// every reused client for LOSS_PROBE_WINDOW_MS after it.
|
|
165
|
+
const lastLossAt = new WeakMap();
|
|
150
166
|
/** One `kind=db-connection-loss` WARN, the shape every pool loss shares. */
|
|
151
167
|
function connectionLossWarner(pool, logger, credentialExpiry) {
|
|
152
168
|
const log = logger?.with({ kind: CONNECTION_LOSS_KIND });
|
|
153
169
|
return (phase, message, err, since, extra = {}) => {
|
|
170
|
+
// A failed connect or a starved wait loses no existing connection.
|
|
171
|
+
if (phase === 'idle' || phase === 'checked-out')
|
|
172
|
+
lastLossAt.set(pool, Date.now());
|
|
154
173
|
const expiry = credentialExpiry?.();
|
|
155
174
|
const meta = {
|
|
156
175
|
phase,
|
|
@@ -391,7 +410,9 @@ function timeNewConnections(pool, logger, options) {
|
|
|
391
410
|
}
|
|
392
411
|
const probed = new WeakSet();
|
|
393
412
|
/** Hand out no pooled client that died while idle. A client idle for
|
|
394
|
-
* `afterIdleMs` or more
|
|
413
|
+
* `afterIdleMs` or more, or any reused client within `afterLossMs` of the
|
|
414
|
+
* pool's last connection loss (a cut kills the siblings too; see
|
|
415
|
+
* LOSS_PROBE_WINDOW_MS), runs `select 1` (bounded by `timeoutMs`) before
|
|
395
416
|
* the borrower gets it; if that fails the client is discarded, one WARN
|
|
396
417
|
* (`kind=db-connection-loss`, `phase=idle`, `detectedAt=checkout`) is
|
|
397
418
|
* logged, and the checkout is retried, ending at a fresh connection at
|
|
@@ -399,8 +420,12 @@ const probed = new WeakSet();
|
|
|
399
420
|
* ran on the dead client. What stays unretried, as before: a connection
|
|
400
421
|
* that dies after the probe, mid-statement or mid-transaction (the
|
|
401
422
|
* borrower sees the error; whether a lone statement took effect is
|
|
402
|
-
* unknowable),
|
|
403
|
-
*
|
|
423
|
+
* unknowable), a failed new connection (`phase=connect`), and the
|
|
424
|
+
* first checkout to meet a cut (nothing has been lost yet to warn of it).
|
|
425
|
+
* New clients, and recently used ones outside the window, are not probed;
|
|
426
|
+
* a probe the window caused logs `sinceLossMs` on its WARN. Losses are
|
|
427
|
+
* seen through `logPoolErrors` (idle and checked-out) and this probe
|
|
428
|
+
* itself, so a hand-built pool needs both to get the full window. Both connect forms are covered
|
|
404
429
|
* (`pool.query` checks out in callback form). `createPool` attaches this;
|
|
405
430
|
* exported for a pool an app built itself. Idempotent per pool. */
|
|
406
431
|
export function probeIdleCheckouts(pool, logger, options = {}) {
|
|
@@ -409,6 +434,7 @@ export function probeIdleCheckouts(pool, logger, options = {}) {
|
|
|
409
434
|
probed.add(pool);
|
|
410
435
|
const afterIdleMs = options.afterIdleMs ?? IDLE_PROBE_AFTER_MS;
|
|
411
436
|
const timeoutMs = options.timeoutMs ?? IDLE_PROBE_TIMEOUT_MS;
|
|
437
|
+
const afterLossMs = options.afterLossMs ?? LOSS_PROBE_WINDOW_MS;
|
|
412
438
|
const releasedAt = new WeakMap();
|
|
413
439
|
pool.on('release', (_err, client) => releasedAt.set(client, Date.now()));
|
|
414
440
|
const warn = connectionLossWarner(pool, logger);
|
|
@@ -419,7 +445,12 @@ export function probeIdleCheckouts(pool, logger, options = {}) {
|
|
|
419
445
|
for (;;) {
|
|
420
446
|
const client = await connect();
|
|
421
447
|
const idleSince = releasedAt.get(client);
|
|
422
|
-
if (idleSince === undefined
|
|
448
|
+
if (idleSince === undefined)
|
|
449
|
+
return client;
|
|
450
|
+
const now = Date.now();
|
|
451
|
+
const lossAt = lastLossAt.get(pool);
|
|
452
|
+
const sinceLossMs = lossAt === undefined || now - lossAt >= afterLossMs ? undefined : now - lossAt;
|
|
453
|
+
if (now - idleSince < afterIdleMs && sinceLossMs === undefined)
|
|
423
454
|
return client;
|
|
424
455
|
probing.add(client);
|
|
425
456
|
// The death also arrives as a client 'error', possibly after the
|
|
@@ -444,7 +475,10 @@ export function probeIdleCheckouts(pool, logger, options = {}) {
|
|
|
444
475
|
}
|
|
445
476
|
catch (err) {
|
|
446
477
|
const error = err instanceof Error ? err : new Error(String(err));
|
|
447
|
-
warn('idle', 'database pool: idle client found dead at checkout; replaced', error, idleSince, {
|
|
478
|
+
warn('idle', 'database pool: idle client found dead at checkout; replaced', error, idleSince, {
|
|
479
|
+
detectedAt: 'checkout',
|
|
480
|
+
...(now - idleSince < afterIdleMs ? { sinceLossMs } : {}),
|
|
481
|
+
});
|
|
448
482
|
client.release(error);
|
|
449
483
|
}
|
|
450
484
|
finally {
|
package/dist/email.d.ts
CHANGED
|
@@ -24,8 +24,15 @@ export interface SendEmailResult {
|
|
|
24
24
|
ok: boolean;
|
|
25
25
|
/** Resend's message id, when the send succeeded and the response parsed. */
|
|
26
26
|
emailId?: string;
|
|
27
|
-
/** Human-readable failure description, present when `ok` is false.
|
|
27
|
+
/** Human-readable failure description, present when `ok` is false. For a
|
|
28
|
+
* refused send it quotes Resend's answer, which is Resend's text, not
|
|
29
|
+
* ours: a caller that sends with `logContent: false` should not log it. */
|
|
28
30
|
error?: string;
|
|
31
|
+
/** Resend's HTTP status when it answered and refused the send. Absent for
|
|
32
|
+
* a failure with no answer (not configured, network, timeout). A caller
|
|
33
|
+
* that retries can tell a rejection it will never win (4xx other than
|
|
34
|
+
* 408, 409 and 429) from one worth another attempt. */
|
|
35
|
+
status?: number;
|
|
29
36
|
}
|
|
30
37
|
export interface EmailDeps {
|
|
31
38
|
/** Resend API key. Falsy means "email not configured": logged at ERROR with
|
|
@@ -48,13 +55,23 @@ export interface EmailDeps {
|
|
|
48
55
|
* the email unique (e.g. `digest:<user>:<date>`), never from the
|
|
49
56
|
* attempt. See the header of this file for the verified semantics. */
|
|
50
57
|
idempotencyKey?: string;
|
|
58
|
+
/** Whether log lines may carry the message's content. Default true: every
|
|
59
|
+
* line has the subject, and a failure's ERROR has a preview of the bodies
|
|
60
|
+
* and Resend's answer, so the send can be redone by hand. False: no line
|
|
61
|
+
* written here contains the subject or any part of the text or HTML
|
|
62
|
+
* body, on success or failure — it logs their lengths instead, and of
|
|
63
|
+
* Resend's answer to a refused send only the status, the length and the
|
|
64
|
+
* error `name`. The recipient, `context` and `idempotencyKey` are logged
|
|
65
|
+
* either way, so keep content out of those. */
|
|
66
|
+
logContent?: boolean;
|
|
51
67
|
}
|
|
52
68
|
export declare const DEFAULT_EMAIL_TIMEOUT_MS = 30000;
|
|
53
69
|
/**
|
|
54
70
|
* Send one email through Resend. Never throws: every failure is an ERROR
|
|
55
|
-
* log (with enough of the message to redo the send by hand
|
|
56
|
-
* `{ ok: false, error }` result the
|
|
57
|
-
*
|
|
58
|
-
* nevertheless have been
|
|
71
|
+
* log (with enough of the message to redo the send by hand, unless
|
|
72
|
+
* `deps.logContent` is false) and an `{ ok: false, error }` result the
|
|
73
|
+
* caller surfaces where it matters. That includes a timeout
|
|
74
|
+
* (`deps.timeoutMs`), after which the email may nevertheless have been
|
|
75
|
+
* delivered.
|
|
59
76
|
*/
|
|
60
77
|
export declare function sendEmail(msg: EmailMessage, deps: EmailDeps): Promise<SendEmailResult>;
|
package/dist/email.js
CHANGED
|
@@ -25,9 +25,30 @@
|
|
|
25
25
|
// the first is still in flight is 409 `concurrent_idempotent_requests`
|
|
26
26
|
// (retry later); a key over 256 characters is 400 `invalid_idempotency_key`.
|
|
27
27
|
// All three are failures: none confirms that this message was accepted.
|
|
28
|
+
//
|
|
29
|
+
// `logContent: false` (3.68.0) is for mail whose words are other people's
|
|
30
|
+
// (Notes' comment digests): the logs then carry sizes and Resend's status,
|
|
31
|
+
// never the subject, the bodies, or Resend's own prose about the message.
|
|
32
|
+
// Such a caller gives up "redone by hand" and owns its retries.
|
|
28
33
|
import { serializeError, truncate } from './log-core.js';
|
|
29
34
|
export const RESEND_API_URL = 'https://api.resend.com/emails';
|
|
30
35
|
export const DEFAULT_EMAIL_TIMEOUT_MS = 30_000;
|
|
36
|
+
/** What a no-content log line says about Resend's answer to a refused send:
|
|
37
|
+
* its length and its machine-readable `name` (`validation_error`, …). The
|
|
38
|
+
* rest is Resend's prose, which may quote the message. */
|
|
39
|
+
function refusalFacts(body) {
|
|
40
|
+
let name;
|
|
41
|
+
try {
|
|
42
|
+
name = JSON.parse(body)?.name;
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
// Not JSON: the length is all there is to say.
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
responseLength: body.length,
|
|
49
|
+
...(typeof name === 'string' && /^[a-z0-9_]{1,64}$/.test(name) ? { errorName: name } : {}),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
31
52
|
/** The JSON body of Resend's `POST /emails`: optional fields are omitted
|
|
32
53
|
* rather than sent empty. */
|
|
33
54
|
function resendRequestBody(msg) {
|
|
@@ -51,25 +72,28 @@ function resendRequestBody(msg) {
|
|
|
51
72
|
}
|
|
52
73
|
/**
|
|
53
74
|
* Send one email through Resend. Never throws: every failure is an ERROR
|
|
54
|
-
* log (with enough of the message to redo the send by hand
|
|
55
|
-
* `{ ok: false, error }` result the
|
|
56
|
-
*
|
|
57
|
-
* nevertheless have been
|
|
75
|
+
* log (with enough of the message to redo the send by hand, unless
|
|
76
|
+
* `deps.logContent` is false) and an `{ ok: false, error }` result the
|
|
77
|
+
* caller surfaces where it matters. That includes a timeout
|
|
78
|
+
* (`deps.timeoutMs`), after which the email may nevertheless have been
|
|
79
|
+
* delivered.
|
|
58
80
|
*/
|
|
59
81
|
export async function sendEmail(msg, deps) {
|
|
60
82
|
const { logger } = deps;
|
|
61
83
|
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
62
84
|
const timeoutMs = deps.timeoutMs ?? DEFAULT_EMAIL_TIMEOUT_MS;
|
|
85
|
+
const logContent = deps.logContent ?? true;
|
|
63
86
|
const base = {
|
|
64
87
|
to: msg.to,
|
|
65
|
-
subject: truncate(msg.subject, 200),
|
|
88
|
+
...(logContent ? { subject: truncate(msg.subject, 200) } : { subjectLength: msg.subject.length }),
|
|
66
89
|
textLength: msg.text?.length ?? 0,
|
|
67
90
|
htmlLength: msg.html?.length ?? 0,
|
|
68
91
|
attachmentCount: msg.attachments?.length ?? 0,
|
|
69
92
|
...(deps.idempotencyKey !== undefined ? { idempotencyKey: deps.idempotencyKey } : {}),
|
|
70
93
|
...deps.context,
|
|
71
94
|
};
|
|
72
|
-
|
|
95
|
+
// Added to a failure's ERROR, where nothing else records what was not sent.
|
|
96
|
+
const preview = logContent ? { text: truncate(msg.text ?? '', 500), html: truncate(msg.html ?? '', 500) } : {};
|
|
73
97
|
if (!msg.text && !msg.html) {
|
|
74
98
|
logger.error('email_rejected_no_body', base);
|
|
75
99
|
return { ok: false, error: 'sendEmail requires a non-empty `text` or `html` body' };
|
|
@@ -96,8 +120,9 @@ export async function sendEmail(msg, deps) {
|
|
|
96
120
|
const body = await res.text().catch(() => '');
|
|
97
121
|
if (!res.ok) {
|
|
98
122
|
const bodyPreview = truncate(body, 500);
|
|
99
|
-
|
|
100
|
-
|
|
123
|
+
const answer = logContent ? { body: bodyPreview } : refusalFacts(body);
|
|
124
|
+
logger.error('email_send_failed', { ...base, status: res.status, ...answer, elapsedMs, ...preview });
|
|
125
|
+
return { ok: false, error: `Resend API ${res.status}: ${bodyPreview}`, status: res.status };
|
|
101
126
|
}
|
|
102
127
|
let emailId;
|
|
103
128
|
try {
|
package/dist/hub/server.d.ts
CHANGED
|
@@ -58,8 +58,9 @@ export interface HubOptions {
|
|
|
58
58
|
};
|
|
59
59
|
};
|
|
60
60
|
/** Passed through to requireIdentity (authUrl, whoamiFetch, verifyClient,
|
|
61
|
-
* rateLimitPerMin…). The hub admits invited users for sockets
|
|
62
|
-
|
|
61
|
+
* rateLimitPerMin…). The hub admits invited users for sockets, and never
|
|
62
|
+
* a guest. */
|
|
63
|
+
identity?: Partial<Omit<RequireIdentityOptions, 'audience' | 'grants' | 'logger' | 'userAccess' | 'guestAccess'>>;
|
|
63
64
|
/** Injectable for tests. */
|
|
64
65
|
bridge?: Partial<Pick<DbBroadcastBridgeOptions, 'heartbeatMs' | 'heartbeatTimeoutMs' | 'reconnectDelaysMs'>>;
|
|
65
66
|
/** Monotonic milliseconds (tests). */
|
package/dist/hub/server.js
CHANGED
|
@@ -85,6 +85,7 @@ export function createHub(app, opts) {
|
|
|
85
85
|
grants: opts.grants,
|
|
86
86
|
logger,
|
|
87
87
|
userAccess: 'invited',
|
|
88
|
+
guestAccess: false,
|
|
88
89
|
});
|
|
89
90
|
const serviceAccount = new RegExp(`^([a-z][a-z0-9-]*)-svc@${escapeRegExp(opts.serviceAccountDomain)}$`);
|
|
90
91
|
if (opts.webSocketServer)
|
package/dist/oauth-resource.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Context } from 'hono';
|
|
2
|
-
import type {
|
|
2
|
+
import type { FullRole, UserAccessPolicy } from './auth.js';
|
|
3
3
|
import type { Logger } from './log-core.js';
|
|
4
4
|
import { serviceFetch } from './s2s.js';
|
|
5
5
|
/** The exact shape of an access token: the prefix plus 32 random bytes in
|
|
@@ -11,7 +11,7 @@ export interface ConnectorUser {
|
|
|
11
11
|
email: string;
|
|
12
12
|
name?: string;
|
|
13
13
|
userId?: string;
|
|
14
|
-
role:
|
|
14
|
+
role: FullRole;
|
|
15
15
|
scopes: ReadonlySet<string>;
|
|
16
16
|
/** The OAuth client the user approved (e.g. Claude's client ID URL). */
|
|
17
17
|
clientId: string;
|
package/dist/oauth-resource.js
CHANGED
|
@@ -13,6 +13,10 @@
|
|
|
13
13
|
// 1. Test bypass (AUTH_MODE=test): X-Test-Connector-User (+ -Role, -Scope).
|
|
14
14
|
// Credential verification is bypassed; the access policy and the app's
|
|
15
15
|
// scope checks still run.
|
|
16
|
+
//
|
|
17
|
+
// A connector user is never a guest (auth.ts): the auth service issues a
|
|
18
|
+
// guest no token, and a 'guest' role in an introspection answer is as
|
|
19
|
+
// malformed as any role outside owner/invited.
|
|
16
20
|
// 2. Authorization: Bearer pwat_… → introspection at the auth service over
|
|
17
21
|
// s2s OIDC, cached in-instance (5 min hits, capped by the token's own
|
|
18
22
|
// expiry / 30 s misses, bounded LRU). Introspections are budgeted per
|
|
@@ -25,7 +29,7 @@
|
|
|
25
29
|
// non-200, a malformed answer) is 503 and is never cached.
|
|
26
30
|
import { createHash } from 'node:crypto';
|
|
27
31
|
import { createMiddleware } from 'hono/factory';
|
|
28
|
-
import { ACCESS_DENIED_CODE, DEFAULT_AUTH_URL, userAllowed } from './auth.js';
|
|
32
|
+
import { ACCESS_DENIED_CODE, DEFAULT_AUTH_URL, parseFullRole, userAllowed } from './auth.js';
|
|
29
33
|
import { authMode } from './config.js';
|
|
30
34
|
import { forwardedClientIp } from './http.js';
|
|
31
35
|
import { RateLimiter, serviceFetch } from './s2s.js';
|
|
@@ -116,9 +120,6 @@ class LruCache {
|
|
|
116
120
|
}
|
|
117
121
|
}
|
|
118
122
|
}
|
|
119
|
-
function parseRole(value) {
|
|
120
|
-
return value === 'owner' || value === 'invited' ? value : undefined;
|
|
121
|
-
}
|
|
122
123
|
function parseScopes(value) {
|
|
123
124
|
return new Set(typeof value === 'string' ? value.split(' ').filter(Boolean) : []);
|
|
124
125
|
}
|
|
@@ -167,11 +168,15 @@ export function requireConnectorUser(opts) {
|
|
|
167
168
|
const email = c.req.header('x-test-connector-user');
|
|
168
169
|
if (!email)
|
|
169
170
|
return unauthorized(c, opts);
|
|
171
|
+
const role = c.req.header('x-test-connector-role');
|
|
172
|
+
// As in production, where a guest holds no connector token.
|
|
173
|
+
if (role === 'guest')
|
|
174
|
+
return unauthorized(c, opts);
|
|
170
175
|
const scope = c.req.header('x-test-connector-scope');
|
|
171
176
|
return admit({
|
|
172
177
|
type: 'connector',
|
|
173
178
|
email,
|
|
174
|
-
role:
|
|
179
|
+
role: parseFullRole(role) ?? 'invited',
|
|
175
180
|
scopes: scope === undefined ? new Set(opts.scopes) : parseScopes(scope),
|
|
176
181
|
clientId: 'test-client',
|
|
177
182
|
grantId: 'test-grant',
|
|
@@ -229,7 +234,7 @@ export function requireConnectorUser(opts) {
|
|
|
229
234
|
opts.logger?.warn('connector token is for another resource', { resource: data.resource });
|
|
230
235
|
return reject();
|
|
231
236
|
}
|
|
232
|
-
const role =
|
|
237
|
+
const role = parseFullRole(data.role);
|
|
233
238
|
const expMs = typeof data.exp === 'number' ? data.exp * 1000 : NaN;
|
|
234
239
|
if (!role ||
|
|
235
240
|
!nonEmptyString(data.email) ||
|
package/package.json
CHANGED