@parlor/auth 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +25 -2
- package/dist/account.d.ts +59 -0
- package/dist/account.d.ts.map +1 -0
- package/dist/account.js +127 -0
- package/dist/account.js.map +1 -0
- package/dist/audit.d.ts +10 -0
- package/dist/audit.d.ts.map +1 -0
- package/dist/audit.js +130 -0
- package/dist/audit.js.map +1 -0
- package/dist/better-auth.d.ts +46 -0
- package/dist/better-auth.d.ts.map +1 -0
- package/dist/better-auth.js +120 -0
- package/dist/better-auth.js.map +1 -0
- package/dist/client/index.d.ts +79 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +554 -0
- package/dist/client/index.js.map +1 -0
- package/dist/database.d.ts +7 -0
- package/dist/database.d.ts.map +1 -0
- package/dist/database.js +11 -0
- package/dist/database.js.map +1 -0
- package/dist/devices.d.ts +157 -0
- package/dist/devices.d.ts.map +1 -0
- package/dist/devices.js +403 -0
- package/dist/devices.js.map +1 -0
- package/dist/es256.d.ts +4 -0
- package/dist/es256.d.ts.map +1 -0
- package/dist/es256.js +44 -0
- package/dist/es256.js.map +1 -0
- package/dist/grants.d.ts +4 -0
- package/dist/grants.d.ts.map +1 -0
- package/dist/grants.js +6 -0
- package/dist/grants.js.map +1 -0
- package/dist/hosts.d.ts +116 -0
- package/dist/hosts.d.ts.map +1 -0
- package/dist/hosts.js +538 -0
- package/dist/hosts.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/migrations.d.ts +3 -0
- package/dist/migrations.d.ts.map +1 -0
- package/dist/migrations.js +17 -0
- package/dist/migrations.js.map +1 -0
- package/dist/native-sign-in.d.ts +45 -0
- package/dist/native-sign-in.d.ts.map +1 -0
- package/dist/native-sign-in.js +183 -0
- package/dist/native-sign-in.js.map +1 -0
- package/dist/pages.d.ts +4 -0
- package/dist/pages.d.ts.map +1 -0
- package/dist/pages.js +53 -0
- package/dist/pages.js.map +1 -0
- package/dist/provider.d.ts +81 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +301 -0
- package/dist/provider.js.map +1 -0
- package/dist/revocation.d.ts +51 -0
- package/dist/revocation.d.ts.map +1 -0
- package/dist/revocation.js +233 -0
- package/dist/revocation.js.map +1 -0
- package/dist/routes.d.ts +15 -0
- package/dist/routes.d.ts.map +1 -0
- package/dist/routes.js +116 -0
- package/dist/routes.js.map +1 -0
- package/dist/schema.d.ts +2970 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +308 -0
- package/dist/schema.js.map +1 -0
- package/dist/statements.d.ts +92 -0
- package/dist/statements.d.ts.map +1 -0
- package/dist/statements.js +199 -0
- package/dist/statements.js.map +1 -0
- package/dist/tokens.d.ts +69 -0
- package/dist/tokens.d.ts.map +1 -0
- package/dist/tokens.js +134 -0
- package/dist/tokens.js.map +1 -0
- package/dist/turn-keys.d.ts +16 -0
- package/dist/turn-keys.d.ts.map +1 -0
- package/dist/turn-keys.js +108 -0
- package/dist/turn-keys.js.map +1 -0
- package/package.json +57 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 cychien
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,26 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @parlor/auth
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Sign-in for Parlor apps on Better Auth: sessions, per-user scopes, OAuth for MCP clients, and pairing a computer's agents with an account.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pnpm parlor add auth
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
`parlor add auth` installs this package and writes the wiring. The server side it writes:
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { betterAuthProvider, parlorAuth } from "@parlor/auth";
|
|
13
|
+
import { betterAuth } from "better-auth";
|
|
14
|
+
|
|
15
|
+
export const auth = betterAuthProvider({
|
|
16
|
+
instance: betterAuth(
|
|
17
|
+
parlorAuth({
|
|
18
|
+
appName: "Todos",
|
|
19
|
+
signInPage: "/sign-in",
|
|
20
|
+
emailAndPassword: { enabled: true },
|
|
21
|
+
}),
|
|
22
|
+
),
|
|
23
|
+
});
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Docs: https://cychien.github.io/parlor/guides/auth/
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { type ActionContext, type UserPrincipal } from "@parlor/core";
|
|
2
|
+
import { type ActionsOf } from "@parlor/core/registry";
|
|
3
|
+
import type { PluginCaller, PluginHost } from "@parlor/server";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import type { DeviceAccountActions } from "./devices.js";
|
|
6
|
+
import type { HostAccountActions } from "./hosts.js";
|
|
7
|
+
import type { BetterAuthInstance } from "./provider.js";
|
|
8
|
+
import type { RevocationNotice } from "./revocation.js";
|
|
9
|
+
export declare const SESSIONS_TAG = "parlor_auth_sessions";
|
|
10
|
+
export declare const AGENTS_TAG = "parlor_auth_agents";
|
|
11
|
+
export interface SignedInSession {
|
|
12
|
+
readonly id: string;
|
|
13
|
+
readonly current: boolean;
|
|
14
|
+
readonly userAgent: string | null;
|
|
15
|
+
readonly ipAddress: string | null;
|
|
16
|
+
readonly createdAt: string;
|
|
17
|
+
readonly lastActiveAt: string;
|
|
18
|
+
}
|
|
19
|
+
export interface ConnectedAgent {
|
|
20
|
+
readonly clientId: string;
|
|
21
|
+
readonly name: string;
|
|
22
|
+
readonly scopes: readonly string[];
|
|
23
|
+
readonly connectedAt: string;
|
|
24
|
+
}
|
|
25
|
+
export type AccountActions = ActionsOf<ReturnType<typeof accountActions>> & HostAccountActions & DeviceAccountActions;
|
|
26
|
+
interface AccountDeps {
|
|
27
|
+
readonly instance: BetterAuthInstance;
|
|
28
|
+
readonly host: PluginHost;
|
|
29
|
+
readonly revoke: (notice: RevocationNotice) => Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
export declare function signedIn(ctx: ActionContext): UserPrincipal;
|
|
32
|
+
/**
|
|
33
|
+
* Computers and device keys exist only for the chat, so a user its `access` refuses can
|
|
34
|
+
* pair neither; removing what they already have stays open.
|
|
35
|
+
*/
|
|
36
|
+
export declare function chatAllows(host: PluginHost, caller: PluginCaller): Promise<boolean>;
|
|
37
|
+
export declare const CHAT_REFUSED = "This account cannot use the agent.";
|
|
38
|
+
export declare function requireChat(host: PluginHost, ctx: ActionContext): Promise<void>;
|
|
39
|
+
/**
|
|
40
|
+
* Plugin actions at `/_parlor/auth/actions/<name>`. Better Auth writes through its own
|
|
41
|
+
* connection, so these never run inside an action transaction (on PGlite that would
|
|
42
|
+
* deadlock) and announce their changes afterwards instead of declaring `writes`.
|
|
43
|
+
*/
|
|
44
|
+
export declare function accountActions({ instance, host, revoke }: AccountDeps): import("@parlor/core/registry").ActionRegistry<{
|
|
45
|
+
sessions: import("@parlor/core").ActionDefinition<z.ZodObject<{}, z.core.$strip>, SignedInSession[]>;
|
|
46
|
+
revokeSession: import("@parlor/core").ActionDefinition<z.ZodObject<{
|
|
47
|
+
id: z.ZodString;
|
|
48
|
+
}, z.core.$strip>, {
|
|
49
|
+
id: string;
|
|
50
|
+
}>;
|
|
51
|
+
agents: import("@parlor/core").ActionDefinition<z.ZodObject<{}, z.core.$strip>, ConnectedAgent[]>;
|
|
52
|
+
revokeAgent: import("@parlor/core").ActionDefinition<z.ZodObject<{
|
|
53
|
+
clientId: z.ZodString;
|
|
54
|
+
}, z.core.$strip>, {
|
|
55
|
+
id: string;
|
|
56
|
+
}>;
|
|
57
|
+
}>;
|
|
58
|
+
export {};
|
|
59
|
+
//# sourceMappingURL=account.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"account.d.ts","sourceRoot":"","sources":["../src/account.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,aAAa,EAElB,KAAK,aAAa,EACnB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,KAAK,SAAS,EAAkB,MAAM,uBAAuB,CAAC;AACvE,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC/D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAEzD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AACxD,OAAO,KAAK,EAAE,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E,UAAU,EAAE,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAErF;AAKD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,WAAW;;;;;;;;;;;;;GAiGrE"}
|
package/dist/account.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { CHAT_PLUGIN } from "@parlor/chat";
|
|
2
|
+
import { ActionError, defineAction, } from "@parlor/core";
|
|
3
|
+
import { createRegistry } from "@parlor/core/registry";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { grantIdOf } from "./grants.js";
|
|
6
|
+
export const SESSIONS_TAG = "parlor_auth_sessions";
|
|
7
|
+
export const AGENTS_TAG = "parlor_auth_agents";
|
|
8
|
+
export function signedIn(ctx) {
|
|
9
|
+
if (ctx.principal.kind !== "user") {
|
|
10
|
+
throw new ActionError("forbidden", "Only a signed-in user manages the account.");
|
|
11
|
+
}
|
|
12
|
+
return ctx.principal;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Computers and device keys exist only for the chat, so a user its `access` refuses can
|
|
16
|
+
* pair neither; removing what they already have stays open.
|
|
17
|
+
*/
|
|
18
|
+
export async function chatAllows(host, caller) {
|
|
19
|
+
return (await host.allows?.(CHAT_PLUGIN, caller)) ?? true;
|
|
20
|
+
}
|
|
21
|
+
export const CHAT_REFUSED = "This account cannot use the agent.";
|
|
22
|
+
export async function requireChat(host, ctx) {
|
|
23
|
+
if (!(await chatAllows(host, ctx)))
|
|
24
|
+
throw new ActionError("forbidden", CHAT_REFUSED);
|
|
25
|
+
}
|
|
26
|
+
const scopesOf = (scopes) => typeof scopes === "string" ? scopes.split(" ").filter(Boolean) : [...scopes];
|
|
27
|
+
/**
|
|
28
|
+
* Plugin actions at `/_parlor/auth/actions/<name>`. Better Auth writes through its own
|
|
29
|
+
* connection, so these never run inside an action transaction (on PGlite that would
|
|
30
|
+
* deadlock) and announce their changes afterwards instead of declaring `writes`.
|
|
31
|
+
*/
|
|
32
|
+
export function accountActions({ instance, host, revoke }) {
|
|
33
|
+
return createRegistry({
|
|
34
|
+
sessions: defineAction({
|
|
35
|
+
description: "List the places this account is signed in.",
|
|
36
|
+
input: z.object({}),
|
|
37
|
+
reads: [SESSIONS_TAG],
|
|
38
|
+
run: async (_input, ctx) => {
|
|
39
|
+
const user = signedIn(ctx);
|
|
40
|
+
const { internalAdapter } = await instance.$context;
|
|
41
|
+
const sessions = await internalAdapter.listSessions(user.userId);
|
|
42
|
+
return sessions
|
|
43
|
+
.filter((session) => session.expiresAt.getTime() > Date.now())
|
|
44
|
+
.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())
|
|
45
|
+
.map((session) => ({
|
|
46
|
+
id: session.id,
|
|
47
|
+
current: session.id === user.sessionId,
|
|
48
|
+
userAgent: session.userAgent ?? null,
|
|
49
|
+
ipAddress: session.ipAddress ?? null,
|
|
50
|
+
createdAt: session.createdAt.toISOString(),
|
|
51
|
+
lastActiveAt: session.updatedAt.toISOString(),
|
|
52
|
+
}));
|
|
53
|
+
},
|
|
54
|
+
}),
|
|
55
|
+
revokeSession: defineAction({
|
|
56
|
+
description: "Sign this account out of one place; its open connections close.",
|
|
57
|
+
input: z.object({ id: z.string().min(1) }),
|
|
58
|
+
run: async ({ id }, ctx) => {
|
|
59
|
+
const user = signedIn(ctx);
|
|
60
|
+
const { internalAdapter } = await instance.$context;
|
|
61
|
+
const sessions = await internalAdapter.listSessions(user.userId);
|
|
62
|
+
const session = sessions.find((candidate) => candidate.id === id);
|
|
63
|
+
if (!session)
|
|
64
|
+
throw new ActionError("not_found", `No session ${id}`);
|
|
65
|
+
await internalAdapter.deleteSession(session.token);
|
|
66
|
+
await host.announce(ctx.scope, [[SESSIONS_TAG, id]]);
|
|
67
|
+
return { id };
|
|
68
|
+
},
|
|
69
|
+
}),
|
|
70
|
+
agents: defineAction({
|
|
71
|
+
description: "List the agents this account authorized through MCP.",
|
|
72
|
+
input: z.object({}),
|
|
73
|
+
reads: [AGENTS_TAG],
|
|
74
|
+
run: async (_input, ctx) => {
|
|
75
|
+
const user = signedIn(ctx);
|
|
76
|
+
const { adapter } = await instance.$context;
|
|
77
|
+
const mine = [{ field: "userId", value: user.userId }];
|
|
78
|
+
const [consents, refreshTokens] = await Promise.all([
|
|
79
|
+
adapter.findMany({ model: "oauthConsent", where: mine }),
|
|
80
|
+
adapter.findMany({
|
|
81
|
+
model: "oauthRefreshToken",
|
|
82
|
+
where: mine,
|
|
83
|
+
}),
|
|
84
|
+
]);
|
|
85
|
+
// A trusted client skips consent, so its live refresh tokens are its only trace.
|
|
86
|
+
const live = refreshTokens.filter((token) => !token.revoked && token.expiresAt.getTime() > Date.now());
|
|
87
|
+
const grants = new Map();
|
|
88
|
+
for (const grant of [...live, ...consents]) {
|
|
89
|
+
const known = grants.get(grant.clientId);
|
|
90
|
+
if (!known || grant.createdAt < known.createdAt)
|
|
91
|
+
grants.set(grant.clientId, grant);
|
|
92
|
+
}
|
|
93
|
+
return Promise.all([...grants.values()].map(async (grant) => {
|
|
94
|
+
const client = await adapter.findOne({
|
|
95
|
+
model: "oauthClient",
|
|
96
|
+
where: [{ field: "clientId", value: grant.clientId }],
|
|
97
|
+
});
|
|
98
|
+
return {
|
|
99
|
+
clientId: grant.clientId,
|
|
100
|
+
name: client?.name || grant.clientId,
|
|
101
|
+
scopes: scopesOf(grant.scopes),
|
|
102
|
+
connectedAt: grant.createdAt.toISOString(),
|
|
103
|
+
};
|
|
104
|
+
}));
|
|
105
|
+
},
|
|
106
|
+
}),
|
|
107
|
+
revokeAgent: defineAction({
|
|
108
|
+
description: "Revoke an agent's access; its tokens stop working at once.",
|
|
109
|
+
input: z.object({ clientId: z.string().min(1) }),
|
|
110
|
+
run: async ({ clientId }, ctx) => {
|
|
111
|
+
const user = signedIn(ctx);
|
|
112
|
+
await revoke({ kind: "grant", id: grantIdOf(user.userId, clientId) });
|
|
113
|
+
const { adapter } = await instance.$context;
|
|
114
|
+
const where = [
|
|
115
|
+
{ field: "userId", value: user.userId },
|
|
116
|
+
{ field: "clientId", value: clientId },
|
|
117
|
+
];
|
|
118
|
+
for (const model of ["oauthConsent", "oauthRefreshToken", "oauthAccessToken"]) {
|
|
119
|
+
await adapter.deleteMany({ model, where });
|
|
120
|
+
}
|
|
121
|
+
await host.announce(ctx.scope, [[AGENTS_TAG, clientId]]);
|
|
122
|
+
return { id: clientId };
|
|
123
|
+
},
|
|
124
|
+
}),
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
//# sourceMappingURL=account.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"account.js","sourceRoot":"","sources":["../src/account.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EACL,WAAW,EAEX,YAAY,GAEb,MAAM,cAAc,CAAC;AACtB,OAAO,EAAkB,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEvE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAKxC,MAAM,CAAC,MAAM,YAAY,GAAG,sBAAsB,CAAC;AACnD,MAAM,CAAC,MAAM,UAAU,GAAG,oBAAoB,CAAC;AAuC/C,MAAM,UAAU,QAAQ,CAAC,GAAkB;IACzC,IAAI,GAAG,CAAC,SAAS,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;QAClC,MAAM,IAAI,WAAW,CAAC,WAAW,EAAE,4CAA4C,CAAC,CAAC;IACnF,CAAC;IACD,OAAO,GAAG,CAAC,SAAS,CAAC;AACvB,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAC9B,IAAgB,EAChB,MAAoB;IAEpB,OAAO,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC,IAAI,IAAI,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AC3B,MAAM,MAAM,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,EAAE,SAAS,CAAC,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE,CAAC,CAAC;gBACtE,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,QAAQ,CAAC,QAAQ,CAAC;gBAC5C,MAAM,KAAK,GAAG;oBACZ,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,CAAC,MAAM,EAAE;oBACvC,EAAE,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,QAAQ,EAAE;iBACvC,CAAC;gBACF,KAAK,MAAM,KAAK,IAAI,CAAC,cAAc,EAAE,mBAAmB,EAAE,kBAAkB,CAAC,EAAE,CAAC;oBAC9E,MAAM,OAAO,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;gBAC7C,CAAC;gBACD,MAAM,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;gBACzD,OAAO,EAAE,EAAE,EAAE,QAAQ,EAAE,CAAC;YAC1B,CAAC;SACF,CAAC;KACH,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { CHAT_PLUGIN } from \"@parlor/chat\";\nimport {\n ActionError,\n type ActionContext,\n defineAction,\n type UserPrincipal,\n} from \"@parlor/core\";\nimport { type ActionsOf, createRegistry } from \"@parlor/core/registry\";\nimport type { PluginCaller, PluginHost } from \"@parlor/server\";\nimport { z } from \"zod\";\n\nimport type { DeviceAccountActions } from \"./devices.js\";\nimport { grantIdOf } from \"./grants.js\";\nimport type { HostAccountActions } from \"./hosts.js\";\nimport type { BetterAuthInstance } from \"./provider.js\";\nimport type { RevocationNotice } from \"./revocation.js\";\n\nexport const SESSIONS_TAG = \"parlor_auth_sessions\";\nexport const AGENTS_TAG = \"parlor_auth_agents\";\n\nexport interface SignedInSession {\n readonly id: string;\n readonly current: boolean;\n readonly userAgent: string | null;\n readonly ipAddress: string | null;\n readonly createdAt: string;\n readonly lastActiveAt: string;\n}\n\nexport interface ConnectedAgent {\n readonly clientId: string;\n readonly name: string;\n readonly scopes: readonly string[];\n readonly connectedAt: string;\n}\n\ninterface Grant {\n readonly clientId: string;\n readonly scopes: string | readonly string[];\n readonly createdAt: Date;\n}\n\ninterface RefreshToken {\n readonly revoked?: Date | null;\n readonly expiresAt: Date;\n}\n\nexport type AccountActions = ActionsOf<ReturnType<typeof accountActions>> &\n HostAccountActions &\n DeviceAccountActions;\n\ninterface AccountDeps {\n readonly instance: BetterAuthInstance;\n readonly host: PluginHost;\n readonly revoke: (notice: RevocationNotice) => Promise<void>;\n}\n\nexport function signedIn(ctx: ActionContext): UserPrincipal {\n if (ctx.principal.kind !== \"user\") {\n throw new ActionError(\"forbidden\", \"Only a signed-in user manages the account.\");\n }\n return ctx.principal;\n}\n\n/**\n * Computers and device keys exist only for the chat, so a user its `access` refuses can\n * pair neither; removing what they already have stays open.\n */\nexport async function chatAllows(\n host: PluginHost,\n caller: PluginCaller,\n): Promise<boolean> {\n return (await host.allows?.(CHAT_PLUGIN, caller)) ?? true;\n}\n\nexport const CHAT_REFUSED = \"This account cannot use the agent.\";\n\nexport async function requireChat(host: PluginHost, ctx: ActionContext): Promise<void> {\n if (!(await chatAllows(host, ctx))) throw new ActionError(\"forbidden\", CHAT_REFUSED);\n}\n\nconst scopesOf = (scopes: Grant[\"scopes\"]) =>\n typeof scopes === \"string\" ? scopes.split(\" \").filter(Boolean) : [...scopes];\n\n/**\n * Plugin actions at `/_parlor/auth/actions/<name>`. Better Auth writes through its own\n * connection, so these never run inside an action transaction (on PGlite that would\n * deadlock) and announce their changes afterwards instead of declaring `writes`.\n */\nexport function accountActions({ instance, host, revoke }: AccountDeps) {\n return createRegistry({\n sessions: defineAction({\n description: \"List the places this account is signed in.\",\n input: z.object({}),\n reads: [SESSIONS_TAG],\n run: async (_input, ctx): Promise<SignedInSession[]> => {\n const user = signedIn(ctx);\n const { internalAdapter } = await instance.$context;\n const sessions = await internalAdapter.listSessions(user.userId);\n return sessions\n .filter((session) => session.expiresAt.getTime() > Date.now())\n .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())\n .map((session) => ({\n id: session.id,\n current: session.id === user.sessionId,\n userAgent: session.userAgent ?? null,\n ipAddress: session.ipAddress ?? null,\n createdAt: session.createdAt.toISOString(),\n lastActiveAt: session.updatedAt.toISOString(),\n }));\n },\n }),\n revokeSession: defineAction({\n description: \"Sign this account out of one place; its open connections close.\",\n input: z.object({ id: z.string().min(1) }),\n run: async ({ id }, ctx) => {\n const user = signedIn(ctx);\n const { internalAdapter } = await instance.$context;\n const sessions = await internalAdapter.listSessions(user.userId);\n const session = sessions.find((candidate) => candidate.id === id);\n if (!session) throw new ActionError(\"not_found\", `No session ${id}`);\n await internalAdapter.deleteSession(session.token);\n await host.announce(ctx.scope, [[SESSIONS_TAG, id]]);\n return { id };\n },\n }),\n agents: defineAction({\n description: \"List the agents this account authorized through MCP.\",\n input: z.object({}),\n reads: [AGENTS_TAG],\n run: async (_input, ctx): Promise<ConnectedAgent[]> => {\n const user = signedIn(ctx);\n const { adapter } = await instance.$context;\n const mine = [{ field: \"userId\", value: user.userId }];\n const [consents, refreshTokens] = await Promise.all([\n adapter.findMany<Grant>({ model: \"oauthConsent\", where: mine }),\n adapter.findMany<Grant & RefreshToken>({\n model: \"oauthRefreshToken\",\n where: mine,\n }),\n ]);\n // A trusted client skips consent, so its live refresh tokens are its only trace.\n const live = refreshTokens.filter(\n (token) => !token.revoked && token.expiresAt.getTime() > Date.now(),\n );\n const grants = new Map<string, Grant>();\n for (const grant of [...live, ...consents]) {\n const known = grants.get(grant.clientId);\n if (!known || grant.createdAt < known.createdAt)\n grants.set(grant.clientId, grant);\n }\n return Promise.all(\n [...grants.values()].map(async (grant) => {\n const client = await adapter.findOne<{ name?: string | null }>({\n model: \"oauthClient\",\n where: [{ field: \"clientId\", value: grant.clientId }],\n });\n return {\n clientId: grant.clientId,\n name: client?.name || grant.clientId,\n scopes: scopesOf(grant.scopes),\n connectedAt: grant.createdAt.toISOString(),\n };\n }),\n );\n },\n }),\n revokeAgent: defineAction({\n description: \"Revoke an agent's access; its tokens stop working at once.\",\n input: z.object({ clientId: z.string().min(1) }),\n run: async ({ clientId }, ctx) => {\n const user = signedIn(ctx);\n await revoke({ kind: \"grant\", id: grantIdOf(user.userId, clientId) });\n const { adapter } = await instance.$context;\n const where = [\n { field: \"userId\", value: user.userId },\n { field: \"clientId\", value: clientId },\n ];\n for (const model of [\"oauthConsent\", \"oauthRefreshToken\", \"oauthAccessToken\"]) {\n await adapter.deleteMany({ model, where });\n }\n await host.announce(ctx.scope, [[AGENTS_TAG, clientId]]);\n return { id: clientId };\n },\n }),\n });\n}\n"]}
|
package/dist/audit.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { DataProvider } from "@parlor/core";
|
|
2
|
+
import type { ActionAudit, Migration } from "@parlor/server";
|
|
3
|
+
export declare const AUDIT_MIGRATION: Migration;
|
|
4
|
+
export interface AuditLog {
|
|
5
|
+
record(audit: ActionAudit): void;
|
|
6
|
+
flush(): Promise<void>;
|
|
7
|
+
stop(): Promise<void>;
|
|
8
|
+
}
|
|
9
|
+
export declare function createAuditLog(database: DataProvider): AuditLog;
|
|
10
|
+
//# sourceMappingURL=audit.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"audit.d.ts","sourceRoot":"","sources":["../src/audit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,KAAK,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAK7D,eAAO,MAAM,eAAe,EAAE,SAiC7B,CAAC;AA+BF,MAAM,WAAW,QAAQ;IACvB,MAAM,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI,CAAC;IACjC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACvB;AAED,wBAAgB,cAAc,CAAC,QAAQ,EAAE,YAAY,GAAG,QAAQ,CAkE/D"}
|
package/dist/audit.js
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { sql } from "drizzle-orm";
|
|
2
|
+
export const AUDIT_MIGRATION = {
|
|
3
|
+
id: "auth/0006_audit",
|
|
4
|
+
sql: `
|
|
5
|
+
create table parlor_auth_audit (
|
|
6
|
+
id bigint generated always as identity primary key,
|
|
7
|
+
at timestamptz not null,
|
|
8
|
+
action text not null,
|
|
9
|
+
actor_kind text not null,
|
|
10
|
+
user_id text,
|
|
11
|
+
grant_id text,
|
|
12
|
+
session_id text,
|
|
13
|
+
device_id text,
|
|
14
|
+
host_id text,
|
|
15
|
+
agent_name text,
|
|
16
|
+
agent_verified boolean,
|
|
17
|
+
thread_id text,
|
|
18
|
+
turn_id text,
|
|
19
|
+
source text not null,
|
|
20
|
+
scope text not null,
|
|
21
|
+
input_digest text not null,
|
|
22
|
+
stage text not null,
|
|
23
|
+
outcome text not null,
|
|
24
|
+
confirmation text
|
|
25
|
+
);
|
|
26
|
+
create index parlor_auth_audit_by_user on parlor_auth_audit (user_id, at);
|
|
27
|
+
create function parlor_auth_audit_append_only() returns trigger language plpgsql as $$
|
|
28
|
+
begin
|
|
29
|
+
raise exception 'parlor_auth_audit is append-only';
|
|
30
|
+
end
|
|
31
|
+
$$;
|
|
32
|
+
create trigger parlor_auth_audit_append_only
|
|
33
|
+
before update or delete on parlor_auth_audit
|
|
34
|
+
for each row execute function parlor_auth_audit_append_only()`,
|
|
35
|
+
};
|
|
36
|
+
const FLUSH_MS = 250;
|
|
37
|
+
const FLUSH_AT = 100;
|
|
38
|
+
const KEEP_AT_MOST = 10_000;
|
|
39
|
+
function audited({ principal, stage, confirmation }) {
|
|
40
|
+
return principal.kind === "agent" || stage === "refused" || confirmation !== undefined;
|
|
41
|
+
}
|
|
42
|
+
function rowOf(audit) {
|
|
43
|
+
const { principal } = audit;
|
|
44
|
+
const user = principal.kind === "anonymous" ? undefined : principal.userId;
|
|
45
|
+
const grant = principal.kind === "agent" || principal.kind === "host"
|
|
46
|
+
? principal.grantId
|
|
47
|
+
: undefined;
|
|
48
|
+
const turn = principal.kind === "agent" ? principal.turn : undefined;
|
|
49
|
+
const host = principal.kind === "host" ? principal.hostId : turn?.hostId;
|
|
50
|
+
return sql `(${new Date(audit.at).toISOString()}, ${audit.action}, ${principal.kind},
|
|
51
|
+
${user ?? null}, ${grant ?? null},
|
|
52
|
+
${principal.kind === "user" ? principal.sessionId : null},
|
|
53
|
+
${principal.kind === "user" ? (principal.deviceId ?? null) : null},
|
|
54
|
+
${host ?? null},
|
|
55
|
+
${principal.kind === "agent" ? principal.agent.name : null},
|
|
56
|
+
${principal.kind === "agent" ? principal.agent.verified : null},
|
|
57
|
+
${turn?.threadId ?? null}, ${turn?.turnId ?? null},
|
|
58
|
+
${audit.source}, ${audit.scope}, ${audit.inputDigest}, ${audit.stage}, ${audit.outcome},
|
|
59
|
+
${audit.confirmation ?? null})`;
|
|
60
|
+
}
|
|
61
|
+
export function createAuditLog(database) {
|
|
62
|
+
let queued = [];
|
|
63
|
+
let timer;
|
|
64
|
+
let writing = Promise.resolve();
|
|
65
|
+
let stopped = false;
|
|
66
|
+
const write = async () => {
|
|
67
|
+
if (queued.length === 0)
|
|
68
|
+
return;
|
|
69
|
+
const batch = queued;
|
|
70
|
+
queued = [];
|
|
71
|
+
try {
|
|
72
|
+
await database.transaction(async (tx) => {
|
|
73
|
+
await tx.execute(sql `
|
|
74
|
+
insert into parlor_auth_audit
|
|
75
|
+
(at, action, actor_kind, user_id, grant_id, session_id, device_id, host_id,
|
|
76
|
+
agent_name, agent_verified, thread_id, turn_id, source, scope, input_digest,
|
|
77
|
+
stage, outcome, confirmation)
|
|
78
|
+
values ${sql.join(batch.map(rowOf), sql `, `)}`);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
queued = [...batch, ...queued].slice(-KEEP_AT_MOST);
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
const flush = () => {
|
|
87
|
+
if (timer !== undefined)
|
|
88
|
+
clearTimeout(timer);
|
|
89
|
+
timer = undefined;
|
|
90
|
+
const next = writing.then(write, write);
|
|
91
|
+
writing = next.catch(() => { });
|
|
92
|
+
return next;
|
|
93
|
+
};
|
|
94
|
+
const schedule = () => {
|
|
95
|
+
if (timer !== undefined || stopped)
|
|
96
|
+
return;
|
|
97
|
+
timer = setTimeout(() => {
|
|
98
|
+
timer = undefined;
|
|
99
|
+
flush().catch((error) => {
|
|
100
|
+
console.error("[parlor] audit write failed, will retry:", error);
|
|
101
|
+
schedule();
|
|
102
|
+
});
|
|
103
|
+
}, FLUSH_MS);
|
|
104
|
+
timer.unref?.();
|
|
105
|
+
};
|
|
106
|
+
return {
|
|
107
|
+
record(audit) {
|
|
108
|
+
if (!audited(audit))
|
|
109
|
+
return;
|
|
110
|
+
queued.push(audit);
|
|
111
|
+
if (queued.length >= FLUSH_AT) {
|
|
112
|
+
flush().catch((error) => {
|
|
113
|
+
console.error("[parlor] audit write failed, will retry:", error);
|
|
114
|
+
schedule();
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
schedule();
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
flush,
|
|
122
|
+
async stop() {
|
|
123
|
+
stopped = true;
|
|
124
|
+
await flush().catch((error) => {
|
|
125
|
+
console.error("[parlor] audit write failed on shutdown:", error);
|
|
126
|
+
});
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
//# sourceMappingURL=audit.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"audit.js","sourceRoot":"","sources":["../src/audit.ts"],"names":[],"mappings":"AAE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,CAAC,KAAK,CAAC,CAAC;YACnB,IAAI,MAAM,CAAC,MAAM,IAAI,QAAQ,EAAE,CAAC;gBAC9B,KAAK,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;oBAC/B,OAAO,CAAC,KAAK,CAAC,0CAA0C,EAAE,KAAK,CAAC,CAAC;oBACjE,QAAQ,EAAE,CAAC;gBACb,CAAC,CAAC,CAAC;YACL,CAAC;iBAAM,CAAC;gBACN,QAAQ,EAAE,CAAC;YACb,CAAC;QACH,CAAC;QACD,KAAK;QACL,KAAK,CAAC,IAAI;YACR,OAAO,GAAG,IAAI,CAAC;YACf,MAAM,KAAK,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;gBACrC,OAAO,CAAC,KAAK,CAAC,0CAA0C,EAAE,KAAK,CAAC,CAAC;YACnE,CAAC,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { DataProvider } from \"@parlor/core\";\nimport type { ActionAudit, Migration } from \"@parlor/server\";\nimport { type SQL, sql } from \"drizzle-orm\";\n\nimport type { Database } from \"./database.js\";\n\nexport const AUDIT_MIGRATION: Migration = {\n id: \"auth/0006_audit\",\n sql: `\n create table parlor_auth_audit (\n id bigint generated always as identity primary key,\n at timestamptz not null,\n action text not null,\n actor_kind text not null,\n user_id text,\n grant_id text,\n session_id text,\n device_id text,\n host_id text,\n agent_name text,\n agent_verified boolean,\n thread_id text,\n turn_id text,\n source text not null,\n scope text not null,\n input_digest text not null,\n stage text not null,\n outcome text not null,\n confirmation text\n );\n create index parlor_auth_audit_by_user on parlor_auth_audit (user_id, at);\n create function parlor_auth_audit_append_only() returns trigger language plpgsql as $$\n begin\n raise exception 'parlor_auth_audit is append-only';\n end\n $$;\n create trigger parlor_auth_audit_append_only\n before update or delete on parlor_auth_audit\n for each row execute function parlor_auth_audit_append_only()`,\n};\n\nconst FLUSH_MS = 250;\nconst FLUSH_AT = 100;\nconst KEEP_AT_MOST = 10_000;\n\nfunction audited({ principal, stage, confirmation }: ActionAudit): boolean {\n return principal.kind === \"agent\" || stage === \"refused\" || confirmation !== undefined;\n}\n\nfunction rowOf(audit: ActionAudit): SQL {\n const { principal } = audit;\n const user = principal.kind === \"anonymous\" ? undefined : principal.userId;\n const grant =\n principal.kind === \"agent\" || principal.kind === \"host\"\n ? principal.grantId\n : undefined;\n const turn = principal.kind === \"agent\" ? principal.turn : undefined;\n const host = principal.kind === \"host\" ? principal.hostId : turn?.hostId;\n return sql`(${new Date(audit.at).toISOString()}, ${audit.action}, ${principal.kind},\n ${user ?? null}, ${grant ?? null},\n ${principal.kind === \"user\" ? principal.sessionId : null},\n ${principal.kind === \"user\" ? (principal.deviceId ?? null) : null},\n ${host ?? null},\n ${principal.kind === \"agent\" ? principal.agent.name : null},\n ${principal.kind === \"agent\" ? principal.agent.verified : null},\n ${turn?.threadId ?? null}, ${turn?.turnId ?? null},\n ${audit.source}, ${audit.scope}, ${audit.inputDigest}, ${audit.stage}, ${audit.outcome},\n ${audit.confirmation ?? null})`;\n}\n\nexport interface AuditLog {\n record(audit: ActionAudit): void;\n flush(): Promise<void>;\n stop(): Promise<void>;\n}\n\nexport function createAuditLog(database: DataProvider): AuditLog {\n let queued: ActionAudit[] = [];\n let timer: ReturnType<typeof setTimeout> | undefined;\n let writing: Promise<void> = Promise.resolve();\n let stopped = false;\n\n const write = async () => {\n if (queued.length === 0) return;\n const batch = queued;\n queued = [];\n try {\n await database.transaction(async (tx) => {\n await (tx as Database).execute(sql`\n insert into parlor_auth_audit\n (at, action, actor_kind, user_id, grant_id, session_id, device_id, host_id,\n agent_name, agent_verified, thread_id, turn_id, source, scope, input_digest,\n stage, outcome, confirmation)\n values ${sql.join(batch.map(rowOf), sql`, `)}`);\n });\n } catch (error) {\n queued = [...batch, ...queued].slice(-KEEP_AT_MOST);\n throw error;\n }\n };\n\n const flush = () => {\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n const next = writing.then(write, write);\n writing = next.catch(() => {});\n return next;\n };\n\n const schedule = () => {\n if (timer !== undefined || stopped) return;\n timer = setTimeout(() => {\n timer = undefined;\n flush().catch((error: unknown) => {\n console.error(\"[parlor] audit write failed, will retry:\", error);\n schedule();\n });\n }, FLUSH_MS);\n timer.unref?.();\n };\n\n return {\n record(audit) {\n if (!audited(audit)) return;\n queued.push(audit);\n if (queued.length >= FLUSH_AT) {\n flush().catch((error: unknown) => {\n console.error(\"[parlor] audit write failed, will retry:\", error);\n schedule();\n });\n } else {\n schedule();\n }\n },\n flush,\n async stop() {\n stopped = true;\n await flush().catch((error: unknown) => {\n console.error(\"[parlor] audit write failed on shutdown:\", error);\n });\n },\n };\n}\n"]}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { BetterAuthOptions } from "better-auth";
|
|
2
|
+
import type { RevocationNotice } from "./revocation.js";
|
|
3
|
+
export declare const AUTH_PLUGIN = "auth";
|
|
4
|
+
export declare const AUTH_BASE_PATH = "/_parlor/auth";
|
|
5
|
+
export declare const MCP_SCOPE = "mcp";
|
|
6
|
+
export declare const CONSENT_PATH = "/consent";
|
|
7
|
+
export declare const ACCESS_TOKEN_TTL_S: number;
|
|
8
|
+
export interface ParlorAuthOptions extends Omit<BetterAuthOptions, "basePath" | "baseURL"> {
|
|
9
|
+
/**
|
|
10
|
+
* The app's public origin, which serves its pages and `/_parlor`. Defaults to
|
|
11
|
+
* `PARLOR_ORIGIN`, then to the web origin `parlor dev` sets.
|
|
12
|
+
*/
|
|
13
|
+
readonly origin?: string | undefined;
|
|
14
|
+
/**
|
|
15
|
+
* The app page that signs a user in. An MCP client's authorization lands there and
|
|
16
|
+
* resumes once the user signs in through `@parlor/auth/client`.
|
|
17
|
+
*/
|
|
18
|
+
readonly signInPage: string;
|
|
19
|
+
/**
|
|
20
|
+
* The app's URL scheme, `app.scheme`, where social sign-in in a native shell returns.
|
|
21
|
+
* Defaults to `PARLOR_APP_SCHEME`, which `parlor dev` and `parlor build` set from it.
|
|
22
|
+
*/
|
|
23
|
+
readonly scheme?: string | undefined;
|
|
24
|
+
}
|
|
25
|
+
export interface ParlorAuthSettings {
|
|
26
|
+
readonly appName?: string | undefined;
|
|
27
|
+
readonly origin: string;
|
|
28
|
+
readonly baseURL: string;
|
|
29
|
+
readonly resource: string;
|
|
30
|
+
}
|
|
31
|
+
interface Bridge {
|
|
32
|
+
settings: ParlorAuthSettings;
|
|
33
|
+
revoke?: ((notice: RevocationNotice) => Promise<void>) | undefined;
|
|
34
|
+
}
|
|
35
|
+
export declare function bridgeOf(options: BetterAuthOptions): Bridge;
|
|
36
|
+
/** The other frontends one `parlor dev` serves next to the web target, each on its own port. */
|
|
37
|
+
export declare function devOrigins(env?: NodeJS.ProcessEnv): readonly string[];
|
|
38
|
+
/**
|
|
39
|
+
* The Better Auth options Parlor needs, merged into the app's own: sessions as a cookie
|
|
40
|
+
* on the web and a bearer token in native shells, and an OAuth authorization server for
|
|
41
|
+
* MCP clients (MCP 2026-07-28: protected resource metadata, Client ID Metadata Documents,
|
|
42
|
+
* PKCE, tokens bound to `/_parlor/mcp`).
|
|
43
|
+
*/
|
|
44
|
+
export declare function parlorAuth(options: ParlorAuthOptions): BetterAuthOptions;
|
|
45
|
+
export {};
|
|
46
|
+
//# sourceMappingURL=better-auth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"better-auth.d.ts","sourceRoot":"","sources":["../src/better-auth.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,iBAAiB,EAAoB,MAAM,aAAa,CAAC;AAIvE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAExD,eAAO,MAAM,WAAW,SAAS,CAAC;AAClC,eAAO,MAAM,cAAc,kBAAwC,CAAC;AACpE,eAAO,MAAM,SAAS,QAAQ,CAAC;AAC/B,eAAO,MAAM,YAAY,aAAa,CAAC;AAGvC,eAAO,MAAM,kBAAkB,QAA2C,CAAC;AAa3E,MAAM,WAAW,iBAAkB,SAAQ,IAAI,CAC7C,iBAAiB,EACjB,UAAU,GAAG,SAAS,CACvB;IACC;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACrC;;;OAGG;IACH,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACtC;AAED,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AAED,UAAU,MAAM;IACd,QAAQ,EAAE,kBAAkB,CAAC;IAC7B,MAAM,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,gBAAgB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,SAAS,CAAC;CACpE;AA8BD,wBAAgB,QAAQ,CAAC,OAAO,EAAE,iBAAiB,GAAG,MAAM,CAQ3D;AAED,gGAAgG;AAChG,wBAAgB,UAAU,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,SAAS,MAAM,EAAE,CAMlF;AAWD;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,iBAAiB,CA4BxE"}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { cimd } from "@better-auth/cimd";
|
|
2
|
+
import { fetchClientMetadataResource } from "@better-auth/cimd/node";
|
|
3
|
+
import { mcp } from "@better-auth/mcp";
|
|
4
|
+
import { DEFAULT_BASE_PATH, REVOCATION_HORIZON_MS, SHELL_ORIGINS } from "@parlor/server";
|
|
5
|
+
import { bearer, jwt } from "better-auth/plugins";
|
|
6
|
+
import { nativeSignIn } from "./native-sign-in.js";
|
|
7
|
+
export const AUTH_PLUGIN = "auth";
|
|
8
|
+
export const AUTH_BASE_PATH = `${DEFAULT_BASE_PATH}/${AUTH_PLUGIN}`;
|
|
9
|
+
export const MCP_SCOPE = "mcp";
|
|
10
|
+
export const CONSENT_PATH = "/consent";
|
|
11
|
+
/** Clock skew a revocation must outlast beyond a credential's own lifetime. */
|
|
12
|
+
const SKEW_MS = 60_000;
|
|
13
|
+
export const ACCESS_TOKEN_TTL_S = (REVOCATION_HORIZON_MS - SKEW_MS) / 1000;
|
|
14
|
+
/** Better Auth endpoints that would let a user bypass Parlor's own account actions. */
|
|
15
|
+
const DISABLED_PATHS = [
|
|
16
|
+
"/oauth2/create-client",
|
|
17
|
+
"/oauth2/update-client",
|
|
18
|
+
"/oauth2/delete-client",
|
|
19
|
+
"/oauth2/client/rotate-secret",
|
|
20
|
+
"/oauth2/get-clients",
|
|
21
|
+
"/oauth2/delete-consent",
|
|
22
|
+
"/oauth2/update-consent",
|
|
23
|
+
];
|
|
24
|
+
const BRIDGE_PLUGIN = "parlor";
|
|
25
|
+
function bridgePlugin(bridge) {
|
|
26
|
+
const ended = async (notice) => {
|
|
27
|
+
if (!bridge.revoke) {
|
|
28
|
+
throw new Error("Install betterAuthProvider() in createServer({ auth }).");
|
|
29
|
+
}
|
|
30
|
+
await bridge.revoke(notice);
|
|
31
|
+
};
|
|
32
|
+
return {
|
|
33
|
+
id: BRIDGE_PLUGIN,
|
|
34
|
+
bridge,
|
|
35
|
+
init: () => ({
|
|
36
|
+
options: {
|
|
37
|
+
databaseHooks: {
|
|
38
|
+
session: {
|
|
39
|
+
delete: { after: (session) => ended({ kind: "session", id: session.id }) },
|
|
40
|
+
},
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
}),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export function bridgeOf(options) {
|
|
47
|
+
const plugin = options.plugins?.find((candidate) => candidate.id === BRIDGE_PLUGIN);
|
|
48
|
+
if (!plugin) {
|
|
49
|
+
throw new Error("Pass the Better Auth options through parlorAuth() before betterAuth().");
|
|
50
|
+
}
|
|
51
|
+
return plugin.bridge;
|
|
52
|
+
}
|
|
53
|
+
/** The other frontends one `parlor dev` serves next to the web target, each on its own port. */
|
|
54
|
+
export function devOrigins(env = process.env) {
|
|
55
|
+
if (env.PARLOR_DEV !== "1")
|
|
56
|
+
return [];
|
|
57
|
+
return (env.PARLOR_DEV_ORIGINS ?? "")
|
|
58
|
+
.split(",")
|
|
59
|
+
.map((origin) => origin.trim())
|
|
60
|
+
.filter((origin) => /^https?:\/\//.test(origin));
|
|
61
|
+
}
|
|
62
|
+
function originOf(options) {
|
|
63
|
+
const origin = options.origin ?? process.env.PARLOR_ORIGIN ?? process.env.PARLOR_WEB_ORIGIN;
|
|
64
|
+
if (!origin) {
|
|
65
|
+
throw new Error("Set PARLOR_ORIGIN to the app's public origin, or pass `origin`.");
|
|
66
|
+
}
|
|
67
|
+
return new URL(origin).origin;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The Better Auth options Parlor needs, merged into the app's own: sessions as a cookie
|
|
71
|
+
* on the web and a bearer token in native shells, and an OAuth authorization server for
|
|
72
|
+
* MCP clients (MCP 2026-07-28: protected resource metadata, Client ID Metadata Documents,
|
|
73
|
+
* PKCE, tokens bound to `/_parlor/mcp`).
|
|
74
|
+
*/
|
|
75
|
+
export function parlorAuth(options) {
|
|
76
|
+
const { origin: _origin, signInPage, scheme, ...rest } = options;
|
|
77
|
+
const origin = originOf(options);
|
|
78
|
+
const baseURL = `${origin}${AUTH_BASE_PATH}`;
|
|
79
|
+
const resource = `${origin}${DEFAULT_BASE_PATH}/mcp`;
|
|
80
|
+
const bridge = {
|
|
81
|
+
settings: { appName: rest.appName, origin, baseURL, resource },
|
|
82
|
+
};
|
|
83
|
+
const trusted = rest.trustedOrigins;
|
|
84
|
+
return {
|
|
85
|
+
...rest,
|
|
86
|
+
baseURL,
|
|
87
|
+
basePath: AUTH_BASE_PATH,
|
|
88
|
+
trustedOrigins: Array.isArray(trusted)
|
|
89
|
+
? [origin, ...SHELL_ORIGINS, ...devOrigins(), ...trusted]
|
|
90
|
+
: async (request) => [
|
|
91
|
+
origin,
|
|
92
|
+
...SHELL_ORIGINS,
|
|
93
|
+
...devOrigins(),
|
|
94
|
+
...(typeof trusted === "function" ? await trusted(request) : []),
|
|
95
|
+
],
|
|
96
|
+
disabledPaths: [...DISABLED_PATHS, ...(rest.disabledPaths ?? [])],
|
|
97
|
+
plugins: [
|
|
98
|
+
...(rest.plugins ?? []),
|
|
99
|
+
...frameworkPlugins(resource, signInPage, scheme ?? process.env.PARLOR_APP_SCHEME),
|
|
100
|
+
bridgePlugin(bridge),
|
|
101
|
+
],
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
function frameworkPlugins(resource, signInPage, scheme) {
|
|
105
|
+
// Better Auth's plugin types are not written for exactOptionalPropertyTypes.
|
|
106
|
+
return [
|
|
107
|
+
bearer(),
|
|
108
|
+
jwt(),
|
|
109
|
+
mcp({
|
|
110
|
+
resource,
|
|
111
|
+
loginPage: signInPage,
|
|
112
|
+
consentPage: `${AUTH_BASE_PATH}${CONSENT_PATH}`,
|
|
113
|
+
scopes: [MCP_SCOPE, "offline_access"],
|
|
114
|
+
accessTokenExpiresIn: ACCESS_TOKEN_TTL_S,
|
|
115
|
+
}),
|
|
116
|
+
cimd({ fetchClientMetadataResource, metadataProfile: "mcp-2026-07-28" }),
|
|
117
|
+
nativeSignIn({ scheme: scheme || undefined }),
|
|
118
|
+
];
|
|
119
|
+
}
|
|
120
|
+
//# sourceMappingURL=better-auth.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"better-auth.js","sourceRoot":"","sources":["../src/better-auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACzC,OAAO,EAAE,2BAA2B,EAAE,MAAM,wBAAwB,CAAC;AACrE,OAAO,EAAE,GAAG,EAAE,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AAC,MAAM,CAAC;SACrB;KACF,CAAC;AACJ,CAAC;AAED,SAAS,gBAAgB,CACvB,QAAgB,EAChB,UAAkB,EAClB,MAA0B;IAE1B,6EAA6E;IAC7E,OAAO;QACL,MAAM,EAAE;QACR,GAAG,EAAE;QACL,GAAG,CAAC;YACF,QAAQ;YACR,SAAS,EAAE,UAAU;YACrB,WAAW,EAAE,GAAG,cAAc,GAAG,YAAY,EAAE;YAC/C,MAAM,EAAE,CAAC,SAAS,EAAE,gBAAgB,CAAC;YACrC,oBAAoB,EAAE,kBAAkB;SACzC,CAAC;QACF,IAAI,CAAC,EAAE,2BAA2B,EAAE,eAAe,EAAE,gBAAgB,EAAE,CAAC;QACxE,YAAY,CAAC,EAAE,MAAM,EAAE,MAAM,IAAI,SAAS,EAAE,CAAC;KACxB,CAAC;AAC1B,CAAC","sourcesContent":["import { cimd } from \"@better-auth/cimd\";\nimport { fetchClientMetadataResource } from \"@better-auth/cimd/node\";\nimport { mcp } from \"@better-auth/mcp\";\nimport { DEFAULT_BASE_PATH, REVOCATION_HORIZON_MS, SHELL_ORIGINS } from \"@parlor/server\";\nimport type { BetterAuthOptions, BetterAuthPlugin } from \"better-auth\";\nimport { bearer, jwt } from \"better-auth/plugins\";\n\nimport { nativeSignIn } from \"./native-sign-in.js\";\nimport type { RevocationNotice } from \"./revocation.js\";\n\nexport const AUTH_PLUGIN = \"auth\";\nexport const AUTH_BASE_PATH = `${DEFAULT_BASE_PATH}/${AUTH_PLUGIN}`;\nexport const MCP_SCOPE = \"mcp\";\nexport const CONSENT_PATH = \"/consent\";\n/** Clock skew a revocation must outlast beyond a credential's own lifetime. */\nconst SKEW_MS = 60_000;\nexport const ACCESS_TOKEN_TTL_S = (REVOCATION_HORIZON_MS - SKEW_MS) / 1000;\n\n/** Better Auth endpoints that would let a user bypass Parlor's own account actions. */\nconst DISABLED_PATHS = [\n \"/oauth2/create-client\",\n \"/oauth2/update-client\",\n \"/oauth2/delete-client\",\n \"/oauth2/client/rotate-secret\",\n \"/oauth2/get-clients\",\n \"/oauth2/delete-consent\",\n \"/oauth2/update-consent\",\n];\n\nexport interface ParlorAuthOptions extends Omit<\n BetterAuthOptions,\n \"basePath\" | \"baseURL\"\n> {\n /**\n * The app's public origin, which serves its pages and `/_parlor`. Defaults to\n * `PARLOR_ORIGIN`, then to the web origin `parlor dev` sets.\n */\n readonly origin?: string | undefined;\n /**\n * The app page that signs a user in. An MCP client's authorization lands there and\n * resumes once the user signs in through `@parlor/auth/client`.\n */\n readonly signInPage: string;\n /**\n * The app's URL scheme, `app.scheme`, where social sign-in in a native shell returns.\n * Defaults to `PARLOR_APP_SCHEME`, which `parlor dev` and `parlor build` set from it.\n */\n readonly scheme?: string | undefined;\n}\n\nexport interface ParlorAuthSettings {\n readonly appName?: string | undefined;\n readonly origin: string;\n readonly baseURL: string;\n readonly resource: string;\n}\n\ninterface Bridge {\n settings: ParlorAuthSettings;\n revoke?: ((notice: RevocationNotice) => Promise<void>) | undefined;\n}\n\nconst BRIDGE_PLUGIN = \"parlor\";\n\ninterface BridgePlugin extends BetterAuthPlugin {\n readonly bridge: Bridge;\n}\n\nfunction bridgePlugin(bridge: Bridge): BridgePlugin {\n const ended = async (notice: RevocationNotice) => {\n if (!bridge.revoke) {\n throw new Error(\"Install betterAuthProvider() in createServer({ auth }).\");\n }\n await bridge.revoke(notice);\n };\n return {\n id: BRIDGE_PLUGIN,\n bridge,\n init: () => ({\n options: {\n databaseHooks: {\n session: {\n delete: { after: (session) => ended({ kind: \"session\", id: session.id }) },\n },\n },\n },\n }),\n };\n}\n\nexport function bridgeOf(options: BetterAuthOptions): Bridge {\n const plugin = options.plugins?.find((candidate) => candidate.id === BRIDGE_PLUGIN);\n if (!plugin) {\n throw new Error(\n \"Pass the Better Auth options through parlorAuth() before betterAuth().\",\n );\n }\n return (plugin as BridgePlugin).bridge;\n}\n\n/** The other frontends one `parlor dev` serves next to the web target, each on its own port. */\nexport function devOrigins(env: NodeJS.ProcessEnv = process.env): readonly string[] {\n if (env.PARLOR_DEV !== \"1\") return [];\n return (env.PARLOR_DEV_ORIGINS ?? \"\")\n .split(\",\")\n .map((origin) => origin.trim())\n .filter((origin) => /^https?:\\/\\//.test(origin));\n}\n\nfunction originOf(options: ParlorAuthOptions): string {\n const origin =\n options.origin ?? process.env.PARLOR_ORIGIN ?? process.env.PARLOR_WEB_ORIGIN;\n if (!origin) {\n throw new Error(\"Set PARLOR_ORIGIN to the app's public origin, or pass `origin`.\");\n }\n return new URL(origin).origin;\n}\n\n/**\n * The Better Auth options Parlor needs, merged into the app's own: sessions as a cookie\n * on the web and a bearer token in native shells, and an OAuth authorization server for\n * MCP clients (MCP 2026-07-28: protected resource metadata, Client ID Metadata Documents,\n * PKCE, tokens bound to `/_parlor/mcp`).\n */\nexport function parlorAuth(options: ParlorAuthOptions): BetterAuthOptions {\n const { origin: _origin, signInPage, scheme, ...rest } = options;\n const origin = originOf(options);\n const baseURL = `${origin}${AUTH_BASE_PATH}`;\n const resource = `${origin}${DEFAULT_BASE_PATH}/mcp`;\n const bridge: Bridge = {\n settings: { appName: rest.appName, origin, baseURL, resource },\n };\n const trusted = rest.trustedOrigins;\n return {\n ...rest,\n baseURL,\n basePath: AUTH_BASE_PATH,\n trustedOrigins: Array.isArray(trusted)\n ? [origin, ...SHELL_ORIGINS, ...devOrigins(), ...trusted]\n : async (request) => [\n origin,\n ...SHELL_ORIGINS,\n ...devOrigins(),\n ...(typeof trusted === \"function\" ? await trusted(request) : []),\n ],\n disabledPaths: [...DISABLED_PATHS, ...(rest.disabledPaths ?? [])],\n plugins: [\n ...(rest.plugins ?? []),\n ...frameworkPlugins(resource, signInPage, scheme ?? process.env.PARLOR_APP_SCHEME),\n bridgePlugin(bridge),\n ],\n };\n}\n\nfunction frameworkPlugins(\n resource: string,\n signInPage: string,\n scheme: string | undefined,\n): BetterAuthPlugin[] {\n // Better Auth's plugin types are not written for exactOptionalPropertyTypes.\n return [\n bearer(),\n jwt(),\n mcp({\n resource,\n loginPage: signInPage,\n consentPage: `${AUTH_BASE_PATH}${CONSENT_PATH}`,\n scopes: [MCP_SCOPE, \"offline_access\"],\n accessTokenExpiresIn: ACCESS_TOKEN_TTL_S,\n }),\n cimd({ fetchClientMetadataResource, metadataProfile: \"mcp-2026-07-28\" }),\n nativeSignIn({ scheme: scheme || undefined }),\n ] as BetterAuthPlugin[];\n}\n"]}
|