agent-relay-server 0.83.1 → 0.84.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/docs/openapi.json +113 -1
- package/package.json +2 -2
- package/public/assets/display-CWMHll1J.js.map +1 -1
- package/src/auth/index.ts +23 -0
- package/src/auth/password.ts +122 -0
- package/src/auth/provider.ts +60 -0
- package/src/auth/session.ts +92 -0
- package/src/db/auth-identities.ts +119 -0
- package/src/db/index.ts +1 -0
- package/src/db/migrations.ts +6 -0
- package/src/index.ts +6 -1
- package/src/routes/_shared.ts +40 -2
- package/src/routes/auth.ts +107 -0
- package/src/routes/index.ts +8 -0
- package/src/routes/tokens.ts +8 -2
- package/src/security.ts +1 -1
- package/src/validation.ts +2 -0
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// Password authentication provider (#389). The only built-in provider in Phase 1. Secrets are
|
|
2
|
+
// hashed with scrypt (node:crypto — no dependency) and compared with `timingSafeEqual`, the same
|
|
3
|
+
// constant-time primitive the token layer uses. The hash is stored in `auth_identities.secret_hash`
|
|
4
|
+
// keyed by (provider="password", provider_subject=<username>).
|
|
5
|
+
import { randomBytes, scryptSync, timingSafeEqual } from "node:crypto";
|
|
6
|
+
import { createAuthIdentity, getAuthIdentity, type AuthIdentity } from "../db/auth-identities.ts";
|
|
7
|
+
import { isRecord } from "agent-relay-sdk";
|
|
8
|
+
import type { AuthProvider, AuthVerifyResult } from "./provider.ts";
|
|
9
|
+
|
|
10
|
+
/** The provider id stored in `auth_identities.provider` and sent in a login request's `provider`. */
|
|
11
|
+
export const PASSWORD_PROVIDER_ID = "password";
|
|
12
|
+
|
|
13
|
+
// scrypt cost parameters. N=2^14 keeps 128*N*r ≈ 16MB under node's 32MB default maxmem; r=8/p=1 are
|
|
14
|
+
// the standard interactive-login settings. keylen 64. Encoded into the hash string so a future cost
|
|
15
|
+
// bump stays verifiable against existing hashes.
|
|
16
|
+
const SCRYPT_N = 16384;
|
|
17
|
+
const SCRYPT_R = 8;
|
|
18
|
+
const SCRYPT_P = 1;
|
|
19
|
+
const KEYLEN = 64;
|
|
20
|
+
const SALT_BYTES = 16;
|
|
21
|
+
export const DUMMY_PASSWORD_HASH =
|
|
22
|
+
`scrypt$${SCRYPT_N}$${SCRYPT_R}$${SCRYPT_P}$${"00".repeat(SALT_BYTES)}$${"00".repeat(KEYLEN)}`;
|
|
23
|
+
|
|
24
|
+
type PasswordVerifier = (password: string, stored: string | null) => boolean;
|
|
25
|
+
type PasswordIdentityLookup = (provider: string, providerSubject: string) => AuthIdentity | undefined;
|
|
26
|
+
|
|
27
|
+
interface PasswordVerifyAttempt {
|
|
28
|
+
valid: boolean;
|
|
29
|
+
attemptedKdf: boolean;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Hash a plaintext password into a self-describing `scrypt$N$r$p$saltHex$hashHex` string. */
|
|
33
|
+
export function hashPassword(password: string): string {
|
|
34
|
+
const salt = randomBytes(SALT_BYTES);
|
|
35
|
+
const derived = scryptSync(password, salt, KEYLEN, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
|
|
36
|
+
return `scrypt$${SCRYPT_N}$${SCRYPT_R}$${SCRYPT_P}$${salt.toString("hex")}$${derived.toString("hex")}`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function verifyPasswordAttempt(password: string, stored: string | null): PasswordVerifyAttempt {
|
|
40
|
+
if (!stored) return { valid: false, attemptedKdf: false };
|
|
41
|
+
const parts = stored.split("$");
|
|
42
|
+
if (parts.length !== 6 || parts[0] !== "scrypt") return { valid: false, attemptedKdf: false };
|
|
43
|
+
const [, nRaw, rRaw, pRaw, saltHex, hashHex] = parts as [string, string, string, string, string, string];
|
|
44
|
+
const N = Number(nRaw);
|
|
45
|
+
const r = Number(rRaw);
|
|
46
|
+
const p = Number(pRaw);
|
|
47
|
+
if (!Number.isInteger(N) || !Number.isInteger(r) || !Number.isInteger(p)) return { valid: false, attemptedKdf: false };
|
|
48
|
+
const expected = Buffer.from(hashHex, "hex");
|
|
49
|
+
if (expected.length <= 0) return { valid: false, attemptedKdf: false };
|
|
50
|
+
let derived: Buffer;
|
|
51
|
+
try {
|
|
52
|
+
derived = scryptSync(password, Buffer.from(saltHex, "hex"), expected.length, { N, r, p });
|
|
53
|
+
} catch {
|
|
54
|
+
return { valid: false, attemptedKdf: false };
|
|
55
|
+
}
|
|
56
|
+
return { valid: derived.length === expected.length && timingSafeEqual(derived, expected), attemptedKdf: true };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Constant-time verify a plaintext password against a stored `scrypt$...` hash. */
|
|
60
|
+
export function verifyPassword(password: string, stored: string | null): boolean {
|
|
61
|
+
return verifyPasswordAttempt(password, stored).valid;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function verifyPasswordWithDummyFallback(password: string, stored: string | null): boolean {
|
|
65
|
+
const result = verifyPasswordAttempt(password, stored);
|
|
66
|
+
if (result.attemptedKdf) return result.valid;
|
|
67
|
+
verifyPasswordAttempt(password, DUMMY_PASSWORD_HASH);
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Link a password login to a user (admin pre-link / first-user bootstrap). Hashes the password and
|
|
73
|
+
* inserts an `auth_identities` row. `username` is the `provider_subject` the user logs in with.
|
|
74
|
+
*/
|
|
75
|
+
export function createPasswordIdentity(input: {
|
|
76
|
+
userId: string;
|
|
77
|
+
username: string;
|
|
78
|
+
password: string;
|
|
79
|
+
metadata?: Record<string, unknown>;
|
|
80
|
+
}): AuthIdentity {
|
|
81
|
+
return createAuthIdentity({
|
|
82
|
+
userId: input.userId,
|
|
83
|
+
provider: PASSWORD_PROVIDER_ID,
|
|
84
|
+
providerSubject: input.username,
|
|
85
|
+
secretHash: hashPassword(input.password),
|
|
86
|
+
metadata: input.metadata,
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Parse `{ username, password }` from a login request body. */
|
|
91
|
+
function readCredentials(credentials: unknown): { username: string; password: string } | null {
|
|
92
|
+
if (!isRecord(credentials)) return null;
|
|
93
|
+
const username = credentials.username ?? credentials.handle ?? credentials.email;
|
|
94
|
+
const password = credentials.password;
|
|
95
|
+
if (typeof username !== "string" || !username || typeof password !== "string" || !password) return null;
|
|
96
|
+
return { username, password };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function verifyPasswordCredentials(
|
|
100
|
+
credentials: unknown,
|
|
101
|
+
opts: { lookupIdentity?: PasswordIdentityLookup; verifyStoredPassword?: PasswordVerifier } = {},
|
|
102
|
+
): AuthVerifyResult | null {
|
|
103
|
+
const creds = readCredentials(credentials);
|
|
104
|
+
if (!creds) return null;
|
|
105
|
+
const lookupIdentity = opts.lookupIdentity ?? getAuthIdentity;
|
|
106
|
+
const verifyStoredPassword = opts.verifyStoredPassword ?? verifyPasswordWithDummyFallback;
|
|
107
|
+
const identity = lookupIdentity(PASSWORD_PROVIDER_ID, creds.username);
|
|
108
|
+
const passwordMatches = verifyStoredPassword(creds.password, identity?.secretHash ?? DUMMY_PASSWORD_HASH);
|
|
109
|
+
if (!identity || !passwordMatches) return null;
|
|
110
|
+
return { providerSubject: creds.username };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export const passwordAuthProvider: AuthProvider = {
|
|
114
|
+
id: PASSWORD_PROVIDER_ID,
|
|
115
|
+
displayName: "Password",
|
|
116
|
+
flow: "password",
|
|
117
|
+
verify(credentials: unknown): AuthVerifyResult | null {
|
|
118
|
+
// Unknown username, malformed stored hash, and wrong password all pay one scrypt verification
|
|
119
|
+
// before returning null, so login failure timing does not identify linked accounts.
|
|
120
|
+
return verifyPasswordCredentials(credentials);
|
|
121
|
+
},
|
|
122
|
+
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// Pluggable authentication providers (#389). An AuthProvider turns a login request into a
|
|
2
|
+
// `providerSubject` — the stable external identifier (a username, an OAuth `sub`, an email) that
|
|
3
|
+
// `auth_identities` maps onto a `users.id`. The login route is provider-agnostic: it resolves the
|
|
4
|
+
// provider, calls `verify()`, then looks the returned subject up in `auth_identities`. Adding a
|
|
5
|
+
// provider (GitHub OAuth in Phase 2, magic-link, …) is a `register()` call plus rows — no schema
|
|
6
|
+
// change, no route change (the pluggability guarantee #389 must hold).
|
|
7
|
+
//
|
|
8
|
+
// In-process registry. The registry knows ONLY the interface — concrete providers register
|
|
9
|
+
// themselves via the composition root (src/auth/index.ts), which keeps this module free of any
|
|
10
|
+
// dependency on a concrete provider (no registry ↔ plugin cycle).
|
|
11
|
+
|
|
12
|
+
/** How a provider proves identity — drives the login UI and which fields `verify()` reads. */
|
|
13
|
+
export type AuthProviderFlow = "password" | "oauth" | "magic-link";
|
|
14
|
+
|
|
15
|
+
/** Result of a successful `verify()`: the external subject to resolve against `auth_identities`. */
|
|
16
|
+
export interface AuthVerifyResult {
|
|
17
|
+
providerSubject: string;
|
|
18
|
+
/** Optional provider-supplied profile bits (display name, email) for first-link/auto-provision. */
|
|
19
|
+
profile?: Record<string, unknown>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface AuthProvider {
|
|
23
|
+
/** Stable id; the `auth_identities.provider` value and the `provider` field a login request sends. */
|
|
24
|
+
id: string;
|
|
25
|
+
/** Human label for the login UI. */
|
|
26
|
+
displayName: string;
|
|
27
|
+
flow: AuthProviderFlow;
|
|
28
|
+
/**
|
|
29
|
+
* Begin an interactive (redirect) flow — returns where to send the user (e.g. an OAuth authorize
|
|
30
|
+
* URL). Optional: password is single-step and omits it. Phase 2 (GitHub OAuth) implements it.
|
|
31
|
+
*/
|
|
32
|
+
begin?(req: Request): Promise<{ redirectUrl: string } | null> | ({ redirectUrl: string } | null);
|
|
33
|
+
/**
|
|
34
|
+
* Verify the presented credentials and return the authenticated subject, or null on failure.
|
|
35
|
+
* MUST be constant-ish on failure (no "unknown user" vs "bad password" distinction leaking to
|
|
36
|
+
* the caller — both return null). The route maps a non-null subject to a user.
|
|
37
|
+
*/
|
|
38
|
+
verify(credentials: unknown): Promise<AuthVerifyResult | null> | (AuthVerifyResult | null);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const registry = new Map<string, AuthProvider>();
|
|
42
|
+
|
|
43
|
+
/** Register (or replace) a provider. Idempotent by id — re-registering overrides, which is how
|
|
44
|
+
* tests install a throwaway provider to prove pluggability. */
|
|
45
|
+
export function registerAuthProvider(provider: AuthProvider): void {
|
|
46
|
+
registry.set(provider.id, provider);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Remove a provider by id (test teardown / runtime disable). Returns true if one was removed. */
|
|
50
|
+
export function unregisterAuthProvider(id: string): boolean {
|
|
51
|
+
return registry.delete(id);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function getAuthProvider(id: string): AuthProvider | undefined {
|
|
55
|
+
return registry.get(id);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function listAuthProviders(): AuthProvider[] {
|
|
59
|
+
return [...registry.values()];
|
|
60
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// Human session tokens (#389). A session is a component token minted via the existing `createToken`
|
|
2
|
+
// — the `tokens` table IS the session store, so `verifyComponentToken` already enforces expiry and
|
|
3
|
+
// revocation, and "sign out everywhere" is just revoking every token for a `sub`. The session token
|
|
4
|
+
// reuses ONLY the signing primitive: it carries a new `sub` namespace (`user:<id>`) and a new
|
|
5
|
+
// `role` ("user"), so no machine-token path branches on it.
|
|
6
|
+
import { userSinkId, userIdFromAddress, isHumanAgentId, type User, type UserRole } from "agent-relay-sdk";
|
|
7
|
+
import { createToken } from "../token-db.ts";
|
|
8
|
+
import { verifyComponentToken } from "../security.ts";
|
|
9
|
+
import { getUser } from "../db/users.ts";
|
|
10
|
+
import type { ComponentToken } from "../types.ts";
|
|
11
|
+
|
|
12
|
+
/** Access token lifetime (~1h) — short, because refresh re-mints it silently. */
|
|
13
|
+
export const ACCESS_TTL_SECONDS = 60 * 60;
|
|
14
|
+
/** Refresh token lifetime (~30d) — the dashboard re-mints the access token until this expires. */
|
|
15
|
+
export const REFRESH_TTL_SECONDS = 30 * 24 * 60 * 60;
|
|
16
|
+
/** Marker scope carried ONLY by refresh tokens. It matches no route's required scope, so a refresh
|
|
17
|
+
* token can never act as an access token; the refresh route validates it explicitly. */
|
|
18
|
+
export const REFRESH_SCOPE = "auth:refresh";
|
|
19
|
+
|
|
20
|
+
/** The `role` stamped on a human session token. New namespace — no machine path branches on it. */
|
|
21
|
+
export const USER_TOKEN_ROLE = "user";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Map a user role to the scopes its session carries. STOPGAP for #392 (real RBAC): admins get full
|
|
25
|
+
* access via the `admin:*` alias (→ `system:admin`, which `hasScope` short-circuits everywhere), and
|
|
26
|
+
* everyone else gets a read-only baseline. When #392 lands the per-role scope matrix, replace this
|
|
27
|
+
* one function — every session inherits the new policy with no other change.
|
|
28
|
+
*/
|
|
29
|
+
export function scopesForUserRole(role: UserRole): string[] {
|
|
30
|
+
if (role === "admin") return ["admin:*"];
|
|
31
|
+
if (role === "operator") return ["agent:read", "agent:write", "message:read", "message:send", "task:read", "task:write"];
|
|
32
|
+
return ["agent:read", "message:read", "task:read"];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface MintedSession {
|
|
36
|
+
accessToken: string;
|
|
37
|
+
refreshToken: string;
|
|
38
|
+
accessJti: string;
|
|
39
|
+
refreshJti: string;
|
|
40
|
+
expiresIn: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Mint an access + refresh token pair for a logged-in user. `constraints.tenantId` carries the
|
|
45
|
+
* SaaS seam (identity-only — enforces nothing). Both tokens share the `user:<id>` sub so a single
|
|
46
|
+
* "sign out everywhere" revoke (by sub) kills the whole session family.
|
|
47
|
+
*/
|
|
48
|
+
export function mintUserSession(user: User): MintedSession {
|
|
49
|
+
const sub = userSinkId(user.id);
|
|
50
|
+
const constraints = user.tenantId ? { tenantId: user.tenantId } : undefined;
|
|
51
|
+
const access = createToken({
|
|
52
|
+
sub,
|
|
53
|
+
role: USER_TOKEN_ROLE,
|
|
54
|
+
scope: scopesForUserRole(user.role),
|
|
55
|
+
constraints,
|
|
56
|
+
ttlSeconds: ACCESS_TTL_SECONDS,
|
|
57
|
+
createdBy: `auth:login:${user.id}`,
|
|
58
|
+
});
|
|
59
|
+
const refresh = createToken({
|
|
60
|
+
sub,
|
|
61
|
+
role: USER_TOKEN_ROLE,
|
|
62
|
+
scope: [REFRESH_SCOPE],
|
|
63
|
+
constraints,
|
|
64
|
+
ttlSeconds: REFRESH_TTL_SECONDS,
|
|
65
|
+
createdBy: `auth:refresh:${user.id}`,
|
|
66
|
+
});
|
|
67
|
+
return {
|
|
68
|
+
accessToken: access.token,
|
|
69
|
+
refreshToken: refresh.token,
|
|
70
|
+
accessJti: access.record.jti,
|
|
71
|
+
refreshJti: refresh.record.jti,
|
|
72
|
+
expiresIn: ACCESS_TTL_SECONDS,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Validate a refresh token and resolve it to its live user. Returns null unless the token verifies
|
|
78
|
+
* (signature + unexpired + unrevoked, via `verifyComponentToken`), carries the refresh scope, names
|
|
79
|
+
* a human `sub`, and that user still exists and is active. The caller mints a fresh session for the
|
|
80
|
+
* user.
|
|
81
|
+
*/
|
|
82
|
+
export function resolveRefreshToken(token: string): { user: User; payload: ComponentToken } | null {
|
|
83
|
+
const payload = verifyComponentToken(token);
|
|
84
|
+
if (!payload) return null;
|
|
85
|
+
if (!payload.scope.includes(REFRESH_SCOPE)) return null;
|
|
86
|
+
if (!isHumanAgentId(payload.sub)) return null;
|
|
87
|
+
const userId = userIdFromAddress(payload.sub);
|
|
88
|
+
if (!userId) return null;
|
|
89
|
+
const user = getUser(userId);
|
|
90
|
+
if (!user || user.status !== "active") return null;
|
|
91
|
+
return { user, payload };
|
|
92
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Pluggable authentication identities (#389 auth & sessions). Maps an external login —
|
|
2
|
+
// a (provider, provider_subject) pair such as ("password", "admin") or ("github", "12345") —
|
|
3
|
+
// onto a relational `users.id`. The login flow authenticates a provider_subject, looks it up
|
|
4
|
+
// here, and mints a session token for the resolved user. Provider-agnostic by construction:
|
|
5
|
+
// `secret_hash` is nullable so an OAuth/magic-link identity is just a row with no stored secret —
|
|
6
|
+
// a new provider needs ZERO schema change (the #389 pluggability guarantee).
|
|
7
|
+
//
|
|
8
|
+
// DDL home (single owner; the barrel re-exports, never inlines DDL). Wired into applyMigrations
|
|
9
|
+
// right after seedDefaultUser(), mirroring the idempotent ensureUsersSchema() pattern.
|
|
10
|
+
import { randomUUID } from "node:crypto";
|
|
11
|
+
import { getDb } from "./connection.ts";
|
|
12
|
+
|
|
13
|
+
export interface AuthIdentity {
|
|
14
|
+
id: string;
|
|
15
|
+
userId: string;
|
|
16
|
+
provider: string;
|
|
17
|
+
providerSubject: string;
|
|
18
|
+
/** Opaque provider-managed secret material (e.g. a scrypt password hash). Null for secretless
|
|
19
|
+
* providers (OAuth, magic-link) whose proof lives with the upstream provider, not here. */
|
|
20
|
+
secretHash: string | null;
|
|
21
|
+
metadata: Record<string, unknown>;
|
|
22
|
+
createdAt: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface AuthIdentityRow {
|
|
26
|
+
id: string;
|
|
27
|
+
user_id: string;
|
|
28
|
+
provider: string;
|
|
29
|
+
provider_subject: string;
|
|
30
|
+
secret_hash: string | null;
|
|
31
|
+
metadata: string | null;
|
|
32
|
+
created_at: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Single DDL home for `auth_identities` (#389). Idempotent (CREATE TABLE IF NOT EXISTS), so it is
|
|
37
|
+
* safe on every boot/migration — an old single-user DB gains the table on upgrade, with zero rows,
|
|
38
|
+
* and the god-token break-glass keeps working without any identity present. `UNIQUE(provider,
|
|
39
|
+
* provider_subject)` makes a login subject resolve to exactly one identity; `user_id` cascades on
|
|
40
|
+
* user delete so removing a human drops their logins.
|
|
41
|
+
*/
|
|
42
|
+
export function ensureAuthIdentitiesSchema(): void {
|
|
43
|
+
getDb().run(`
|
|
44
|
+
CREATE TABLE IF NOT EXISTS auth_identities (
|
|
45
|
+
id TEXT PRIMARY KEY,
|
|
46
|
+
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
47
|
+
provider TEXT NOT NULL,
|
|
48
|
+
provider_subject TEXT NOT NULL,
|
|
49
|
+
secret_hash TEXT,
|
|
50
|
+
metadata TEXT NOT NULL DEFAULT '{}',
|
|
51
|
+
created_at INTEGER NOT NULL,
|
|
52
|
+
UNIQUE(provider, provider_subject)
|
|
53
|
+
)
|
|
54
|
+
`);
|
|
55
|
+
getDb().run("CREATE INDEX IF NOT EXISTS idx_auth_identities_user ON auth_identities(user_id)");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function rowToIdentity(row: AuthIdentityRow): AuthIdentity {
|
|
59
|
+
return {
|
|
60
|
+
id: row.id,
|
|
61
|
+
userId: row.user_id,
|
|
62
|
+
provider: row.provider,
|
|
63
|
+
providerSubject: row.provider_subject,
|
|
64
|
+
secretHash: row.secret_hash,
|
|
65
|
+
metadata: row.metadata ? (JSON.parse(row.metadata) as Record<string, unknown>) : {},
|
|
66
|
+
createdAt: row.created_at,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Resolve a login subject to its identity, or undefined if no such (provider, subject) exists. */
|
|
71
|
+
export function getAuthIdentity(provider: string, providerSubject: string): AuthIdentity | undefined {
|
|
72
|
+
const row = getDb()
|
|
73
|
+
.query("SELECT * FROM auth_identities WHERE provider = ? AND provider_subject = ?")
|
|
74
|
+
.get(provider, providerSubject) as AuthIdentityRow | null;
|
|
75
|
+
return row ? rowToIdentity(row) : undefined;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** All identities linked to a user — used by account UIs and "unlink provider" flows. */
|
|
79
|
+
export function listAuthIdentitiesForUser(userId: string): AuthIdentity[] {
|
|
80
|
+
const rows = getDb()
|
|
81
|
+
.query("SELECT * FROM auth_identities WHERE user_id = ? ORDER BY created_at")
|
|
82
|
+
.all(userId) as AuthIdentityRow[];
|
|
83
|
+
return rows.map(rowToIdentity);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Link a login to a user. `secretHash` is null for secretless providers. Throws on a duplicate
|
|
88
|
+
* (provider, provider_subject) — the caller surfaces it as a 409/validation error.
|
|
89
|
+
*/
|
|
90
|
+
export function createAuthIdentity(input: {
|
|
91
|
+
userId: string;
|
|
92
|
+
provider: string;
|
|
93
|
+
providerSubject: string;
|
|
94
|
+
secretHash?: string | null;
|
|
95
|
+
metadata?: Record<string, unknown>;
|
|
96
|
+
}): AuthIdentity {
|
|
97
|
+
const id = randomUUID();
|
|
98
|
+
const now = Date.now();
|
|
99
|
+
getDb()
|
|
100
|
+
.query(
|
|
101
|
+
`INSERT INTO auth_identities (id, user_id, provider, provider_subject, secret_hash, metadata, created_at)
|
|
102
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
103
|
+
)
|
|
104
|
+
.run(
|
|
105
|
+
id,
|
|
106
|
+
input.userId,
|
|
107
|
+
input.provider,
|
|
108
|
+
input.providerSubject,
|
|
109
|
+
input.secretHash ?? null,
|
|
110
|
+
JSON.stringify(input.metadata ?? {}),
|
|
111
|
+
now,
|
|
112
|
+
);
|
|
113
|
+
return getAuthIdentity(input.provider, input.providerSubject)!;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Remove an identity by id. Returns true if a row was deleted. */
|
|
117
|
+
export function deleteAuthIdentity(id: string): boolean {
|
|
118
|
+
return getDb().query("DELETE FROM auth_identities WHERE id = ?").run(id).changes > 0;
|
|
119
|
+
}
|
package/src/db/index.ts
CHANGED
|
@@ -17,6 +17,7 @@ export * from "./delivery.ts";
|
|
|
17
17
|
export * from "./message-reads.ts";
|
|
18
18
|
export * from "./inbox.ts";
|
|
19
19
|
export * from "./users.ts";
|
|
20
|
+
export * from "./auth-identities.ts";
|
|
20
21
|
export * from "./agent-ownership.ts";
|
|
21
22
|
export * from "./drive-leases.ts";
|
|
22
23
|
export * from "./activity.ts";
|
package/src/db/migrations.ts
CHANGED
|
@@ -16,6 +16,7 @@ import { STALE_TTL_MS, DAY_MS, CLAIM_LEASE_MS, POOL_CLAIM_LEASE_MS, WORKSPACE_ME
|
|
|
16
16
|
import { matchAgents } from "../agent-ref";
|
|
17
17
|
import { getDb } from "./connection.ts";
|
|
18
18
|
import { ensureUsersSchema, seedDefaultUser } from "./users.ts";
|
|
19
|
+
import { ensureAuthIdentitiesSchema } from "./auth-identities.ts";
|
|
19
20
|
import { ensureAgentOwnershipSchema, seedDefaultAgentOwnership } from "./agent-ownership.ts";
|
|
20
21
|
import { ensureDriveLeaseSchema } from "./drive-leases.ts";
|
|
21
22
|
import { ensureContinuationArchiveSearchSchema } from "./continuation-archives.ts";
|
|
@@ -800,6 +801,11 @@ export function applyMigrations(): void {
|
|
|
800
801
|
ensureUsersSchema();
|
|
801
802
|
seedDefaultUser();
|
|
802
803
|
|
|
804
|
+
// Pluggable login identities (#389): the (provider, provider_subject) → users.id map behind real
|
|
805
|
+
// login + sessions. Ensured right after the user seed (FK → users) and idempotent — an old
|
|
806
|
+
// single-user DB gains it empty, and the god-token break-glass keeps working with zero rows.
|
|
807
|
+
ensureAuthIdentitiesSchema();
|
|
808
|
+
|
|
803
809
|
// Agent ownership/visibility table (#392). FK-references both agents and users, so it ensures
|
|
804
810
|
// AFTER both exist. The backfill (seedDefaultAgentOwnership) runs below, once the built-in
|
|
805
811
|
// agents are in, so they can be excluded from ownership.
|
package/src/index.ts
CHANGED
|
@@ -268,7 +268,12 @@ export function createFetchHandler(
|
|
|
268
268
|
const matched = matchRoute(req.method, url.pathname);
|
|
269
269
|
if (matched) {
|
|
270
270
|
const publicPaths = ["/api/spec", "/api/docs", "/api/health"];
|
|
271
|
-
|
|
271
|
+
// Pre-auth allowlist (#389): the auth endpoints must be reachable unauthenticated — they ARE
|
|
272
|
+
// the way a session is obtained. Each handler self-authenticates (login verifies credentials,
|
|
273
|
+
// refresh validates the refresh token, logout revokes the presented token). Everything else
|
|
274
|
+
// still flows through the component-token gate below.
|
|
275
|
+
const publicAuthPaths = ["/api/auth/providers", "/api/auth/login", "/api/auth/refresh", "/api/auth/logout"];
|
|
276
|
+
if (!publicPaths.includes(url.pathname) && !publicAuthPaths.includes(url.pathname)) {
|
|
272
277
|
const integrationAuth = getIntegrationAuth(req);
|
|
273
278
|
const componentAuth = getComponentAuth(req);
|
|
274
279
|
const handlerOwnsScopedAuth = url.pathname === "/api/tokens/me" ||
|
package/src/routes/_shared.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { ValidationError, createActivityEvent, createCallbackDelivery, finishCal
|
|
|
5
5
|
import { cleanEpoch, cleanString, optionalEnum } from "../validation";
|
|
6
6
|
import { emitActivityEvent, emitMessageQueued, emitNewMessage } from "../sse";
|
|
7
7
|
import { emitRelayEvent } from "../events";
|
|
8
|
-
import { canonicalHumanAgentId, DEFAULT_USER_ID, errMessage, isRecord, userSinkId } from "agent-relay-sdk";
|
|
8
|
+
import { canonicalHumanAgentId, DEFAULT_USER_ID, errMessage, isHumanAgentId, isRecord, userIdFromAddress, userSinkId } from "agent-relay-sdk";
|
|
9
9
|
import { authorizeAgentForUser, visibleAgentIdsForUser, type AgentAction } from "../agent-authz";
|
|
10
10
|
import { generateSpawnRequestId } from "../spawn-command";
|
|
11
11
|
import { getComponentAuth, getIntegrationAuth, isAuthorized, isRequestAuthorizedFor } from "../security";
|
|
@@ -58,13 +58,51 @@ export function authAuditMetadata(req: Request): Record<string, unknown> {
|
|
|
58
58
|
},
|
|
59
59
|
};
|
|
60
60
|
}
|
|
61
|
-
|
|
61
|
+
if (!hasPresentedCredential(req)) return {};
|
|
62
|
+
// Root (god-token) credential: stamp the seeded-admin identity it now carries (#389 break-glass),
|
|
63
|
+
// so the audit trail records *who* acted instead of an anonymous root.
|
|
64
|
+
const acting = resolveActingUser(req);
|
|
65
|
+
return acting
|
|
66
|
+
? { auth: { type: "root", userId: acting.userId, source: acting.source } }
|
|
67
|
+
: { auth: { type: "root" } };
|
|
62
68
|
}
|
|
63
69
|
|
|
64
70
|
export function isRootCredentialRequest(req: Request): boolean {
|
|
65
71
|
return hasPresentedCredential(req) && isAuthorized(req) && !getComponentAuth(req) && !getIntegrationAuth(req);
|
|
66
72
|
}
|
|
67
73
|
|
|
74
|
+
/**
|
|
75
|
+
* Which human is acting, and how their request was authenticated (#389). The single bridge from a
|
|
76
|
+
* request to a `users.id`:
|
|
77
|
+
* - a human session token (component token whose `sub` is a `user:<id>` address) → that user, via
|
|
78
|
+
* the SDK resolver (never a hand-rolled namespace) — `source: "session"`;
|
|
79
|
+
* - the raw god-token / root credential (`isRootCredentialRequest`) → the seeded admin
|
|
80
|
+
* `DEFAULT_USER_ID` with `source: "break-glass"`. This is what gives the env token an *identity*
|
|
81
|
+
* instead of the anonymous "server" it carried before, while it KEEPS bypassing scope checks
|
|
82
|
+
* unchanged (the gate in src/index.ts is untouched). Works with zero `auth_identities` rows, so
|
|
83
|
+
* it is simultaneously the break-glass path and the first-user bootstrap.
|
|
84
|
+
*
|
|
85
|
+
* Returns null for a machine component/integration token (no human is acting).
|
|
86
|
+
*/
|
|
87
|
+
export type ActingUserSource = "session" | "break-glass";
|
|
88
|
+
|
|
89
|
+
export interface ActingUser {
|
|
90
|
+
userId: string;
|
|
91
|
+
source: ActingUserSource;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function resolveActingUser(req: Request): ActingUser | null {
|
|
95
|
+
const component = getComponentAuth(req);
|
|
96
|
+
if (component && isHumanAgentId(component.sub)) {
|
|
97
|
+
const userId = userIdFromAddress(component.sub);
|
|
98
|
+
if (userId) return { userId, source: "session" };
|
|
99
|
+
}
|
|
100
|
+
if (isRootCredentialRequest(req)) {
|
|
101
|
+
return { userId: DEFAULT_USER_ID, source: "break-glass" };
|
|
102
|
+
}
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
|
|
68
106
|
function sanitizeAttribution(raw: unknown): string | undefined {
|
|
69
107
|
if (typeof raw !== "string") return undefined;
|
|
70
108
|
// eslint-disable-next-line no-control-regex
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// Authentication & session routes (#389). These four paths sit on a pre-auth PUBLIC ALLOWLIST
|
|
2
|
+
// (src/index.ts) so they are reachable unauthenticated — each handler owns its own auth: login
|
|
3
|
+
// verifies credentials, refresh validates the refresh token, logout revokes the presented session.
|
|
4
|
+
// Everything else on the relay still flows through the existing component-token gate.
|
|
5
|
+
import { isRecord, type User } from "agent-relay-sdk";
|
|
6
|
+
import { error, json, parseBody, type Handler } from "./_shared";
|
|
7
|
+
import { getAuthProvider, listAuthProviders, mintUserSession, resolveRefreshToken } from "../auth";
|
|
8
|
+
import { getAuthIdentity, getUser } from "../db";
|
|
9
|
+
import { revokeToken } from "../token-db.ts";
|
|
10
|
+
import { getComponentAuth } from "../security";
|
|
11
|
+
|
|
12
|
+
/** Public projection of a user for login/refresh responses — never leaks internal-only columns. */
|
|
13
|
+
function userView(user: User): Record<string, unknown> {
|
|
14
|
+
return {
|
|
15
|
+
id: user.id,
|
|
16
|
+
handle: user.handle,
|
|
17
|
+
displayName: user.displayName,
|
|
18
|
+
role: user.role,
|
|
19
|
+
tenantId: user.tenantId,
|
|
20
|
+
avatarUrl: user.avatarUrl,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function sessionResponse(user: User): Response {
|
|
25
|
+
const session = mintUserSession(user);
|
|
26
|
+
return json({
|
|
27
|
+
tokenType: "Bearer",
|
|
28
|
+
accessToken: session.accessToken,
|
|
29
|
+
refreshToken: session.refreshToken,
|
|
30
|
+
expiresIn: session.expiresIn,
|
|
31
|
+
user: userView(user),
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** GET /api/auth/providers — the login screen reads this to render available login methods. */
|
|
36
|
+
export const getAuthProvidersRoute: Handler = () =>
|
|
37
|
+
json({
|
|
38
|
+
providers: listAuthProviders().map((provider) => ({
|
|
39
|
+
id: provider.id,
|
|
40
|
+
displayName: provider.displayName,
|
|
41
|
+
flow: provider.flow,
|
|
42
|
+
})),
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* POST /api/auth/login — body `{ provider, ...credentials }`. Resolves the provider, verifies the
|
|
47
|
+
* credentials to a `providerSubject`, maps it through `auth_identities` to a user, and mints a
|
|
48
|
+
* session. Every failure returns the same generic 401 (no provider/user/credential enumeration).
|
|
49
|
+
*/
|
|
50
|
+
export const postAuthLoginRoute: Handler = async (req) => {
|
|
51
|
+
const parsed = await parseBody<unknown>(req);
|
|
52
|
+
if (!parsed.ok) return error(parsed.error, parsed.status);
|
|
53
|
+
if (!isRecord(parsed.body)) return error("login body required", 400);
|
|
54
|
+
const providerId = parsed.body.provider;
|
|
55
|
+
if (typeof providerId !== "string" || !providerId) return error("provider required", 400);
|
|
56
|
+
|
|
57
|
+
const provider = getAuthProvider(providerId);
|
|
58
|
+
if (!provider) return error("invalid credentials", 401);
|
|
59
|
+
|
|
60
|
+
const result = await provider.verify(parsed.body);
|
|
61
|
+
if (!result) return error("invalid credentials", 401);
|
|
62
|
+
|
|
63
|
+
const identity = getAuthIdentity(provider.id, result.providerSubject);
|
|
64
|
+
if (!identity) return error("invalid credentials", 401);
|
|
65
|
+
|
|
66
|
+
const user = getUser(identity.userId);
|
|
67
|
+
if (!user || user.status !== "active") return error("invalid credentials", 401);
|
|
68
|
+
|
|
69
|
+
return sessionResponse(user);
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* POST /api/auth/refresh — body `{ refreshToken }`. Validates the refresh token and mints a fresh
|
|
74
|
+
* session, rotating the refresh token: the consumed one is revoked so a captured refresh token is
|
|
75
|
+
* single-use. Returns the same generic 401 on any invalid/expired/revoked token.
|
|
76
|
+
*/
|
|
77
|
+
export const postAuthRefreshRoute: Handler = async (req) => {
|
|
78
|
+
const parsed = await parseBody<unknown>(req);
|
|
79
|
+
if (!parsed.ok) return error(parsed.error, parsed.status);
|
|
80
|
+
if (!isRecord(parsed.body)) return error("refresh body required", 400);
|
|
81
|
+
const refreshToken = parsed.body.refreshToken;
|
|
82
|
+
if (typeof refreshToken !== "string" || !refreshToken) return error("refreshToken required", 400);
|
|
83
|
+
|
|
84
|
+
const resolved = resolveRefreshToken(refreshToken);
|
|
85
|
+
if (!resolved) return error("invalid refresh token", 401);
|
|
86
|
+
|
|
87
|
+
const response = sessionResponse(resolved.user);
|
|
88
|
+
// Rotate: revoke the consumed refresh token so it can't be replayed (the fresh pair supersedes it).
|
|
89
|
+
if (resolved.payload.jti) revokeToken(resolved.payload.jti, "rotation");
|
|
90
|
+
return response;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* POST /api/auth/logout — revokes the presented session token and, if supplied, its refresh token.
|
|
95
|
+
* Idempotent: revoking an already-revoked or absent token is a no-op. Always returns 204.
|
|
96
|
+
*/
|
|
97
|
+
export const postAuthLogoutRoute: Handler = async (req) => {
|
|
98
|
+
const component = getComponentAuth(req);
|
|
99
|
+
if (component?.jti) revokeToken(component.jti, "admin");
|
|
100
|
+
|
|
101
|
+
const parsed = await parseBody<unknown>(req);
|
|
102
|
+
if (parsed.ok && isRecord(parsed.body) && typeof parsed.body.refreshToken === "string") {
|
|
103
|
+
const resolved = resolveRefreshToken(parsed.body.refreshToken);
|
|
104
|
+
if (resolved?.payload.jti) revokeToken(resolved.payload.jti, "admin");
|
|
105
|
+
}
|
|
106
|
+
return new Response(null, { status: 204 });
|
|
107
|
+
};
|
package/src/routes/index.ts
CHANGED
|
@@ -18,6 +18,7 @@ import { deleteSpawnPolicyRoute, getSpawnPoliciesHealth, getSpawnPoliciesRoute,
|
|
|
18
18
|
import { deleteTokenProfileRoute, getTokenById, getTokenMe, getTokenProfiles, getTokens, patchTokenProfile, postIntegrationRuntimeToken, postInteractiveRunnerRuntimeToken, postMcpRuntimeToken, postOrchestratorRunnerToken, postRuntimeTokenRenew, postToken, postTokenProfile, postTokenRevoke } from "./tokens";
|
|
19
19
|
import { deleteWorkspaceById, getWorkspaceById, getWorkspaceDiagnostics, getWorkspaceDiff, getWorkspaceGitState, getWorkspaceMergePreview, getWorkspaceOrphans, getWorkspaceRecoveryBranches, getWorkspaceStewards, getWorkspaces, postWorkspaceAction, postWorkspaceCleanupStale, postWorkspaceOrphanReclaim, postWorkspaceRecoveryBranchDiscard } from "./workspaces";
|
|
20
20
|
import { error, type Handler } from "./_shared";
|
|
21
|
+
import { getAuthProvidersRoute, postAuthLoginRoute, postAuthLogoutRoute, postAuthRefreshRoute } from "./auth";
|
|
21
22
|
import { getActivityEvents, postActivityEvent } from "./activity";
|
|
22
23
|
import { getAnalyticsRoute, getHealthRoute, getMaintenanceJobs, getStatsRoute, postMaintenanceJobRun, postSystemReap } from "./stats";
|
|
23
24
|
import { getApiDocs, getApiSpec } from "./spec";
|
|
@@ -69,6 +70,13 @@ function route(method: string, path: string, handler: Handler): Route {
|
|
|
69
70
|
}
|
|
70
71
|
|
|
71
72
|
const routes: Route[] = [
|
|
73
|
+
// Auth & sessions (#389). On the pre-auth public allowlist (src/index.ts) — each handler owns
|
|
74
|
+
// its own auth (login verifies credentials, refresh validates the refresh token, logout revokes).
|
|
75
|
+
route("GET", "/api/auth/providers", getAuthProvidersRoute),
|
|
76
|
+
route("POST", "/api/auth/login", postAuthLoginRoute),
|
|
77
|
+
route("POST", "/api/auth/refresh", postAuthRefreshRoute),
|
|
78
|
+
route("POST", "/api/auth/logout", postAuthLogoutRoute),
|
|
79
|
+
|
|
72
80
|
route("POST", "/api/artifacts", postArtifact),
|
|
73
81
|
route("GET", "/api/artifacts", getArtifacts),
|
|
74
82
|
route("GET", "/api/artifacts/:id/content", getArtifactContent),
|
package/src/routes/tokens.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Auto-split from routes.ts (#299). Domain: tokens.
|
|
2
|
-
import { SPAWN_PROVIDERS, isRecord } from "agent-relay-sdk";
|
|
2
|
+
import { SPAWN_PROVIDERS, isRecord, userSinkId } from "agent-relay-sdk";
|
|
3
3
|
import { ValidationError, getOrchestrator, upsertIntegrationRegistry } from "../db";
|
|
4
|
-
import { auditEvent, authAuditMetadata, authorizeRoute, error, isRootCredentialRequest, json, parseBody, type Handler } from "./_shared";
|
|
4
|
+
import { auditEvent, authAuditMetadata, authorizeRoute, error, isRootCredentialRequest, json, parseBody, resolveActingUser, type Handler } from "./_shared";
|
|
5
5
|
import { cleanString, cleanStringArray, cleanTokenConstraints, optionalEnum } from "../validation";
|
|
6
6
|
import { createToken, deleteTokenProfile, getToken, getTokenProfile, listTokenProfiles, listTokens, renewToken, revokeToken, updateTokenProfile, upsertTokenProfile } from "../token-db";
|
|
7
7
|
import { getComponentAuth, getIntegrationAuth, isAuthorized } from "../security";
|
|
@@ -36,6 +36,12 @@ export const getTokenMe: Handler = (req) => {
|
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
if (isAuthorized(req)) {
|
|
39
|
+
// Root (god-token) now carries the seeded-admin identity (#389): report *who* is acting
|
|
40
|
+
// (break-glass → user:default) instead of the anonymous "server" it showed before.
|
|
41
|
+
const acting = resolveActingUser(req);
|
|
42
|
+
if (acting) {
|
|
43
|
+
return json({ actor: userSinkId(acting.userId), userId: acting.userId, source: acting.source, kind: "server", scopes: ["*"] });
|
|
44
|
+
}
|
|
39
45
|
return json({ actor: "server", kind: "server", scopes: ["*"] });
|
|
40
46
|
}
|
|
41
47
|
return error("unauthorized", 401);
|
package/src/security.ts
CHANGED
|
@@ -539,7 +539,7 @@ function isTokenConstraints(value: unknown): value is TokenConstraints {
|
|
|
539
539
|
for (const [key, item] of Object.entries(record)) {
|
|
540
540
|
if (["terminalAttach", "logsRead", "canDelegate"].includes(key)) {
|
|
541
541
|
if (typeof item !== "boolean") return false;
|
|
542
|
-
} else if (key === "cwd" || key === "spawnedBy" || key === "teamId" || key === "projectId") {
|
|
542
|
+
} else if (key === "cwd" || key === "spawnedBy" || key === "teamId" || key === "projectId" || key === "tenantId") {
|
|
543
543
|
if (typeof item !== "string") return false;
|
|
544
544
|
} else if (key === "maxSpawnedAgents") {
|
|
545
545
|
if (typeof item !== "number") return false;
|