@catamorphic/work-server 0.1.0-alpha.31 → 0.1.0-alpha.33
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 +98 -38
- package/dist/auth/auth-database.d.ts +1 -0
- package/dist/auth/auth-database.d.ts.map +1 -1
- package/dist/auth/fastify-auth.d.ts.map +1 -1
- package/dist/auth/migrate-legacy-oauth.d.ts +14 -0
- package/dist/auth/migrate-legacy-oauth.d.ts.map +1 -0
- package/dist/auth/work-auth-types.d.ts +4 -0
- package/dist/auth/work-auth-types.d.ts.map +1 -1
- package/dist/auth/work-auth.d.ts +2 -0
- package/dist/auth/work-auth.d.ts.map +1 -1
- package/dist/config.d.ts +2 -3
- package/dist/config.d.ts.map +1 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +581 -324
- package/dist/index.js.map +12 -11
- package/dist/server.d.ts +4 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/test-support.d.ts +6 -0
- package/dist/test-support.d.ts.map +1 -1
- package/dist/workers/install-script.d.ts +2 -3
- package/dist/workers/install-script.d.ts.map +1 -1
- package/dist/workers/machine-rules.d.ts.map +1 -1
- package/package.json +21 -19
- package/src/auth/auth-database.ts +33 -3
- package/src/auth/fastify-auth.ts +88 -40
- package/src/auth/migrate-legacy-oauth.ts +238 -0
- package/src/auth/work-auth-types.ts +2 -0
- package/src/auth/work-auth.ts +114 -25
- package/src/config.ts +3 -10
- package/src/index.ts +5 -4
- package/src/server.ts +7 -1
- package/src/test-support.ts +51 -7
- package/src/workers/install-script.ts +4 -5
- package/src/workers/machine-rules.ts +28 -24
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { jsonbText } from "@catamorphic/db";
|
|
3
|
+
import type { BetterAuthOptions } from "better-auth";
|
|
4
|
+
import { symmetricEncrypt } from "better-auth/crypto";
|
|
5
|
+
import { type Kysely, sql } from "kysely";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
|
|
8
|
+
const LegacyClient = z.object({
|
|
9
|
+
id: z.string(),
|
|
10
|
+
clientId: z.string(),
|
|
11
|
+
clientSecret: z.string().nullish(),
|
|
12
|
+
name: z.string().nullish(),
|
|
13
|
+
icon: z.string().nullish(),
|
|
14
|
+
metadata: z.string().nullish(),
|
|
15
|
+
redirectUrls: z.string(),
|
|
16
|
+
type: z.string(),
|
|
17
|
+
disabled: z.boolean().nullish(),
|
|
18
|
+
userId: z.string().nullish(),
|
|
19
|
+
createdAt: z.coerce.date().nullable(),
|
|
20
|
+
updatedAt: z.coerce.date().nullable(),
|
|
21
|
+
});
|
|
22
|
+
const LegacyGrant = z.object({
|
|
23
|
+
id: z.string(),
|
|
24
|
+
clientId: z.string(),
|
|
25
|
+
userId: z.string().nullable(),
|
|
26
|
+
accessToken: z.string(),
|
|
27
|
+
refreshToken: z.string(),
|
|
28
|
+
accessTokenExpiresAt: z.coerce.date(),
|
|
29
|
+
refreshTokenExpiresAt: z.coerce.date(),
|
|
30
|
+
scopes: z.string(),
|
|
31
|
+
createdAt: z.coerce.date(),
|
|
32
|
+
});
|
|
33
|
+
const LegacyConsent = z.object({
|
|
34
|
+
id: z.string(),
|
|
35
|
+
clientId: z.string(),
|
|
36
|
+
userId: z.string(),
|
|
37
|
+
scopes: z.string(),
|
|
38
|
+
consentGiven: z.boolean(),
|
|
39
|
+
createdAt: z.coerce.date(),
|
|
40
|
+
updatedAt: z.coerce.date(),
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
type OAuthMigrationTables = {
|
|
44
|
+
oauthClient: {
|
|
45
|
+
id: string;
|
|
46
|
+
clientId: string;
|
|
47
|
+
clientSecret: string | null;
|
|
48
|
+
name: string | null;
|
|
49
|
+
icon: string | null;
|
|
50
|
+
metadata: unknown;
|
|
51
|
+
redirectUris: unknown;
|
|
52
|
+
tokenEndpointAuthMethod: string;
|
|
53
|
+
requirePKCE: boolean;
|
|
54
|
+
grantTypes: unknown;
|
|
55
|
+
responseTypes: unknown;
|
|
56
|
+
disabled: boolean;
|
|
57
|
+
userId: string | null;
|
|
58
|
+
createdAt: Date | null;
|
|
59
|
+
updatedAt: Date | null;
|
|
60
|
+
};
|
|
61
|
+
oauthResource: {
|
|
62
|
+
id: string;
|
|
63
|
+
identifier: string;
|
|
64
|
+
name: string;
|
|
65
|
+
disabled: boolean;
|
|
66
|
+
};
|
|
67
|
+
oauthClientResource: { id: string; clientId: string; resourceId: string };
|
|
68
|
+
oauthRefreshToken: TokenRow;
|
|
69
|
+
oauthAccessToken: TokenRow & { refreshId: string };
|
|
70
|
+
oauthConsent: {
|
|
71
|
+
id: string;
|
|
72
|
+
clientId: string;
|
|
73
|
+
userId: string;
|
|
74
|
+
resources: unknown;
|
|
75
|
+
scopes: unknown;
|
|
76
|
+
createdAt: Date;
|
|
77
|
+
updatedAt: Date;
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
interface TokenRow {
|
|
81
|
+
id: string;
|
|
82
|
+
token: string;
|
|
83
|
+
clientId: string;
|
|
84
|
+
userId: string | null;
|
|
85
|
+
sessionId: null;
|
|
86
|
+
resources: unknown;
|
|
87
|
+
scopes: unknown;
|
|
88
|
+
expiresAt: Date;
|
|
89
|
+
createdAt: Date;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Convert the private 1.6 OAuth schema in the caller's migration transaction.
|
|
94
|
+
* Reading before dropping also validates every legacy row before any DDL.
|
|
95
|
+
* Dropping the old tables releases their index names for the replacement schema.
|
|
96
|
+
* A failure, including invalid legacy JSON, rolls back the entire upgrade.
|
|
97
|
+
*/
|
|
98
|
+
export async function migrateLegacyOAuth(args: {
|
|
99
|
+
db: Kysely<unknown>;
|
|
100
|
+
resource?: string;
|
|
101
|
+
secret: BetterAuthOptions["secret"];
|
|
102
|
+
}): Promise<() => Promise<void>> {
|
|
103
|
+
const tables = await args.db.introspection.getTables();
|
|
104
|
+
if (!tables.some((table) => table.name === "oauthApplication")) {
|
|
105
|
+
return async () => undefined;
|
|
106
|
+
}
|
|
107
|
+
const { resource, secret } = args;
|
|
108
|
+
if (!resource || typeof secret !== "string") {
|
|
109
|
+
throw new Error(
|
|
110
|
+
"The OAuth upgrade requires Work's resource and auth secret",
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
const clients = z
|
|
114
|
+
.array(LegacyClient)
|
|
115
|
+
.parse((await sql`SELECT * FROM "oauthApplication"`.execute(args.db)).rows);
|
|
116
|
+
const grants = z
|
|
117
|
+
.array(LegacyGrant)
|
|
118
|
+
.parse((await sql`SELECT * FROM "oauthAccessToken"`.execute(args.db)).rows);
|
|
119
|
+
const consents = z
|
|
120
|
+
.array(LegacyConsent)
|
|
121
|
+
.parse((await sql`SELECT * FROM "oauthConsent"`.execute(args.db)).rows);
|
|
122
|
+
// Parse/encrypt before DDL as well: malformed metadata must never be discarded.
|
|
123
|
+
const migratedClients = await Promise.all(
|
|
124
|
+
clients.map(async (client) => {
|
|
125
|
+
const metadata: unknown = client.metadata
|
|
126
|
+
? JSON.parse(client.metadata)
|
|
127
|
+
: null;
|
|
128
|
+
return {
|
|
129
|
+
id: client.id,
|
|
130
|
+
clientId: client.clientId,
|
|
131
|
+
clientSecret:
|
|
132
|
+
client.type === "public" || !client.clientSecret
|
|
133
|
+
? null
|
|
134
|
+
: await symmetricEncrypt({
|
|
135
|
+
key: secret,
|
|
136
|
+
data: client.clientSecret,
|
|
137
|
+
}),
|
|
138
|
+
name: client.name ?? null,
|
|
139
|
+
icon: client.icon ?? null,
|
|
140
|
+
metadata: jsonColumn(metadata),
|
|
141
|
+
redirectUris: jsonColumn(
|
|
142
|
+
client.redirectUrls.split(",").filter(Boolean),
|
|
143
|
+
),
|
|
144
|
+
tokenEndpointAuthMethod:
|
|
145
|
+
client.type === "public" ? "none" : "client_secret_basic",
|
|
146
|
+
requirePKCE: true,
|
|
147
|
+
grantTypes: jsonColumn(["authorization_code", "refresh_token"]),
|
|
148
|
+
responseTypes: jsonColumn(["code"]),
|
|
149
|
+
disabled: client.disabled ?? false,
|
|
150
|
+
userId: client.userId ?? null,
|
|
151
|
+
createdAt: client.createdAt,
|
|
152
|
+
updatedAt: client.updatedAt,
|
|
153
|
+
};
|
|
154
|
+
}),
|
|
155
|
+
);
|
|
156
|
+
await args.db.schema.dropTable("oauthAccessToken").execute();
|
|
157
|
+
await args.db.schema.dropTable("oauthConsent").execute();
|
|
158
|
+
await args.db.schema.dropTable("oauthApplication").execute();
|
|
159
|
+
|
|
160
|
+
return async () => {
|
|
161
|
+
const db = args.db.withTables<OAuthMigrationTables>();
|
|
162
|
+
await db
|
|
163
|
+
.insertInto("oauthResource")
|
|
164
|
+
.values({
|
|
165
|
+
id: randomUUID(),
|
|
166
|
+
identifier: resource,
|
|
167
|
+
name: "Work API",
|
|
168
|
+
disabled: false,
|
|
169
|
+
})
|
|
170
|
+
.onConflict((conflict) => conflict.column("identifier").doNothing())
|
|
171
|
+
.execute();
|
|
172
|
+
for (const client of migratedClients) {
|
|
173
|
+
await db.insertInto("oauthClient").values(client).execute();
|
|
174
|
+
await db
|
|
175
|
+
.insertInto("oauthClientResource")
|
|
176
|
+
.values({
|
|
177
|
+
id: randomUUID(),
|
|
178
|
+
clientId: client.clientId,
|
|
179
|
+
resourceId: resource,
|
|
180
|
+
})
|
|
181
|
+
.execute();
|
|
182
|
+
}
|
|
183
|
+
for (const grant of grants) {
|
|
184
|
+
// Legacy grant IDs anchor Work's existing refresh-family ledger.
|
|
185
|
+
// OAuth grants are independent of the short browser login session.
|
|
186
|
+
const common = {
|
|
187
|
+
id: grant.id,
|
|
188
|
+
clientId: grant.clientId,
|
|
189
|
+
userId: grant.userId,
|
|
190
|
+
sessionId: null,
|
|
191
|
+
resources: jsonColumn([resource]),
|
|
192
|
+
scopes: jsonColumn(grant.scopes.split(/\s+/).filter(Boolean)),
|
|
193
|
+
createdAt: grant.createdAt,
|
|
194
|
+
};
|
|
195
|
+
// Refresh tokens require a user; 1.6 Work only issued user grants.
|
|
196
|
+
if (!grant.userId) throw new Error("Legacy OAuth grant has no user");
|
|
197
|
+
await db
|
|
198
|
+
.insertInto("oauthRefreshToken")
|
|
199
|
+
.values({
|
|
200
|
+
...common,
|
|
201
|
+
token: tokenHash(grant.refreshToken),
|
|
202
|
+
expiresAt: grant.refreshTokenExpiresAt,
|
|
203
|
+
})
|
|
204
|
+
.execute();
|
|
205
|
+
await db
|
|
206
|
+
.insertInto("oauthAccessToken")
|
|
207
|
+
.values({
|
|
208
|
+
...common,
|
|
209
|
+
token: tokenHash(grant.accessToken),
|
|
210
|
+
expiresAt: grant.accessTokenExpiresAt,
|
|
211
|
+
refreshId: grant.id,
|
|
212
|
+
})
|
|
213
|
+
.execute();
|
|
214
|
+
}
|
|
215
|
+
for (const consent of consents.filter((row) => row.consentGiven)) {
|
|
216
|
+
await db
|
|
217
|
+
.insertInto("oauthConsent")
|
|
218
|
+
.values({
|
|
219
|
+
id: consent.id,
|
|
220
|
+
clientId: consent.clientId,
|
|
221
|
+
userId: consent.userId,
|
|
222
|
+
scopes: jsonColumn(consent.scopes.split(/\s+/).filter(Boolean)),
|
|
223
|
+
resources: jsonColumn([resource]),
|
|
224
|
+
createdAt: consent.createdAt,
|
|
225
|
+
updatedAt: consent.updatedAt,
|
|
226
|
+
})
|
|
227
|
+
.execute();
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function jsonColumn(value: unknown) {
|
|
233
|
+
return sql<unknown>`${jsonbText(value)}::jsonb`;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function tokenHash(token: string): string {
|
|
237
|
+
return createHash("sha256").update(token).digest("base64url");
|
|
238
|
+
}
|
|
@@ -28,6 +28,8 @@ export type WorkSignInGate = (args: {
|
|
|
28
28
|
|
|
29
29
|
export interface WorkAuth {
|
|
30
30
|
migrate(): Promise<void>;
|
|
31
|
+
/** Validate the signed authorization query before showing its consent page. */
|
|
32
|
+
verifyAuthorizationQuery(args: { query: string }): Promise<boolean>;
|
|
31
33
|
createLocalUser(args: {
|
|
32
34
|
username: string;
|
|
33
35
|
name: string;
|
package/src/auth/work-auth.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
import { randomBytes } from "node:crypto";
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
|
+
import { mcp } from "@better-auth/mcp";
|
|
5
|
+
import { verifyOAuthQueryParams } from "@better-auth/oauth-provider";
|
|
4
6
|
import { betterAuth } from "better-auth";
|
|
5
|
-
import { bearer, genericOAuth,
|
|
7
|
+
import { bearer, genericOAuth, username } from "better-auth/plugins";
|
|
8
|
+
import { z } from "zod";
|
|
6
9
|
import {
|
|
7
10
|
parseWorkAuthConfig,
|
|
8
11
|
type ResolvedWorkAuthConfig,
|
|
@@ -54,13 +57,17 @@ export function createWorkAuth(options: {
|
|
|
54
57
|
// Starting a provider sign-in guesses nothing: the identity provider
|
|
55
58
|
// authenticates. An office behind one address must not queue for it.
|
|
56
59
|
customRules: {
|
|
57
|
-
"/sign-in/oauth2": PROVIDER_SIGN_IN_LIMIT,
|
|
58
60
|
"/sign-in/social": PROVIDER_SIGN_IN_LIMIT,
|
|
59
61
|
},
|
|
60
62
|
},
|
|
61
63
|
// The Work server resolves the client behind trusted proxies itself;
|
|
62
64
|
// Better Auth sees only headers, never the connection's peer.
|
|
63
|
-
advanced: {
|
|
65
|
+
advanced: {
|
|
66
|
+
ipAddress: { ipAddressHeaders: [CLIENT_ADDRESS_HEADER] },
|
|
67
|
+
// Work migrates under its own transaction/replica lock. An eager
|
|
68
|
+
// vendor check would cache the old schema while that migration runs.
|
|
69
|
+
database: { validateSchema: false },
|
|
70
|
+
},
|
|
64
71
|
plugins: [
|
|
65
72
|
username(),
|
|
66
73
|
bearer(),
|
|
@@ -93,22 +100,33 @@ export function createWorkAuth(options: {
|
|
|
93
100
|
}),
|
|
94
101
|
mcp({
|
|
95
102
|
loginPage: `${options.baseURL}/login`,
|
|
103
|
+
consentPage: `${options.baseURL}/oauth/consent`,
|
|
96
104
|
resource: `${options.baseURL}/api`,
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
105
|
+
// Work checks and revokes opaque grants on every request (ADR 0161).
|
|
106
|
+
disableJwtPlugin: true,
|
|
107
|
+
allowDynamicClientRegistration: true,
|
|
108
|
+
allowUnauthenticatedClientRegistration: true,
|
|
109
|
+
clientRegistrationDefaultApplicationType: "infer",
|
|
110
|
+
clientRegistrationRequirePKCE: true,
|
|
111
|
+
grantTypes: ["authorization_code", "refresh_token"],
|
|
112
|
+
accessTokenExpiresIn: config.sessions.accessTokenSeconds,
|
|
113
|
+
refreshTokenExpiresIn: config.sessions.idleSeconds,
|
|
114
|
+
refreshTokenReuseInterval: 0,
|
|
106
115
|
}),
|
|
107
116
|
],
|
|
108
117
|
});
|
|
109
118
|
|
|
110
119
|
return {
|
|
111
|
-
|
|
120
|
+
verifyAuthorizationQuery: ({ query }) =>
|
|
121
|
+
verifyOAuthQueryParams(query, options.secret),
|
|
122
|
+
migrate: async () => {
|
|
123
|
+
await options.database.migrate({
|
|
124
|
+
options: auth.options,
|
|
125
|
+
resource: `${options.baseURL}/api`,
|
|
126
|
+
});
|
|
127
|
+
// Validate only after the schema and its data conversion have committed.
|
|
128
|
+
await (await auth.$context).explicitSchemaCheck?.();
|
|
129
|
+
},
|
|
112
130
|
createLocalUser: async (args) => {
|
|
113
131
|
if (!config.local.enabled) {
|
|
114
132
|
throw new Error(
|
|
@@ -165,18 +183,39 @@ export function createWorkAuth(options: {
|
|
|
165
183
|
return found ? workAuthUser(found.user) : null;
|
|
166
184
|
},
|
|
167
185
|
resolveAccessToken: async ({ authorization }) => {
|
|
168
|
-
const
|
|
169
|
-
|
|
170
|
-
});
|
|
171
|
-
if (!result?.userId) return null;
|
|
186
|
+
const bearerToken = /^Bearer ([^\s]+)$/i.exec(authorization)?.[1];
|
|
187
|
+
if (!bearerToken) return null;
|
|
172
188
|
const context = await auth.$context;
|
|
173
|
-
const
|
|
189
|
+
const parsed = AccessGrant.safeParse(
|
|
190
|
+
await context.adapter.findOne({
|
|
191
|
+
model: "oauthAccessToken",
|
|
192
|
+
where: [{ field: "token", value: authTokenHash(bearerToken) }],
|
|
193
|
+
}),
|
|
194
|
+
);
|
|
195
|
+
if (!parsed.success) return null;
|
|
196
|
+
const grant = parsed.data;
|
|
197
|
+
if (
|
|
198
|
+
!grant.userId ||
|
|
199
|
+
grant.revoked ||
|
|
200
|
+
!grant.resources?.includes(`${options.baseURL}/api`) ||
|
|
201
|
+
grant.confirmation != null ||
|
|
202
|
+
grant.expiresAt.getTime() <= Date.now()
|
|
203
|
+
)
|
|
204
|
+
return null;
|
|
205
|
+
const client = z.object({ disabled: z.boolean().nullish() }).safeParse(
|
|
206
|
+
await context.adapter.findOne({
|
|
207
|
+
model: "oauthClient",
|
|
208
|
+
where: [{ field: "clientId", value: grant.clientId }],
|
|
209
|
+
}),
|
|
210
|
+
);
|
|
211
|
+
if (!client.success || client.data.disabled === true) return null;
|
|
212
|
+
const user = await context.internalAdapter.findUserById(grant.userId);
|
|
174
213
|
if (!user) return null;
|
|
175
214
|
return {
|
|
176
|
-
userId:
|
|
215
|
+
userId: grant.userId,
|
|
177
216
|
email: user.email,
|
|
178
217
|
emailVerified: user.emailVerified,
|
|
179
|
-
scopes:
|
|
218
|
+
scopes: grant.scopes,
|
|
180
219
|
};
|
|
181
220
|
},
|
|
182
221
|
accountsFor: async ({ userId }) => {
|
|
@@ -192,26 +231,55 @@ export function createWorkAuth(options: {
|
|
|
192
231
|
return toGrant(
|
|
193
232
|
await context.adapter.findOne({
|
|
194
233
|
model: "oauthAccessToken",
|
|
195
|
-
where: [{ field: "
|
|
234
|
+
where: [{ field: "token", value: authTokenHash(accessToken) }],
|
|
196
235
|
}),
|
|
197
236
|
);
|
|
198
237
|
},
|
|
199
238
|
grantByRefreshToken: async ({ refreshToken }) => {
|
|
200
239
|
const context = await auth.$context;
|
|
240
|
+
const refresh = z.object({ id: z.string() }).safeParse(
|
|
241
|
+
await context.adapter.findOne({
|
|
242
|
+
model: "oauthRefreshToken",
|
|
243
|
+
where: [{ field: "token", value: authTokenHash(refreshToken) }],
|
|
244
|
+
}),
|
|
245
|
+
);
|
|
246
|
+
if (!refresh.success) return null;
|
|
201
247
|
return toGrant(
|
|
202
248
|
await context.adapter.findOne({
|
|
203
249
|
model: "oauthAccessToken",
|
|
204
|
-
where: [{ field: "
|
|
250
|
+
where: [{ field: "refreshId", value: refresh.data.id }],
|
|
205
251
|
}),
|
|
206
252
|
);
|
|
207
253
|
},
|
|
208
254
|
deleteGrants: async ({ ids }) => {
|
|
209
255
|
if (ids.length === 0) return;
|
|
210
256
|
const context = await auth.$context;
|
|
257
|
+
const grants = await context.adapter.findMany({
|
|
258
|
+
model: "oauthAccessToken",
|
|
259
|
+
where: [{ field: "id", operator: "in", value: [...ids] }],
|
|
260
|
+
});
|
|
261
|
+
const refreshIds = grants.flatMap((grant) =>
|
|
262
|
+
typeof grant === "object" &&
|
|
263
|
+
grant !== null &&
|
|
264
|
+
"refreshId" in grant &&
|
|
265
|
+
typeof grant.refreshId === "string"
|
|
266
|
+
? [grant.refreshId]
|
|
267
|
+
: [],
|
|
268
|
+
);
|
|
211
269
|
await context.adapter.deleteMany({
|
|
212
270
|
model: "oauthAccessToken",
|
|
213
271
|
where: [{ field: "id", operator: "in", value: [...ids] }],
|
|
214
272
|
});
|
|
273
|
+
if (refreshIds.length) {
|
|
274
|
+
await context.adapter.deleteMany({
|
|
275
|
+
model: "oauthAccessToken",
|
|
276
|
+
where: [{ field: "refreshId", operator: "in", value: refreshIds }],
|
|
277
|
+
});
|
|
278
|
+
await context.adapter.deleteMany({
|
|
279
|
+
model: "oauthRefreshToken",
|
|
280
|
+
where: [{ field: "id", operator: "in", value: refreshIds }],
|
|
281
|
+
});
|
|
282
|
+
}
|
|
215
283
|
},
|
|
216
284
|
signOutEverywhere: async ({ userId }) => {
|
|
217
285
|
const context = await auth.$context;
|
|
@@ -219,6 +287,10 @@ export function createWorkAuth(options: {
|
|
|
219
287
|
model: "oauthAccessToken",
|
|
220
288
|
where: [{ field: "userId", value: userId }],
|
|
221
289
|
});
|
|
290
|
+
await context.adapter.deleteMany({
|
|
291
|
+
model: "oauthRefreshToken",
|
|
292
|
+
where: [{ field: "userId", value: userId }],
|
|
293
|
+
});
|
|
222
294
|
await context.internalAdapter.deleteUserSessions(userId);
|
|
223
295
|
},
|
|
224
296
|
usersSignedIn: async () => {
|
|
@@ -226,9 +298,10 @@ export function createWorkAuth(options: {
|
|
|
226
298
|
const now = new Date();
|
|
227
299
|
const [grants, sessions] = await Promise.all([
|
|
228
300
|
context.adapter.findMany({
|
|
229
|
-
model: "
|
|
301
|
+
model: "oauthRefreshToken",
|
|
230
302
|
where: [
|
|
231
|
-
{ field: "
|
|
303
|
+
{ field: "expiresAt", operator: "gt", value: now },
|
|
304
|
+
{ field: "revoked", value: null },
|
|
232
305
|
],
|
|
233
306
|
}),
|
|
234
307
|
context.adapter.findMany({
|
|
@@ -267,6 +340,22 @@ export function createWorkAuth(options: {
|
|
|
267
340
|
};
|
|
268
341
|
}
|
|
269
342
|
|
|
343
|
+
const AccessGrant = z.object({
|
|
344
|
+
id: z.string(),
|
|
345
|
+
userId: z.string().nullish(),
|
|
346
|
+
clientId: z.string(),
|
|
347
|
+
expiresAt: z.coerce.date(),
|
|
348
|
+
revoked: z.coerce.date().nullish(),
|
|
349
|
+
scopes: z.array(z.string()),
|
|
350
|
+
resources: z.array(z.string()).nullish(),
|
|
351
|
+
confirmation: z.unknown().nullish(),
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
/** Better Auth's default opaque-token storage format. */
|
|
355
|
+
export function authTokenHash(token: string): string {
|
|
356
|
+
return createHash("sha256").update(token).digest("base64url");
|
|
357
|
+
}
|
|
358
|
+
|
|
270
359
|
function toGrant(row: unknown): WorkAuthGrant | null {
|
|
271
360
|
if (typeof row !== "object" || row === null) return null;
|
|
272
361
|
const id = "id" in row ? row.id : undefined;
|
package/src/config.ts
CHANGED
|
@@ -130,9 +130,8 @@ export interface WorkServerConfig {
|
|
|
130
130
|
*/
|
|
131
131
|
hetznerToken?: string;
|
|
132
132
|
/**
|
|
133
|
-
* The worker image
|
|
134
|
-
*
|
|
135
|
-
* its build bakes in.
|
|
133
|
+
* The deployment's own worker image (ADRs 0205, 0294), explicitly
|
|
134
|
+
* supplied here or through `WORK_WORKER_IMAGE`.
|
|
136
135
|
*/
|
|
137
136
|
workerImage?: string;
|
|
138
137
|
}
|
|
@@ -227,13 +226,7 @@ function machineSettingsFromEnv(
|
|
|
227
226
|
});
|
|
228
227
|
if (problem) throw new Error(problem);
|
|
229
228
|
}
|
|
230
|
-
|
|
231
|
-
// is (both baked in at build time); machines run that same image.
|
|
232
|
-
const repository = env.WORK_IMAGE_REPOSITORY?.trim();
|
|
233
|
-
const version = env.WORK_VERSION?.trim();
|
|
234
|
-
const workerImage =
|
|
235
|
-
env.WORK_WORKER_IMAGE?.trim() ||
|
|
236
|
-
(repository && version ? `${repository}:${version}` : undefined);
|
|
229
|
+
const workerImage = env.WORK_WORKER_IMAGE?.trim();
|
|
237
230
|
return {
|
|
238
231
|
...(machines ? { machines } : {}),
|
|
239
232
|
...(hetznerToken ? { hetznerToken } : {}),
|
package/src/index.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The Work server as a library (
|
|
3
|
-
* `createWorkServer({ config
|
|
4
|
-
*
|
|
5
|
-
*
|
|
2
|
+
* The Work server as a library (ADRs 0160, 0294). A deployment owns its
|
|
3
|
+
* entry point and image, calling `createWorkServer({ config, hooks })`.
|
|
4
|
+
* `apps/server/src/index.ts` is reference source; config is typed data,
|
|
5
|
+
* hooks are code (ADR 0183).
|
|
6
6
|
*/
|
|
7
7
|
// What a company's own server file needs (ADR 0261), from one package.
|
|
8
8
|
export {
|
|
@@ -15,6 +15,7 @@ export {
|
|
|
15
15
|
type ModelRequestRewrite,
|
|
16
16
|
} from "@catamorphic/core";
|
|
17
17
|
export {
|
|
18
|
+
defineCapability,
|
|
18
19
|
defineGitConnectionProvider,
|
|
19
20
|
defineHttpApiConnectionProvider,
|
|
20
21
|
defineModelConnectionProvider,
|
package/src/server.ts
CHANGED
|
@@ -34,6 +34,7 @@ import {
|
|
|
34
34
|
aiToolKind,
|
|
35
35
|
builtinModelConnectionProviders,
|
|
36
36
|
type Catamorphic,
|
|
37
|
+
type CreateCatamorphicConfig,
|
|
37
38
|
connectionAuthorizationPage,
|
|
38
39
|
createCatamorphic,
|
|
39
40
|
DIRECTORY_TRIGGER_KINDS,
|
|
@@ -138,7 +139,7 @@ import { WorkWorkerRegistry } from "./workers/worker-registry.js";
|
|
|
138
139
|
import { registerWorkerRoutes } from "./workers/worker-routes.js";
|
|
139
140
|
|
|
140
141
|
/**
|
|
141
|
-
* The Work server,
|
|
142
|
+
* The Work server, a composable Catamorphic host (ADR 0059, 0159): everything on disk under one
|
|
142
143
|
* data dir, zero external services. PGlite for the database, bare git
|
|
143
144
|
* repos for project origins, local-process execution (the container is
|
|
144
145
|
* the sandbox, single-tenant only per ADR 0047), Work server OAuth, and ordinary
|
|
@@ -156,6 +157,8 @@ const SETUP_AGENT_USER = "work-setup-agent";
|
|
|
156
157
|
*/
|
|
157
158
|
export interface WorkServerHooks {
|
|
158
159
|
agentCapabilities?: AgentCapabilityOptions;
|
|
160
|
+
/** Workflow host calls and run capabilities, using the existing SDK contract. */
|
|
161
|
+
capabilityProviders?: CreateCatamorphicConfig["capabilityProviders"];
|
|
159
162
|
/** Added to the connections declared in `config.gateway`. */
|
|
160
163
|
connectionProviders?: readonly ConnectionProvider[];
|
|
161
164
|
/**
|
|
@@ -575,6 +578,9 @@ async function createWorkServerInner(
|
|
|
575
578
|
);
|
|
576
579
|
const catamorphic = createCatamorphic({
|
|
577
580
|
hostId,
|
|
581
|
+
...(hooks.capabilityProviders
|
|
582
|
+
? { capabilityProviders: hooks.capabilityProviders }
|
|
583
|
+
: {}),
|
|
578
584
|
agentCapabilities: workAgentCapabilities({
|
|
579
585
|
core: () => catamorphic.core,
|
|
580
586
|
auth: () => workAuth,
|
package/src/test-support.ts
CHANGED
|
@@ -124,6 +124,40 @@ interface InjectableApp {
|
|
|
124
124
|
}>;
|
|
125
125
|
}
|
|
126
126
|
|
|
127
|
+
/** Accept the signed authorization prompt before exchanging the code. */
|
|
128
|
+
export async function acceptOAuthConsent(args: {
|
|
129
|
+
app: InjectableApp;
|
|
130
|
+
location: string;
|
|
131
|
+
cookie: string;
|
|
132
|
+
}): Promise<string> {
|
|
133
|
+
const consent = new URL(args.location);
|
|
134
|
+
if (consent.pathname !== "/oauth/consent") return args.location;
|
|
135
|
+
const page = await args.app.inject({
|
|
136
|
+
method: "GET",
|
|
137
|
+
url: `${consent.pathname}${consent.search}`,
|
|
138
|
+
headers: { cookie: args.cookie },
|
|
139
|
+
});
|
|
140
|
+
if (page.statusCode !== 200) {
|
|
141
|
+
throw new Error(`consent page answered ${page.statusCode}, expected 200`);
|
|
142
|
+
}
|
|
143
|
+
const accepted = await args.app.inject({
|
|
144
|
+
method: "POST",
|
|
145
|
+
url: "/oauth/consent",
|
|
146
|
+
headers: {
|
|
147
|
+
cookie: args.cookie,
|
|
148
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
149
|
+
},
|
|
150
|
+
payload: new URLSearchParams({
|
|
151
|
+
accept: "true",
|
|
152
|
+
oauth_query: consent.search.slice(1),
|
|
153
|
+
}).toString(),
|
|
154
|
+
});
|
|
155
|
+
if (accepted.statusCode !== 302) {
|
|
156
|
+
throw new Error(`consent answered ${accepted.statusCode}, expected 302`);
|
|
157
|
+
}
|
|
158
|
+
return String(accepted.headers.location ?? "");
|
|
159
|
+
}
|
|
160
|
+
|
|
127
161
|
/**
|
|
128
162
|
* The OAuth flow an MCP client runs, in process: local sign-in, dynamic
|
|
129
163
|
* client registration, PKCE authorization, and the code exchange.
|
|
@@ -134,6 +168,13 @@ export async function oauthAccessToken(args: {
|
|
|
134
168
|
password: string;
|
|
135
169
|
}): Promise<string> {
|
|
136
170
|
const { app } = args;
|
|
171
|
+
const resourceMetadata = await app.inject({
|
|
172
|
+
method: "GET",
|
|
173
|
+
url: "/.well-known/oauth-protected-resource",
|
|
174
|
+
});
|
|
175
|
+
const resource = resourceMetadata.json().resource;
|
|
176
|
+
if (typeof resource !== "string")
|
|
177
|
+
throw new Error("Missing Work resource metadata");
|
|
137
178
|
const expectStatus = (step: string, actual: number, expected: number) => {
|
|
138
179
|
if (actual !== expected)
|
|
139
180
|
throw new Error(`${step} answered ${actual}, expected ${expected}`);
|
|
@@ -150,7 +191,7 @@ export async function oauthAccessToken(args: {
|
|
|
150
191
|
const redirectUri = "http://127.0.0.1:49152/callback";
|
|
151
192
|
const registered = await app.inject({
|
|
152
193
|
method: "POST",
|
|
153
|
-
url: "/api/auth/
|
|
194
|
+
url: "/api/auth/oauth2/register",
|
|
154
195
|
payload: {
|
|
155
196
|
redirect_uris: [redirectUri],
|
|
156
197
|
token_endpoint_auth_method: "none",
|
|
@@ -167,6 +208,7 @@ export async function oauthAccessToken(args: {
|
|
|
167
208
|
client_id: clientId,
|
|
168
209
|
redirect_uri: redirectUri,
|
|
169
210
|
response_type: "code",
|
|
211
|
+
resource,
|
|
170
212
|
scope: "openid profile email offline_access",
|
|
171
213
|
state: "work-server-state",
|
|
172
214
|
code_challenge: challenge,
|
|
@@ -174,18 +216,20 @@ export async function oauthAccessToken(args: {
|
|
|
174
216
|
});
|
|
175
217
|
const authorized = await app.inject({
|
|
176
218
|
method: "GET",
|
|
177
|
-
url: `/api/auth/
|
|
219
|
+
url: `/api/auth/oauth2/authorize?${authorize}`,
|
|
178
220
|
headers: { cookie },
|
|
179
221
|
});
|
|
180
222
|
expectStatus("authorization", authorized.statusCode, 302);
|
|
181
|
-
const
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
223
|
+
const callback = await acceptOAuthConsent({
|
|
224
|
+
app,
|
|
225
|
+
location: String(authorized.headers.location ?? ""),
|
|
226
|
+
cookie,
|
|
227
|
+
});
|
|
228
|
+
const code = new URL(callback).searchParams.get("code") ?? "";
|
|
185
229
|
|
|
186
230
|
const token = await app.inject({
|
|
187
231
|
method: "POST",
|
|
188
|
-
url: "/api/auth/
|
|
232
|
+
url: "/api/auth/oauth2/token",
|
|
189
233
|
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
190
234
|
payload: new URLSearchParams({
|
|
191
235
|
grant_type: "authorization_code",
|