@capybara-hq/kernel 0.1.0-rc.93 → 0.1.0-rc.94
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin/login-sources.controller.d.ts +30 -0
- package/dist/admin/login-sources.controller.js +77 -0
- package/dist/admin/login-sources.schemas.d.ts +25 -0
- package/dist/admin/login-sources.schemas.js +49 -0
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/config/schema.d.ts +0 -2
- package/dist/config/schema.js +0 -28
- package/dist/ctx/create-ctx.d.ts +5 -1
- package/dist/ctx/create-ctx.js +13 -2
- package/dist/device-access/device-access.service.d.ts +27 -4
- package/dist/device-access/device-access.service.js +180 -30
- package/dist/errors.d.ts +10 -0
- package/dist/errors.js +10 -0
- package/dist/extensions/instance.js +3 -1
- package/dist/http/api.module.js +2 -0
- package/dist/identity/auth.controller.d.ts +2 -0
- package/dist/identity/auth.controller.js +1 -1
- package/dist/identity/external.d.ts +78 -40
- package/dist/identity/external.js +157 -72
- package/dist/identity/identity.module.js +9 -0
- package/dist/identity/linked-accounts.d.ts +42 -0
- package/dist/identity/linked-accounts.js +78 -0
- package/dist/identity/login-sources.d.ts +160 -0
- package/dist/identity/login-sources.js +403 -0
- package/dist/identity/sso-decisions.d.ts +75 -0
- package/dist/identity/sso-decisions.js +42 -0
- package/dist/identity/sso-link.d.ts +61 -0
- package/dist/identity/sso-link.js +157 -0
- package/dist/identity/sso.controller.d.ts +98 -14
- package/dist/identity/sso.controller.js +222 -28
- package/dist/identity/sso.d.ts +75 -30
- package/dist/identity/sso.js +129 -70
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/infra/config/kernel-config.service.js +0 -3
- package/dist/infra/throttler/named-throttlers.d.ts +1 -1
- package/dist/infra/throttler/named-throttlers.js +1 -1
- package/dist/platform/exclusions.js +15 -0
- package/dist/platform/operation.js +4 -0
- package/dist/platform/ops/admin.ops.d.ts +3 -1
- package/dist/platform/ops/admin.ops.js +106 -2
- package/dist/platform/ops/extensions-admin.ops.d.ts +24 -2
- package/dist/platform/ops/extensions-admin.ops.js +54 -6
- package/dist/platform/route-schemas.js +2 -0
- package/dist/tools/builtins/sandbox/glob.js +7 -4
- package/dist/tools/builtins/sandbox/grep.d.ts +8 -1
- package/dist/tools/builtins/sandbox/grep.js +27 -33
- package/dist/tools/builtins/sandbox/search-command.d.ts +43 -0
- package/dist/tools/builtins/sandbox/search-command.js +86 -0
- package/dist/tools/call-scope.d.ts +19 -6
- package/dist/tools/call-scope.js +29 -0
- package/dist/tools/pipeline.d.ts +3 -2
- package/dist/tools/pipeline.js +29 -10
- package/dist/tools/questions.service.d.ts +2 -2
- package/dist/tools/questions.service.js +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
11
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
12
|
+
import { ApiError } from "../errors.js";
|
|
13
|
+
import { REDIS } from "../infra/tokens.js";
|
|
14
|
+
/** A pending link's lifetime (seconds). */
|
|
15
|
+
export const SSO_LINK_TTL_SECONDS = 600;
|
|
16
|
+
/** Wrong passwords a ticket survives: the fifth burns it. */
|
|
17
|
+
export const SSO_LINK_MAX_ATTEMPTS = 5;
|
|
18
|
+
/** The web's link page (next-intl adds the language prefix). */
|
|
19
|
+
export const SSO_LINK_PAGE_PATH = "/login/link";
|
|
20
|
+
/** The `cap_` prefix keeps the ticket masked in logged paths and queries. */
|
|
21
|
+
const TICKET_PREFIX = "cap_link_";
|
|
22
|
+
const TICKET_RE = /^cap_link_[A-Za-z0-9_-]{43}$/;
|
|
23
|
+
const sha256 = (s) => createHash("sha256").update(s).digest("base64url");
|
|
24
|
+
/** Redis holds only the ticket's hash: reading Redis gives no usable ticket. */
|
|
25
|
+
const ticketKey = (ticket) => `capk:sso-link:${sha256(ticket)}`;
|
|
26
|
+
function sameHash(a, b) {
|
|
27
|
+
const x = Buffer.from(a);
|
|
28
|
+
const y = Buffer.from(b);
|
|
29
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Reserves one password attempt, atomically, before the password is checked: the pending link (a
|
|
33
|
+
* hash `rec` + `attempts`) gains an attempt, which keeps its TTL. Returns 1 when reserved, 0 when
|
|
34
|
+
* the link is gone or its attempts are all taken (the reservation is undone), so concurrent
|
|
35
|
+
* submissions never check more than the limit of passwords.
|
|
36
|
+
*/
|
|
37
|
+
const RESERVE_ATTEMPT = `
|
|
38
|
+
if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end
|
|
39
|
+
local n = redis.call('HINCRBY', KEYS[1], 'attempts', 1)
|
|
40
|
+
if n > tonumber(ARGV[1]) then redis.call('HINCRBY', KEYS[1], 'attempts', -1); return 0 end
|
|
41
|
+
return 1`;
|
|
42
|
+
/** Gives a reserved attempt back (the password was not wrong: a disabled account, a rate limit). */
|
|
43
|
+
const REFUND_ATTEMPT = `
|
|
44
|
+
if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end
|
|
45
|
+
if tonumber(redis.call('HGET', KEYS[1], 'attempts') or '0') > 0 then
|
|
46
|
+
redis.call('HINCRBY', KEYS[1], 'attempts', -1)
|
|
47
|
+
end
|
|
48
|
+
return 1`;
|
|
49
|
+
/**
|
|
50
|
+
* A reserved attempt was a wrong password: it stays reserved (`attempts` = failures + checks in
|
|
51
|
+
* flight, which caps concurrent checks), and `failures` counts it; the link is deleted (burned)
|
|
52
|
+
* once the real failures reach the limit, never because of reservations a refund will give back.
|
|
53
|
+
*/
|
|
54
|
+
const SETTLE_FAILURE = `
|
|
55
|
+
if redis.call('EXISTS', KEYS[1]) == 0 then return -1 end
|
|
56
|
+
local n = redis.call('HINCRBY', KEYS[1], 'failures', 1)
|
|
57
|
+
if n >= tonumber(ARGV[1]) then redis.call('DEL', KEYS[1]) end
|
|
58
|
+
return n`;
|
|
59
|
+
/** Takes the pending link and deletes it in one step (GETDEL on the hash): one caller wins. */
|
|
60
|
+
const REDEEM = `
|
|
61
|
+
local v = redis.call('HGET', KEYS[1], 'rec')
|
|
62
|
+
if v then redis.call('DEL', KEYS[1]) end
|
|
63
|
+
return v`;
|
|
64
|
+
export const linkExpired = () => new ApiError("sso.link_expired", "The link request expired or was already used");
|
|
65
|
+
const sessionMismatch = () => new ApiError("sso.session_mismatch", "The sign-in was started in a different browser");
|
|
66
|
+
/**
|
|
67
|
+
* Link tickets (spec §5): `cap_link_<32 bytes base64url>`, kept in Redis as a hash
|
|
68
|
+
* `capk:sso-link:<sha256(ticket)>` (`rec`: the pending link as JSON, `attempts`: reserved password
|
|
69
|
+
* checks, `failures`: wrong passwords) for 10 minutes.
|
|
70
|
+
* Every read checks the browser binding cookie against the recorded hash. Single use on success
|
|
71
|
+
* ({@link redeem} deletes it atomically, so two concurrent submissions get one winner), burned
|
|
72
|
+
* after {@link SSO_LINK_MAX_ATTEMPTS} wrong passwords (an attempt is reserved atomically before
|
|
73
|
+
* each password check, {@link reserveAttempt}, on the same key, which keeps its TTL). All state is
|
|
74
|
+
* in Redis: any replica serves any step.
|
|
75
|
+
*
|
|
76
|
+
* Deployment assumption: no sibling origin can set cookies for the kernel's host (no untrusted
|
|
77
|
+
* subdomain sharing a parent domain cookie scope), so the `cap_sso` binding value is this
|
|
78
|
+
* browser's own and cannot be planted to tie a victim's browser to an attacker's ticket.
|
|
79
|
+
*/
|
|
80
|
+
let SsoLinkTickets = class SsoLinkTickets {
|
|
81
|
+
redis;
|
|
82
|
+
constructor(redis) {
|
|
83
|
+
this.redis = redis;
|
|
84
|
+
}
|
|
85
|
+
/** Stores a pending link and returns its ticket. */
|
|
86
|
+
async create(link) {
|
|
87
|
+
const ticket = TICKET_PREFIX + randomBytes(32).toString("base64url");
|
|
88
|
+
const key = ticketKey(ticket);
|
|
89
|
+
await this.redis
|
|
90
|
+
.multi()
|
|
91
|
+
.hset(key, { rec: JSON.stringify(link), attempts: 0, failures: 0 })
|
|
92
|
+
.expire(key, SSO_LINK_TTL_SECONDS)
|
|
93
|
+
.exec();
|
|
94
|
+
return ticket;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The pending link of `ticket` without consuming it. Unknown, expired, used or burned →
|
|
98
|
+
* `sso.link_expired`; a browser binding value that does not match → `sso.session_mismatch`.
|
|
99
|
+
*/
|
|
100
|
+
async peek(ticket, binding) {
|
|
101
|
+
if (!TICKET_RE.test(ticket))
|
|
102
|
+
throw linkExpired();
|
|
103
|
+
const raw = await this.redis.hget(ticketKey(ticket), "rec");
|
|
104
|
+
if (raw === null)
|
|
105
|
+
throw linkExpired();
|
|
106
|
+
return checkBinding(JSON.parse(raw), binding);
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Reserves one of the ticket's attempts before a password check; none left, or the ticket gone →
|
|
110
|
+
* `sso.link_expired`.
|
|
111
|
+
*/
|
|
112
|
+
async reserveAttempt(ticket) {
|
|
113
|
+
if (!TICKET_RE.test(ticket))
|
|
114
|
+
throw linkExpired();
|
|
115
|
+
const ok = await this.redis.eval(RESERVE_ATTEMPT, 1, ticketKey(ticket), String(SSO_LINK_MAX_ATTEMPTS));
|
|
116
|
+
if (ok !== 1)
|
|
117
|
+
throw linkExpired();
|
|
118
|
+
}
|
|
119
|
+
/** Gives a reserved attempt back (the check did not find a wrong password). */
|
|
120
|
+
async refundAttempt(ticket) {
|
|
121
|
+
if (TICKET_RE.test(ticket))
|
|
122
|
+
await this.redis.eval(REFUND_ATTEMPT, 1, ticketKey(ticket));
|
|
123
|
+
}
|
|
124
|
+
/** The reserved attempt was a wrong password; the one that reaches the limit burns the ticket. */
|
|
125
|
+
async failedAttempt(ticket) {
|
|
126
|
+
if (!TICKET_RE.test(ticket))
|
|
127
|
+
return;
|
|
128
|
+
await this.redis.eval(SETTLE_FAILURE, 1, ticketKey(ticket), String(SSO_LINK_MAX_ATTEMPTS));
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Takes the pending link and deletes it in one step: of concurrent callers exactly one gets it,
|
|
132
|
+
* the others `sso.link_expired`. The binding is checked again on the taken record.
|
|
133
|
+
*/
|
|
134
|
+
async redeem(ticket, binding) {
|
|
135
|
+
if (!TICKET_RE.test(ticket))
|
|
136
|
+
throw linkExpired();
|
|
137
|
+
const raw = (await this.redis.eval(REDEEM, 1, ticketKey(ticket)));
|
|
138
|
+
if (raw === null)
|
|
139
|
+
throw linkExpired();
|
|
140
|
+
return checkBinding(JSON.parse(raw), binding);
|
|
141
|
+
}
|
|
142
|
+
/** Deletes the ticket (its login source was switched off). */
|
|
143
|
+
async discard(ticket) {
|
|
144
|
+
if (TICKET_RE.test(ticket))
|
|
145
|
+
await this.redis.del(ticketKey(ticket));
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
SsoLinkTickets = __decorate([
|
|
149
|
+
Injectable(),
|
|
150
|
+
__param(0, Inject(REDIS))
|
|
151
|
+
], SsoLinkTickets);
|
|
152
|
+
export { SsoLinkTickets };
|
|
153
|
+
function checkBinding(link, binding) {
|
|
154
|
+
if (binding === undefined || !sameHash(sha256(binding), link.binding))
|
|
155
|
+
throw sessionMismatch();
|
|
156
|
+
return link;
|
|
157
|
+
}
|
|
@@ -1,11 +1,37 @@
|
|
|
1
1
|
import type { FastifyReply, FastifyRequest } from "fastify";
|
|
2
|
+
import { z } from "zod";
|
|
2
3
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
3
|
-
import {
|
|
4
|
+
import { CredentialThrottler } from "../infra/throttler/credential-throttler.js";
|
|
5
|
+
import { type Account, AccountsService } from "./accounts.js";
|
|
4
6
|
import { IdentityBinding, type PendingBinding } from "./binding.js";
|
|
5
|
-
import { ExternalIdentities
|
|
7
|
+
import { ExternalIdentities } from "./external.js";
|
|
8
|
+
import { type LinkableMethod, type LinkedAccountRow, LinkedAccountsService } from "./linked-accounts.js";
|
|
6
9
|
import { type Principal } from "./principal.js";
|
|
7
10
|
import { SessionService } from "./sessions.js";
|
|
8
11
|
import { SsoFlow } from "./sso.js";
|
|
12
|
+
import { SsoLinkTickets } from "./sso-link.js";
|
|
13
|
+
declare const LinkBodySchema: z.ZodObject<{
|
|
14
|
+
ticket: z.ZodString;
|
|
15
|
+
login: z.ZodString;
|
|
16
|
+
password: z.ZodString;
|
|
17
|
+
}, z.core.$strip>;
|
|
18
|
+
declare const StartLinkBodySchema: z.ZodObject<{
|
|
19
|
+
intent: z.ZodLiteral<"link">;
|
|
20
|
+
returnTo: z.ZodOptional<z.ZodString>;
|
|
21
|
+
}, z.core.$strip>;
|
|
22
|
+
/** What the link page shows (`GET /api/v1/auth/sso/link`). */
|
|
23
|
+
export interface SsoLinkView {
|
|
24
|
+
plugin: string;
|
|
25
|
+
label: {
|
|
26
|
+
zh: string;
|
|
27
|
+
en: string;
|
|
28
|
+
};
|
|
29
|
+
tenantId: string;
|
|
30
|
+
displayName: string;
|
|
31
|
+
avatarUrl?: string;
|
|
32
|
+
/** The external account is already linked to a Capybara account for IM (never which one). */
|
|
33
|
+
linkedToAnother: boolean;
|
|
34
|
+
}
|
|
9
35
|
/**
|
|
10
36
|
* 第三方登录(`/api/v1/auth/sources`、`/api/v1/auth/sso/:plugin/*`,均为公开路由)。浏览器整页跳转,
|
|
11
37
|
* 发起与回调都以 302 结束;失败回登录页并带原因码(`/login?error=<code>`),不回显身份源文本。
|
|
@@ -15,8 +41,11 @@ export declare class SsoController {
|
|
|
15
41
|
private readonly sessions;
|
|
16
42
|
private readonly accounts;
|
|
17
43
|
private readonly config;
|
|
18
|
-
|
|
19
|
-
|
|
44
|
+
private readonly linkTickets;
|
|
45
|
+
private readonly external;
|
|
46
|
+
private readonly throttler;
|
|
47
|
+
constructor(flow: SsoFlow, sessions: SessionService, accounts: AccountsService, config: KernelConfigService, linkTickets: SsoLinkTickets, external: ExternalIdentities, throttler: CredentialThrottler);
|
|
48
|
+
sources(): Promise<{
|
|
20
49
|
sources: {
|
|
21
50
|
plugin: string;
|
|
22
51
|
label: {
|
|
@@ -24,20 +53,68 @@ export declare class SsoController {
|
|
|
24
53
|
en: string;
|
|
25
54
|
};
|
|
26
55
|
}[];
|
|
27
|
-
}
|
|
56
|
+
}>;
|
|
28
57
|
/**
|
|
29
|
-
*
|
|
30
|
-
*
|
|
58
|
+
* Starts a sign-in: 302 to the source's authorize URL, writing the browser binding cookie
|
|
59
|
+
* `cap_sso` (HttpOnly, SameSite=Lax: the source's redirect back is a cross-site top-level GET,
|
|
60
|
+
* which Lax sends; Path only `/api/v1/auth/sso`). Always a sign-in: `intent=link` is refused
|
|
61
|
+
* with `sso.session_mismatch` and no state, because a cross-site page can trigger this GET with
|
|
62
|
+
* the person's Lax session cookie and would link whatever external account that browser is
|
|
63
|
+
* signed in to (a link intent starts from `POST …/start`).
|
|
31
64
|
*/
|
|
32
|
-
start(plugin: string, returnTo: unknown,
|
|
65
|
+
start(plugin: string, returnTo: unknown, intent: unknown, req: FastifyRequest, reply: FastifyReply): Promise<void>;
|
|
33
66
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
67
|
+
* Starts a link intent (the linked accounts page, spec §4): web session only, and as an unsafe
|
|
68
|
+
* method it needs the CSRF header (global guard), so no other site can start it. The state
|
|
69
|
+
* records the session's account; the callback must carry the same session. Writes the binding
|
|
70
|
+
* cookie as the GET start does and returns where the browser goes next: the source's authorize
|
|
71
|
+
* URL, or, on failure, the page with `?error=<code>`.
|
|
72
|
+
*/
|
|
73
|
+
startLink(plugin: string, body: z.infer<typeof StartLinkBodySchema>, principal: Principal, req: FastifyRequest, reply: FastifyReply): Promise<{
|
|
74
|
+
location: string;
|
|
75
|
+
}>;
|
|
76
|
+
private setBindingCookie;
|
|
77
|
+
/**
|
|
78
|
+
* The identity source's redirect back: state and binding cookie checked → the plugin verifies
|
|
79
|
+
* the external identity → spec §4's decision ({@link SsoFlow.callback}). A sign-in creates a
|
|
80
|
+
* session, writes the session cookies and 302s to the page (`http.publicUrl` + returnTo); a
|
|
81
|
+
* disabled account → the sign-in page with `auth.account_disabled`, no session. A link intent
|
|
82
|
+
* keeps its session and goes back to its page (its failures too, with `?error=<code>`). The link
|
|
83
|
+
* page branch keeps the binding cookie (renewed for the ticket's lifetime: the link page's routes
|
|
84
|
+
* need it) and 302s to `/login/link?ticket=…`; every other outcome clears it.
|
|
38
85
|
*/
|
|
39
86
|
callback(plugin: string, q: Record<string, unknown>, principal: Principal | undefined, req: FastifyRequest, reply: FastifyReply): Promise<void>;
|
|
87
|
+
/**
|
|
88
|
+
* The link page's view of a pending link (spec §5): needs the ticket and the matching binding
|
|
89
|
+
* cookie (`sso.link_expired` / `sso.session_mismatch`); a source switched off since →
|
|
90
|
+
* `sso.link_expired` (the ticket is dropped). Says whether the external account is already
|
|
91
|
+
* linked to some account (an IM `bind` row), never to which.
|
|
92
|
+
*/
|
|
93
|
+
linkView(ticket: unknown, req: FastifyRequest): Promise<SsoLinkView>;
|
|
94
|
+
/**
|
|
95
|
+
* Completes a pending link with the person's username and password (spec §5). Public; the
|
|
96
|
+
* global guard requires the CSRF header on this unsafe public route, and the binding cookie must
|
|
97
|
+
* match (it relies on no sibling origin being able to set cookies for the kernel's host, see
|
|
98
|
+
* `SsoLinkTickets`). The password goes through the same service and the same credential
|
|
99
|
+
* throttlers as `POST /auth/login` (R25); each check first reserves one of the ticket's attempts
|
|
100
|
+
* atomically, and a wrong password keeps it (the fifth burns the ticket). A disabled account →
|
|
101
|
+
* `auth.account_disabled` (its password was right: the ticket's attempt and the throttler
|
|
102
|
+
* reservation are given back). The login source is checked again after the ticket is taken. An
|
|
103
|
+
* identity already linked to another account → `identity.taken`, the ticket kept. On success the ticket is taken atomically (a concurrent
|
|
104
|
+
* submission gets `sso.link_expired`), the identity is linked as `sso` (or the account's `bind`
|
|
105
|
+
* row upgraded) and a session is created exactly as a password sign-in; an account that must
|
|
106
|
+
* change its password is sent there by the web as after a password sign-in.
|
|
107
|
+
*/
|
|
108
|
+
link(body: z.infer<typeof LinkBodySchema>, req: FastifyRequest, reply: FastifyReply): Promise<{
|
|
109
|
+
account: Account;
|
|
110
|
+
returnTo: string;
|
|
111
|
+
}>;
|
|
40
112
|
}
|
|
113
|
+
/**
|
|
114
|
+
* IM binding confirmation (`/api/v1/bind/:token`, web session only): GET shows the identity to
|
|
115
|
+
* bind, POST binds it to the signed-in account. The token is single use; an identity linked to
|
|
116
|
+
* another account → 409 `identity.taken`.
|
|
117
|
+
*/
|
|
41
118
|
export declare class BindController {
|
|
42
119
|
private readonly binding;
|
|
43
120
|
constructor(binding: IdentityBinding);
|
|
@@ -51,9 +128,16 @@ export declare class BindController {
|
|
|
51
128
|
/** 本人绑定的外部身份(`/api/v1/me/identities`):列出、解除。 */
|
|
52
129
|
export declare class MeIdentitiesController {
|
|
53
130
|
private readonly external;
|
|
54
|
-
|
|
131
|
+
private readonly linked;
|
|
132
|
+
constructor(external: ExternalIdentities, linked: LinkedAccountsService);
|
|
133
|
+
/**
|
|
134
|
+
* The person's identities with their IM and sign-in capabilities, and the enabled login methods
|
|
135
|
+
* they can still link (the linked accounts page).
|
|
136
|
+
*/
|
|
55
137
|
list(principal: Principal): Promise<{
|
|
56
|
-
identities:
|
|
138
|
+
identities: LinkedAccountRow[];
|
|
139
|
+
linkable: LinkableMethod[];
|
|
57
140
|
}>;
|
|
58
141
|
unlink(principal: Principal, source: string, externalId: string): Promise<void>;
|
|
59
142
|
}
|
|
143
|
+
export {};
|
|
@@ -8,15 +8,35 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
8
8
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
9
|
};
|
|
10
10
|
import { Controller, Delete, Get, HttpCode, Inject, Param, Post, Query, Req, Res, } from "@nestjs/common";
|
|
11
|
+
import { z } from "zod";
|
|
12
|
+
import { ApiError } from "../errors.js";
|
|
11
13
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
14
|
+
import { CredentialThrottler } from "../infra/throttler/credential-throttler.js";
|
|
15
|
+
import { createZodDto } from "../infra/validation/create-zod-dto.js";
|
|
16
|
+
import { ZBody } from "../infra/validation/zod-params.js";
|
|
12
17
|
import { AccountsService } from "./accounts.js";
|
|
13
|
-
import { clientMeta } from "./auth.controller.js";
|
|
18
|
+
import { clientMeta, LOGIN_THROTTLERS } from "./auth.controller.js";
|
|
14
19
|
import { IdentityBinding } from "./binding.js";
|
|
15
20
|
import { setSessionCookies } from "./cookies.js";
|
|
16
21
|
import { ExternalIdentities } from "./external.js";
|
|
22
|
+
import { LinkedAccountsService, } from "./linked-accounts.js";
|
|
17
23
|
import { CurrentPrincipal, Public, requireUser, SessionOnly } from "./principal.js";
|
|
18
24
|
import { SessionService } from "./sessions.js";
|
|
19
|
-
import { SSO_BINDING_COOKIE, SSO_COOKIE_PATH, SSO_STATE_TTL_SECONDS, SsoFlow, ssoBrowserBinding, } from "./sso.js";
|
|
25
|
+
import { SSO_BINDING_COOKIE, SSO_COOKIE_PATH, SSO_STATE_TTL_SECONDS, SsoFlow, ssoBrowserBinding, withError, } from "./sso.js";
|
|
26
|
+
import { linkExpired, SSO_LINK_PAGE_PATH, SSO_LINK_TTL_SECONDS, SsoLinkTickets, } from "./sso-link.js";
|
|
27
|
+
const LinkBodySchema = z.object({
|
|
28
|
+
ticket: z.string().max(100),
|
|
29
|
+
login: z.string().max(256),
|
|
30
|
+
password: z.string(),
|
|
31
|
+
});
|
|
32
|
+
class LinkBody extends createZodDto(LinkBodySchema, "SsoLinkBody") {
|
|
33
|
+
}
|
|
34
|
+
const StartLinkBodySchema = z.object({
|
|
35
|
+
intent: z.literal("link"),
|
|
36
|
+
returnTo: z.string().max(2000).optional(),
|
|
37
|
+
});
|
|
38
|
+
class StartLinkBody extends createZodDto(StartLinkBodySchema, "SsoStartLinkBody") {
|
|
39
|
+
}
|
|
20
40
|
const MAX_QUERY_KEYS = 50;
|
|
21
41
|
const MAX_QUERY_VALUE = 4096;
|
|
22
42
|
/** 查询参数只取单值字符串(重复参数 / 数组 / 超长值丢弃)。 */
|
|
@@ -37,43 +57,93 @@ let SsoController = class SsoController {
|
|
|
37
57
|
sessions;
|
|
38
58
|
accounts;
|
|
39
59
|
config;
|
|
40
|
-
|
|
60
|
+
linkTickets;
|
|
61
|
+
external;
|
|
62
|
+
throttler;
|
|
63
|
+
constructor(flow, sessions, accounts, config, linkTickets, external, throttler) {
|
|
41
64
|
this.flow = flow;
|
|
42
65
|
this.sessions = sessions;
|
|
43
66
|
this.accounts = accounts;
|
|
44
67
|
this.config = config;
|
|
68
|
+
this.linkTickets = linkTickets;
|
|
69
|
+
this.external = external;
|
|
70
|
+
this.throttler = throttler;
|
|
71
|
+
}
|
|
72
|
+
async sources() {
|
|
73
|
+
return { sources: await this.flow.sources() };
|
|
45
74
|
}
|
|
46
|
-
|
|
47
|
-
|
|
75
|
+
/**
|
|
76
|
+
* Starts a sign-in: 302 to the source's authorize URL, writing the browser binding cookie
|
|
77
|
+
* `cap_sso` (HttpOnly, SameSite=Lax: the source's redirect back is a cross-site top-level GET,
|
|
78
|
+
* which Lax sends; Path only `/api/v1/auth/sso`). Always a sign-in: `intent=link` is refused
|
|
79
|
+
* with `sso.session_mismatch` and no state, because a cross-site page can trigger this GET with
|
|
80
|
+
* the person's Lax session cookie and would link whatever external account that browser is
|
|
81
|
+
* signed in to (a link intent starts from `POST …/start`).
|
|
82
|
+
*/
|
|
83
|
+
async start(plugin, returnTo, intent, req, reply) {
|
|
84
|
+
if (intent === "link") {
|
|
85
|
+
await reply
|
|
86
|
+
.header("cache-control", "no-store")
|
|
87
|
+
.redirect(this.flow.loginError("sso.session_mismatch"), 302);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
const binding = ssoBrowserBinding(req.cookies[SSO_BINDING_COOKIE]);
|
|
91
|
+
const location = await this.flow.start(plugin, typeof returnTo === "string" ? returnTo : undefined, binding);
|
|
92
|
+
this.setBindingCookie(reply, binding, SSO_STATE_TTL_SECONDS);
|
|
93
|
+
await reply.header("cache-control", "no-store").redirect(location, 302);
|
|
48
94
|
}
|
|
49
95
|
/**
|
|
50
|
-
*
|
|
51
|
-
*
|
|
96
|
+
* Starts a link intent (the linked accounts page, spec §4): web session only, and as an unsafe
|
|
97
|
+
* method it needs the CSRF header (global guard), so no other site can start it. The state
|
|
98
|
+
* records the session's account; the callback must carry the same session. Writes the binding
|
|
99
|
+
* cookie as the GET start does and returns where the browser goes next: the source's authorize
|
|
100
|
+
* URL, or, on failure, the page with `?error=<code>`.
|
|
52
101
|
*/
|
|
53
|
-
async
|
|
102
|
+
async startLink(plugin, body, principal, req, reply) {
|
|
103
|
+
const p = requireUser(principal);
|
|
54
104
|
const binding = ssoBrowserBinding(req.cookies[SSO_BINDING_COOKIE]);
|
|
55
|
-
|
|
56
|
-
|
|
105
|
+
const location = await this.flow.start(plugin, body.returnTo, binding, p.account.id, body.intent);
|
|
106
|
+
this.setBindingCookie(reply, binding, SSO_STATE_TTL_SECONDS);
|
|
107
|
+
reply.header("cache-control", "no-store");
|
|
108
|
+
return { location };
|
|
109
|
+
}
|
|
110
|
+
setBindingCookie(reply, binding, maxAge) {
|
|
57
111
|
reply.setCookie(SSO_BINDING_COOKIE, binding, {
|
|
58
112
|
path: SSO_COOKIE_PATH,
|
|
59
113
|
httpOnly: true,
|
|
60
114
|
sameSite: "lax",
|
|
61
115
|
secure: this.flow.cookieSecure(),
|
|
62
|
-
maxAge
|
|
116
|
+
maxAge,
|
|
63
117
|
});
|
|
64
|
-
await reply.header("cache-control", "no-store").redirect(location, 302);
|
|
65
118
|
}
|
|
66
119
|
/**
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
120
|
+
* The identity source's redirect back: state and binding cookie checked → the plugin verifies
|
|
121
|
+
* the external identity → spec §4's decision ({@link SsoFlow.callback}). A sign-in creates a
|
|
122
|
+
* session, writes the session cookies and 302s to the page (`http.publicUrl` + returnTo); a
|
|
123
|
+
* disabled account → the sign-in page with `auth.account_disabled`, no session. A link intent
|
|
124
|
+
* keeps its session and goes back to its page (its failures too, with `?error=<code>`). The link
|
|
125
|
+
* page branch keeps the binding cookie (renewed for the ticket's lifetime: the link page's routes
|
|
126
|
+
* need it) and 302s to `/login/link?ticket=…`; every other outcome clears it.
|
|
71
127
|
*/
|
|
72
128
|
async callback(plugin, q, principal, req, reply) {
|
|
73
|
-
const
|
|
129
|
+
const binding = req.cookies[SSO_BINDING_COOKIE];
|
|
130
|
+
const r = await this.flow.callback(plugin, stringQuery(q), binding, sessionAccount(principal));
|
|
74
131
|
let location;
|
|
75
132
|
if (!r.ok) {
|
|
76
|
-
location =
|
|
133
|
+
location =
|
|
134
|
+
r.returnTo === undefined
|
|
135
|
+
? this.flow.loginError(r.error === "identity.taken" ? "sso.provider_error" : r.error)
|
|
136
|
+
: this.flow.webUrl(withError(r.returnTo, r.error));
|
|
137
|
+
}
|
|
138
|
+
else if (r.kind === "link_page") {
|
|
139
|
+
// the binding value is the one the state was checked against
|
|
140
|
+
this.setBindingCookie(reply, binding, SSO_LINK_TTL_SECONDS);
|
|
141
|
+
const target = this.flow.webUrl(`${SSO_LINK_PAGE_PATH}?ticket=${encodeURIComponent(r.ticket)}`);
|
|
142
|
+
await reply.header("cache-control", "no-store").redirect(target, 302);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
else if (r.kind === "linked") {
|
|
146
|
+
location = this.flow.webUrl(r.returnTo);
|
|
77
147
|
}
|
|
78
148
|
else {
|
|
79
149
|
const account = await this.accounts.get(r.accountId);
|
|
@@ -89,6 +159,94 @@ let SsoController = class SsoController {
|
|
|
89
159
|
reply.clearCookie(SSO_BINDING_COOKIE, { path: SSO_COOKIE_PATH });
|
|
90
160
|
await reply.header("cache-control", "no-store").redirect(location, 302);
|
|
91
161
|
}
|
|
162
|
+
/**
|
|
163
|
+
* The link page's view of a pending link (spec §5): needs the ticket and the matching binding
|
|
164
|
+
* cookie (`sso.link_expired` / `sso.session_mismatch`); a source switched off since →
|
|
165
|
+
* `sso.link_expired` (the ticket is dropped). Says whether the external account is already
|
|
166
|
+
* linked to some account (an IM `bind` row), never to which.
|
|
167
|
+
*/
|
|
168
|
+
async linkView(ticket, req) {
|
|
169
|
+
const t = typeof ticket === "string" ? ticket : "";
|
|
170
|
+
const link = await this.linkTickets.peek(t, req.cookies[SSO_BINDING_COOKIE]);
|
|
171
|
+
const src = await this.flow.provider(link.plugin);
|
|
172
|
+
if (!src) {
|
|
173
|
+
await this.linkTickets.discard(t);
|
|
174
|
+
throw linkExpired();
|
|
175
|
+
}
|
|
176
|
+
const row = await this.external.peekRow(link.identity);
|
|
177
|
+
return {
|
|
178
|
+
plugin: link.plugin,
|
|
179
|
+
label: { zh: src.label.zh, en: src.label.en },
|
|
180
|
+
tenantId: link.identity.tenantId,
|
|
181
|
+
displayName: link.identity.displayName,
|
|
182
|
+
...(link.identity.avatarUrl !== undefined && { avatarUrl: link.identity.avatarUrl }),
|
|
183
|
+
linkedToAnother: row !== undefined,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Completes a pending link with the person's username and password (spec §5). Public; the
|
|
188
|
+
* global guard requires the CSRF header on this unsafe public route, and the binding cookie must
|
|
189
|
+
* match (it relies on no sibling origin being able to set cookies for the kernel's host, see
|
|
190
|
+
* `SsoLinkTickets`). The password goes through the same service and the same credential
|
|
191
|
+
* throttlers as `POST /auth/login` (R25); each check first reserves one of the ticket's attempts
|
|
192
|
+
* atomically, and a wrong password keeps it (the fifth burns the ticket). A disabled account →
|
|
193
|
+
* `auth.account_disabled` (its password was right: the ticket's attempt and the throttler
|
|
194
|
+
* reservation are given back). The login source is checked again after the ticket is taken. An
|
|
195
|
+
* identity already linked to another account → `identity.taken`, the ticket kept. On success the ticket is taken atomically (a concurrent
|
|
196
|
+
* submission gets `sso.link_expired`), the identity is linked as `sso` (or the account's `bind`
|
|
197
|
+
* row upgraded) and a session is created exactly as a password sign-in; an account that must
|
|
198
|
+
* change its password is sent there by the web as after a password sign-in.
|
|
199
|
+
*/
|
|
200
|
+
async link(body, req, reply) {
|
|
201
|
+
const binding = req.cookies[SSO_BINDING_COOKIE];
|
|
202
|
+
const pending = await this.linkTickets.peek(body.ticket, binding);
|
|
203
|
+
if (!(await this.flow.provider(pending.plugin))) {
|
|
204
|
+
await this.linkTickets.discard(body.ticket);
|
|
205
|
+
throw linkExpired();
|
|
206
|
+
}
|
|
207
|
+
// one of the ticket's attempts first (atomic: concurrent wrong passwords never exceed the
|
|
208
|
+
// limit), then one on the login throttlers, before checking the password (as POST /auth/login)
|
|
209
|
+
await this.linkTickets.reserveAttempt(body.ticket);
|
|
210
|
+
let account;
|
|
211
|
+
try {
|
|
212
|
+
await this.throttler.reserve(LOGIN_THROTTLERS, req, reply);
|
|
213
|
+
try {
|
|
214
|
+
account = await this.accounts.authenticateLocal(body.login, body.password);
|
|
215
|
+
}
|
|
216
|
+
catch (e) {
|
|
217
|
+
// a disabled account's password is right: no failed attempt, the reservation given back
|
|
218
|
+
if (e instanceof ApiError && e.code === "auth.account_disabled") {
|
|
219
|
+
await this.throttler.succeeded(LOGIN_THROTTLERS, req);
|
|
220
|
+
}
|
|
221
|
+
throw e;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
catch (e) {
|
|
225
|
+
// rate limited or disabled: the ticket's attempt is given back
|
|
226
|
+
await this.linkTickets.refundAttempt(body.ticket);
|
|
227
|
+
throw e;
|
|
228
|
+
}
|
|
229
|
+
if (!account) {
|
|
230
|
+
await this.linkTickets.failedAttempt(body.ticket);
|
|
231
|
+
throw new ApiError("auth.invalid_credentials", "Invalid login or password");
|
|
232
|
+
}
|
|
233
|
+
await this.throttler.succeeded(LOGIN_THROTTLERS, req);
|
|
234
|
+
// refused before the ticket is taken, so the person may try the other account's password
|
|
235
|
+
const row = await this.external.peekRow(pending.identity);
|
|
236
|
+
if (row !== undefined && row.accountId !== account.id) {
|
|
237
|
+
await this.linkTickets.refundAttempt(body.ticket);
|
|
238
|
+
throw identityTaken();
|
|
239
|
+
}
|
|
240
|
+
const link = await this.linkTickets.redeem(body.ticket, binding);
|
|
241
|
+
// the source may have been switched off while the password was checked: no row then
|
|
242
|
+
if (!(await this.flow.provider(link.plugin)))
|
|
243
|
+
throw linkExpired();
|
|
244
|
+
await this.external.linkVerified(account.id, link.identity, "link_page");
|
|
245
|
+
const session = await this.sessions.create(account.id, clientMeta(req));
|
|
246
|
+
setSessionCookies(reply, session, this.config.get());
|
|
247
|
+
reply.clearCookie(SSO_BINDING_COOKIE, { path: SSO_COOKIE_PATH });
|
|
248
|
+
return { account, returnTo: link.returnTo };
|
|
249
|
+
}
|
|
92
250
|
};
|
|
93
251
|
__decorate([
|
|
94
252
|
Get("sources"),
|
|
@@ -99,10 +257,20 @@ __decorate([
|
|
|
99
257
|
Public(),
|
|
100
258
|
__param(0, Param("plugin")),
|
|
101
259
|
__param(1, Query("returnTo")),
|
|
102
|
-
__param(2,
|
|
260
|
+
__param(2, Query("intent")),
|
|
103
261
|
__param(3, Req()),
|
|
104
262
|
__param(4, Res())
|
|
105
263
|
], SsoController.prototype, "start", null);
|
|
264
|
+
__decorate([
|
|
265
|
+
Post("sso/:plugin/start"),
|
|
266
|
+
SessionOnly(),
|
|
267
|
+
HttpCode(200),
|
|
268
|
+
__param(0, Param("plugin")),
|
|
269
|
+
__param(1, ZBody(StartLinkBody)),
|
|
270
|
+
__param(2, CurrentPrincipal()),
|
|
271
|
+
__param(3, Req()),
|
|
272
|
+
__param(4, Res({ passthrough: true }))
|
|
273
|
+
], SsoController.prototype, "startLink", null);
|
|
106
274
|
__decorate([
|
|
107
275
|
Get("sso/:plugin/callback"),
|
|
108
276
|
Public(),
|
|
@@ -112,24 +280,43 @@ __decorate([
|
|
|
112
280
|
__param(3, Req()),
|
|
113
281
|
__param(4, Res())
|
|
114
282
|
], SsoController.prototype, "callback", null);
|
|
283
|
+
__decorate([
|
|
284
|
+
Get("sso/link"),
|
|
285
|
+
Public(),
|
|
286
|
+
__param(0, Query("ticket")),
|
|
287
|
+
__param(1, Req())
|
|
288
|
+
], SsoController.prototype, "linkView", null);
|
|
289
|
+
__decorate([
|
|
290
|
+
Post("sso/link"),
|
|
291
|
+
Public(),
|
|
292
|
+
HttpCode(200),
|
|
293
|
+
__param(0, ZBody(LinkBody)),
|
|
294
|
+
__param(1, Req()),
|
|
295
|
+
__param(2, Res({ passthrough: true }))
|
|
296
|
+
], SsoController.prototype, "link", null);
|
|
115
297
|
SsoController = __decorate([
|
|
116
298
|
Controller("api/v1/auth"),
|
|
117
299
|
__param(0, Inject(SsoFlow)),
|
|
118
300
|
__param(1, Inject(SessionService)),
|
|
119
301
|
__param(2, Inject(AccountsService)),
|
|
120
|
-
__param(3, Inject(KernelConfigService))
|
|
302
|
+
__param(3, Inject(KernelConfigService)),
|
|
303
|
+
__param(4, Inject(SsoLinkTickets)),
|
|
304
|
+
__param(5, Inject(ExternalIdentities)),
|
|
305
|
+
__param(6, Inject(CredentialThrottler))
|
|
121
306
|
], SsoController);
|
|
122
307
|
export { SsoController };
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
* 令牌单次有效;身份已绑定他人 → 409 `identity.taken`。
|
|
126
|
-
*/
|
|
127
|
-
/** 请求带着的 Web 会话的账号(PAT / 未登录时 undefined)。 */
|
|
308
|
+
const identityTaken = () => new ApiError("identity.taken", "This external identity is already linked to another account");
|
|
309
|
+
/** The account of the request's web session (undefined for a PAT or when signed out). */
|
|
128
310
|
function sessionAccount(principal) {
|
|
129
311
|
return principal?.kind === "user" && principal.via === "session"
|
|
130
312
|
? principal.account.id
|
|
131
313
|
: undefined;
|
|
132
314
|
}
|
|
315
|
+
/**
|
|
316
|
+
* IM binding confirmation (`/api/v1/bind/:token`, web session only): GET shows the identity to
|
|
317
|
+
* bind, POST binds it to the signed-in account. The token is single use; an identity linked to
|
|
318
|
+
* another account → 409 `identity.taken`.
|
|
319
|
+
*/
|
|
133
320
|
let BindController = class BindController {
|
|
134
321
|
binding;
|
|
135
322
|
constructor(binding) {
|
|
@@ -165,12 +352,18 @@ export { BindController };
|
|
|
165
352
|
/** 本人绑定的外部身份(`/api/v1/me/identities`):列出、解除。 */
|
|
166
353
|
let MeIdentitiesController = class MeIdentitiesController {
|
|
167
354
|
external;
|
|
168
|
-
|
|
355
|
+
linked;
|
|
356
|
+
constructor(external, linked) {
|
|
169
357
|
this.external = external;
|
|
358
|
+
this.linked = linked;
|
|
170
359
|
}
|
|
360
|
+
/**
|
|
361
|
+
* The person's identities with their IM and sign-in capabilities, and the enabled login methods
|
|
362
|
+
* they can still link (the linked accounts page).
|
|
363
|
+
*/
|
|
171
364
|
async list(principal) {
|
|
172
365
|
const p = requireUser(principal);
|
|
173
|
-
return
|
|
366
|
+
return this.linked.list(p.account.id);
|
|
174
367
|
}
|
|
175
368
|
async unlink(principal, source, externalId) {
|
|
176
369
|
const p = requireUser(principal);
|
|
@@ -191,6 +384,7 @@ __decorate([
|
|
|
191
384
|
], MeIdentitiesController.prototype, "unlink", null);
|
|
192
385
|
MeIdentitiesController = __decorate([
|
|
193
386
|
Controller("api/v1/me/identities"),
|
|
194
|
-
__param(0, Inject(ExternalIdentities))
|
|
387
|
+
__param(0, Inject(ExternalIdentities)),
|
|
388
|
+
__param(1, Inject(LinkedAccountsService))
|
|
195
389
|
], MeIdentitiesController);
|
|
196
390
|
export { MeIdentitiesController };
|