@capybara-hq/kernel 0.1.0-rc.103 → 0.1.0-rc.105

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.
Files changed (55) hide show
  1. package/dist/catalog/marketplaces.service.d.ts +1 -1
  2. package/dist/conversations/conversations.service.d.ts +2 -0
  3. package/dist/conversations/conversations.service.js +6 -1
  4. package/dist/conversations/events.d.ts +12 -0
  5. package/dist/conversations/events.js +23 -0
  6. package/dist/errors.d.ts +13 -0
  7. package/dist/errors.js +13 -0
  8. package/dist/evals/reconstruct.d.ts +9 -1
  9. package/dist/evals/reconstruct.js +7 -0
  10. package/dist/handoff/app-schemes.d.ts +28 -0
  11. package/dist/handoff/app-schemes.js +41 -0
  12. package/dist/handoff/handoff-paths.d.ts +26 -0
  13. package/dist/handoff/handoff-paths.js +25 -0
  14. package/dist/handoff/handoff-tickets.d.ts +28 -0
  15. package/dist/handoff/handoff-tickets.js +111 -0
  16. package/dist/handoff/handoff.controller.d.ts +24 -0
  17. package/dist/handoff/handoff.controller.js +74 -0
  18. package/dist/handoff/handoff.module.d.ts +7 -0
  19. package/dist/handoff/handoff.module.js +26 -0
  20. package/dist/handoff/handoff.schemas.d.ts +13 -0
  21. package/dist/handoff/handoff.schemas.js +3 -0
  22. package/dist/handoff/handoff.service.d.ts +49 -0
  23. package/dist/handoff/handoff.service.js +96 -0
  24. package/dist/http/api.module.js +8 -0
  25. package/dist/http/meta.controller.d.ts +1 -0
  26. package/dist/http/meta.controller.js +7 -0
  27. package/dist/identity/sso.controller.d.ts +30 -6
  28. package/dist/identity/sso.controller.js +51 -17
  29. package/dist/identity/sso.d.ts +10 -2
  30. package/dist/identity/sso.js +15 -3
  31. package/dist/overrides.d.ts +4 -4
  32. package/dist/overrides.js +1 -1
  33. package/dist/platform/exclusions.js +5 -0
  34. package/dist/platform/ops/connectors.ops.js +4 -2
  35. package/dist/runtime/compaction.service.d.ts +6 -3
  36. package/dist/runtime/compaction.service.js +7 -6
  37. package/dist/runtime/context/build.d.ts +13 -3
  38. package/dist/runtime/context/build.js +26 -6
  39. package/dist/runtime/context/compaction.d.ts +29 -1
  40. package/dist/runtime/context/compaction.js +108 -39
  41. package/dist/runtime/context/run-outcome.d.ts +10 -0
  42. package/dist/runtime/context/run-outcome.js +92 -0
  43. package/dist/runtime/model-call.d.ts +9 -0
  44. package/dist/runtime/model-call.js +63 -7
  45. package/dist/runtime/project/knowledge.service.d.ts +16 -7
  46. package/dist/runtime/project/knowledge.service.js +31 -13
  47. package/dist/tools/connectors.service.d.ts +4 -13
  48. package/dist/tools/connectors.service.js +12 -21
  49. package/dist/tools/oauth/flow.d.ts +16 -2
  50. package/dist/tools/oauth/flow.js +23 -4
  51. package/dist/tools/oauth/oauth.controller.d.ts +19 -7
  52. package/dist/tools/oauth/oauth.controller.js +42 -12
  53. package/dist/tools/oauth/oauth.schemas.d.ts +14 -1
  54. package/dist/tools/oauth/oauth.schemas.js +4 -1
  55. package/package.json +3 -3
@@ -208,7 +208,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
208
208
  /** The host versions (an entry's `minKernel` is judged against them). */
209
209
  export declare const HOST_VERSIONS: {
210
210
  readonly kernel: string;
211
- readonly sdk: "0.1.0-rc.83";
211
+ readonly sdk: "0.1.0-rc.84";
212
212
  };
213
213
  /** Whether this deployment satisfies the entry's `minKernel`. */
214
214
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -139,6 +139,8 @@ export interface SubagentView {
139
139
  usage: UsageTotals;
140
140
  pendingApprovalIds: string[];
141
141
  pendingQuestionIds: string[];
142
+ /** The pending questions that are watched waits (`InputRequired.watch`): a subset of the above. */
143
+ watchedQuestionIds: string[];
142
144
  }
143
145
  /**
144
146
  * What a message skipped (reply-while-question spec §8.1, network ask-to-allow spec §6.7): its
@@ -826,7 +826,11 @@ let ConversationsService = class ConversationsService {
826
826
  ORDER BY a.created_at, a.id) AS approval_ids,
827
827
  ARRAY(SELECT q.id FROM capybara.questions q
828
828
  WHERE q.conversation_id = c.id AND q.status = 'pending' AND q.expires_at > now()
829
- ORDER BY q.created_at, q.id) AS question_ids
829
+ ORDER BY q.created_at, q.id) AS question_ids,
830
+ ARRAY(SELECT q.id FROM capybara.questions q
831
+ WHERE q.conversation_id = c.id AND q.status = 'pending' AND q.expires_at > now()
832
+ AND (q.spec->>'watch')::boolean IS TRUE
833
+ ORDER BY q.created_at, q.id) AS watched_question_ids
830
834
  FROM page c
831
835
  CROSS JOIN LATERAL (
832
836
  SELECT sd.child_run_id FROM capybara.subagent_dispatches sd
@@ -850,6 +854,7 @@ let ConversationsService = class ConversationsService {
850
854
  usage: toUsage(r),
851
855
  pendingApprovalIds: r.approval_ids,
852
856
  pendingQuestionIds: r.question_ids,
857
+ watchedQuestionIds: r.watched_question_ids,
853
858
  }));
854
859
  const next = rows.length > opts.limit ? (subagents.at(-1)?.id ?? null) : null;
855
860
  return { subagents, next };
@@ -1068,6 +1068,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1068
1068
  sandbox: z.ZodOptional<z.ZodString>;
1069
1069
  }, z.core.$strict>>;
1070
1070
  reminderSeqs: z.ZodArray<z.ZodNumber>;
1071
+ runOutcomeSeqs: z.ZodOptional<z.ZodArray<z.ZodNumber>>;
1071
1072
  maxOutputTokens: z.ZodNumber;
1072
1073
  params: z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
1073
1074
  droppedParams: z.ZodOptional<z.ZodArray<z.ZodString>>;
@@ -2051,6 +2052,17 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
2051
2052
  reason: z.ZodString;
2052
2053
  step: z.ZodNumber;
2053
2054
  }, z.core.$strip>;
2055
+ }, z.core.$strip>, z.ZodObject<{
2056
+ type: z.ZodLiteral<"compaction_skipped">;
2057
+ payload: z.ZodObject<{
2058
+ reason: z.ZodEnum<{
2059
+ nothing_to_summarize: "nothing_to_summarize";
2060
+ too_few_turns: "too_few_turns";
2061
+ }>;
2062
+ keepRecentTurns: z.ZodOptional<z.ZodNumber>;
2063
+ turns: z.ZodNumber;
2064
+ step: z.ZodNumber;
2065
+ }, z.core.$strip>;
2054
2066
  }, z.core.$strip>, z.ZodObject<{
2055
2067
  type: z.ZodLiteral<"run_finished">;
2056
2068
  payload: z.ZodObject<{
@@ -969,6 +969,13 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
969
969
  systemHash: z.string(),
970
970
  permissionContext: PermissionContextMetaV1Schema.optional(),
971
971
  reminderSeqs: z.array(seqNo),
972
+ /**
973
+ * The `run_failed` / `run_aborted` events whose run outcome note the request rendered
974
+ * (`runtime/context/run-outcome.ts`, maintainer decision 2026-11-28), in seq order; absent
975
+ * when it rendered none. Reconstruction reports `run_outcome_note` when the rebuild
976
+ * renders another set (a request sent before the note existed).
977
+ */
978
+ runOutcomeSeqs: z.array(seqNo).optional(),
972
979
  /**
973
980
  * The request's output cap: `min(model cap, maxOutputTokens knob ??
974
981
  * runtime.maxOutputTokens)`, clamped by the hard fit guard.
@@ -1782,6 +1789,22 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
1782
1789
  /** The step the compaction ran in, as on `compaction_summary`. */
1783
1790
  step: count,
1784
1791
  })),
1792
+ /**
1793
+ * A manual compaction (a compact run, context compaction spec §4.7) found nothing to summarize:
1794
+ * nothing precedes the kept tail (the latest user turn, or its latest tool pairs; maintainer
1795
+ * decision 2026-11-28), reason `nothing_to_summarize`. Display only, never model-visible; written
1796
+ * once per compact run. An automatic compaction's skip writes nothing. `too_few_turns` (with
1797
+ * `keepRecentTurns`) is the reason an earlier manual plan wrote, still read.
1798
+ */
1799
+ ev("compaction_skipped", z.object({
1800
+ reason: z.enum(["nothing_to_summarize", "too_few_turns"]),
1801
+ /** The effective `keepRecentTurns` an earlier manual plan used (`too_few_turns` only). */
1802
+ keepRecentTurns: count.optional(),
1803
+ /** The user turns since the last summary (all of them without one). */
1804
+ turns: count,
1805
+ /** The step the compaction ran in (0 for a manual compact run). */
1806
+ step: count,
1807
+ })),
1785
1808
  ev("run_finished", z.object({
1786
1809
  /**
1787
1810
  * `budget`: a sub-agent stopped at its parent run's token cap (phase C, spec §8.3).
package/dist/errors.d.ts CHANGED
@@ -38,6 +38,19 @@ export declare const ERROR_CODES: {
38
38
  readonly "app_auth.code_invalid": 400;
39
39
  /** Native-app sign-in needs `http.publicUrl` (the issuer the app checks). */
40
40
  readonly "app_auth.unavailable": 503;
41
+ /**
42
+ * A browser handoff start names a return scheme whose `<scheme>://auth/callback` is not in
43
+ * `auth.appRedirectUris` (exact match), or `http.publicUrl` is not set.
44
+ */
45
+ readonly "handoff.scheme_not_allowed": 400;
46
+ /** The browser handoff ticket is unknown, expired or already used; start again in the app. */
47
+ readonly "handoff.invalid": 410;
48
+ /**
49
+ * The browser is signed in as another account than the one that started the handoff (the
50
+ * ticket is spent); details `[{ login, displayName, email }]` of the ticket's account (`login`
51
+ * its local login, null without one; `email` null when unset).
52
+ */
53
+ readonly "handoff.account_mismatch": 403;
41
54
  readonly "token.not_found": 404;
42
55
  readonly "org.not_found": 404;
43
56
  readonly "org.creation_disabled": 403;
package/dist/errors.js CHANGED
@@ -38,6 +38,19 @@ export const ERROR_CODES = {
38
38
  "app_auth.code_invalid": 400,
39
39
  /** Native-app sign-in needs `http.publicUrl` (the issuer the app checks). */
40
40
  "app_auth.unavailable": 503,
41
+ /**
42
+ * A browser handoff start names a return scheme whose `<scheme>://auth/callback` is not in
43
+ * `auth.appRedirectUris` (exact match), or `http.publicUrl` is not set.
44
+ */
45
+ "handoff.scheme_not_allowed": 400,
46
+ /** The browser handoff ticket is unknown, expired or already used; start again in the app. */
47
+ "handoff.invalid": 410,
48
+ /**
49
+ * The browser is signed in as another account than the one that started the handoff (the
50
+ * ticket is spent); details `[{ login, displayName, email }]` of the ticket's account (`login`
51
+ * its local login, null without one; `email` null when unset).
52
+ */
53
+ "handoff.account_mismatch": 403,
41
54
  "token.not_found": 404,
42
55
  "org.not_found": 404,
43
56
  "org.creation_disabled": 403,
@@ -26,7 +26,8 @@ import { type CaseSnapshot } from "./snapshot.js";
26
26
  * 图片数 / 页数上限、对象被替换后 etag 变了等);
27
27
  * - `context_fit` (context compaction spec §4.9, never for a baseline): the candidate model's window
28
28
  * makes the hard fit guard plan a different trim than the recorded `model_call.request.fit` (the
29
- * recorded plan is replayed for a baseline; a candidate applies its recomputed plan).
29
+ * recorded plan is replayed for a baseline; a candidate applies its recomputed plan);
30
+ * - `run_outcome_note`: the rebuilt run outcome notes differ from the recorded `runOutcomeSeqs`.
30
31
  */
31
32
  /** 还原结果与原请求不一致的原因。 */
32
33
  export type DriftReason = "system_hash" | "tools_changed" | "tool_spec_missing" | "definition_missing"
@@ -51,6 +52,13 @@ export type DriftReason = "system_hash" | "tools_changed" | "tool_spec_missing"
51
52
  * goes out against the candidate's window.
52
53
  */
53
54
  | "context_fit"
55
+ /**
56
+ * The rebuild renders another set of run outcome notes (`runtime/context/run-outcome.ts`) than
57
+ * the request recorded in `model_call.request.runOutcomeSeqs`: a request sent before the note
58
+ * existed (maintainer decision 2026-11-28). Judged for every reconstruction: the notes come from
59
+ * the log alone, so a candidate cannot change them.
60
+ */
61
+ | "run_outcome_note"
54
62
  /** 整轮回放(T5):有工具调用没有匹配到记录(模型收到 REPLAY_NO_RECORDING)。 */
55
63
  | "tool_unmatched";
56
64
  export interface ReconstructOptions {
@@ -46,6 +46,7 @@ const DRIFT_ORDER = [
46
46
  "media_missing",
47
47
  "media_changed",
48
48
  "context_fit",
49
+ "run_outcome_note",
49
50
  "tool_unmatched",
50
51
  ];
51
52
  function findCall(events, seq) {
@@ -276,6 +277,12 @@ export function reconstructFromInputs(s, gathered, opts) {
276
277
  drift.add("tools_changed");
277
278
  }
278
279
  }
280
+ // run outcome notes: from the log alone, so only a request sent before they existed differs
281
+ const notes = meta.runOutcomeSeqs ?? [];
282
+ const recordedNotes = rec.runOutcomeSeqs ?? [];
283
+ if (notes.length !== recordedNotes.length || notes.some((x, i) => x !== recordedNotes[i])) {
284
+ drift.add("run_outcome_note");
285
+ }
279
286
  // 媒体:按附件 id 与记录比较
280
287
  const recordedMedia = new Map((rec.media ?? []).map((m) => [m.attachmentId, m]));
281
288
  for (const m of meta.media ?? []) {
@@ -0,0 +1,28 @@
1
+ import { z } from "zod";
2
+ /** A plain URL scheme (RFC 3986 letters, lowercase only so the match stays exact). */
3
+ export declare const APP_SCHEME_RE: RegExp;
4
+ /** The config a scheme decision reads (`KernelConfig` fits). */
5
+ export type AppSchemesConfig = {
6
+ http: {
7
+ publicUrl?: string | undefined;
8
+ };
9
+ auth: {
10
+ appRedirectUris: readonly string[];
11
+ };
12
+ };
13
+ /**
14
+ * The schemes `s` for which an entry of `auth.appRedirectUris` is exactly `${s}://auth/callback`,
15
+ * in list order; `[]` without `http.publicUrl` (no app sign-in, so no shell to return to).
16
+ */
17
+ export declare function appSchemes(config: AppSchemesConfig): string[];
18
+ /** A handoff start's return scheme: none passes; otherwise it must be one of {@link appSchemes}. */
19
+ export declare function assertReturnSchemeAllowed(config: AppSchemesConfig, scheme: string | undefined): void;
20
+ /**
21
+ * The `handoff` field of the connector connect and the login-method link start: present when a
22
+ * native shell asks to finish the flow in the system browser. `returnScheme` is the shell's own
23
+ * URL scheme (for the done page's way back into the app).
24
+ */
25
+ export declare const HandoffRequestSchema: z.ZodObject<{
26
+ returnScheme: z.ZodOptional<z.ZodString>;
27
+ }, z.core.$strict>;
28
+ export type HandoffRequest = z.infer<typeof HandoffRequestSchema>;
@@ -0,0 +1,41 @@
1
+ import { z } from "zod";
2
+ import { ApiError } from "../errors.js";
3
+ // The URL schemes of the native shells a browser handoff may send the person back to: pure, no
4
+ // Nest (shell external authorization spec §1, §3).
5
+ /** A plain URL scheme (RFC 3986 letters, lowercase only so the match stays exact). */
6
+ export const APP_SCHEME_RE = /^[a-z][a-z0-9+.-]{0,31}$/;
7
+ /** The app sign-in redirect URI a shell registers under its scheme (desktop client spec §6.5). */
8
+ const APP_CALLBACK_SUFFIX = "://auth/callback";
9
+ /**
10
+ * The schemes `s` for which an entry of `auth.appRedirectUris` is exactly `${s}://auth/callback`,
11
+ * in list order; `[]` without `http.publicUrl` (no app sign-in, so no shell to return to).
12
+ */
13
+ export function appSchemes(config) {
14
+ if (!config.http.publicUrl)
15
+ return [];
16
+ const out = [];
17
+ for (const uri of config.auth.appRedirectUris) {
18
+ if (!uri.endsWith(APP_CALLBACK_SUFFIX))
19
+ continue;
20
+ const scheme = uri.slice(0, -APP_CALLBACK_SUFFIX.length);
21
+ if (APP_SCHEME_RE.test(scheme) && !out.includes(scheme))
22
+ out.push(scheme);
23
+ }
24
+ return out;
25
+ }
26
+ /** A handoff start's return scheme: none passes; otherwise it must be one of {@link appSchemes}. */
27
+ export function assertReturnSchemeAllowed(config, scheme) {
28
+ if (scheme === undefined)
29
+ return;
30
+ if (!appSchemes(config).includes(scheme)) {
31
+ throw new ApiError("handoff.scheme_not_allowed", "This platform does not allow this app to finish authorizations in the browser (its <scheme>://auth/callback is not in auth.appRedirectUris)");
32
+ }
33
+ }
34
+ /**
35
+ * The `handoff` field of the connector connect and the login-method link start: present when a
36
+ * native shell asks to finish the flow in the system browser. `returnScheme` is the shell's own
37
+ * URL scheme (for the done page's way back into the app).
38
+ */
39
+ export const HandoffRequestSchema = z
40
+ .object({ returnScheme: z.string().min(1).max(64).optional() })
41
+ .strict();
@@ -0,0 +1,26 @@
1
+ /** What a handoff ticket holds (Redis, under the ticket's hash). */
2
+ export type HandoffRecord = {
3
+ kind: "connector";
4
+ accountId: string;
5
+ orgId: string;
6
+ connectorId: string;
7
+ /** The site path the shell started from (already checked as a site path). */
8
+ returnTo: string;
9
+ returnScheme?: string;
10
+ } | {
11
+ kind: "identity-link";
12
+ accountId: string;
13
+ plugin: string;
14
+ returnTo: string;
15
+ returnScheme?: string;
16
+ };
17
+ /** The web page that redeems a ticket: `<publicUrl>/handoff/<ticket>`. */
18
+ export declare const HANDOFF_PAGE_PATH = "/handoff";
19
+ /** The web page a handoff flow's callback returns to (next-intl adds the language prefix). */
20
+ export declare const HANDOFF_DONE_PATH = "/handoff/done";
21
+ /**
22
+ * The done page path for a handoff flow, used as the OAuth / SSO state's return page: what was
23
+ * authorized, the page the shell started from and its scheme (when it gave one). The callbacks
24
+ * append their result parameters (`connected` / `oauth_error`, `error`) as for any return page.
25
+ */
26
+ export declare function handoffDonePath(rec: HandoffRecord): string;
@@ -0,0 +1,25 @@
1
+ // The browser handoff's web paths and the record a ticket holds: a leaf module (no service
2
+ // imports), so both the OAuth connect flow and the SSO flow can build the done page path.
3
+ /** The web page that redeems a ticket: `<publicUrl>/handoff/<ticket>`. */
4
+ export const HANDOFF_PAGE_PATH = "/handoff";
5
+ /** The web page a handoff flow's callback returns to (next-intl adds the language prefix). */
6
+ export const HANDOFF_DONE_PATH = "/handoff/done";
7
+ /**
8
+ * The done page path for a handoff flow, used as the OAuth / SSO state's return page: what was
9
+ * authorized, the page the shell started from and its scheme (when it gave one). The callbacks
10
+ * append their result parameters (`connected` / `oauth_error`, `error`) as for any return page.
11
+ */
12
+ export function handoffDonePath(rec) {
13
+ const q = new URLSearchParams({ kind: rec.kind });
14
+ if (rec.kind === "connector") {
15
+ q.set("org", rec.orgId);
16
+ q.set("connector", rec.connectorId);
17
+ }
18
+ else {
19
+ q.set("plugin", rec.plugin);
20
+ }
21
+ q.set("returnTo", rec.returnTo);
22
+ if (rec.returnScheme !== undefined)
23
+ q.set("scheme", rec.returnScheme);
24
+ return `${HANDOFF_DONE_PATH}?${q.toString()}`;
25
+ }
@@ -0,0 +1,28 @@
1
+ import type { Redis } from "ioredis";
2
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
+ import { type HandoffRecord } from "./handoff-paths.js";
4
+ export { HANDOFF_DONE_PATH, type HandoffRecord, handoffDonePath } from "./handoff-paths.js";
5
+ /** A ticket's lifetime (seconds): the same as the OAuth state and the app sign-in attempt. */
6
+ export declare const HANDOFF_TTL_SECONDS = 600;
7
+ /**
8
+ * Browser handoff tickets (shell external authorization spec §1): a native shell's start stores
9
+ * what it checked and gets a single-use ticket for the web page `/handoff/<ticket>`, which the
10
+ * person opens in the system browser. 32 random bytes, stored hashed in Redis for 10 minutes,
11
+ * taken with GETDEL (one redeem wins across replicas). Nothing lives in process memory.
12
+ */
13
+ export declare class HandoffTickets {
14
+ private readonly redis;
15
+ private readonly config;
16
+ constructor(redis: Pick<Redis, "set" | "getdel">, config: Pick<KernelConfigService, "get">);
17
+ /** Stores the record and returns its ticket. */
18
+ create(rec: HandoffRecord): Promise<string>;
19
+ /**
20
+ * Takes the ticket's record and deletes it in one step; null when the ticket is malformed,
21
+ * unknown or used, or the stored value is not a handoff record.
22
+ */
23
+ take(ticket: string): Promise<HandoffRecord | null>;
24
+ /** The web page that redeems the ticket; needs `http.publicUrl`. */
25
+ url(ticket: string): string;
26
+ }
27
+ export declare class HandoffTicketsModule {
28
+ }
@@ -0,0 +1,111 @@
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 } from "node:crypto";
11
+ import { Inject, Injectable, Module } from "@nestjs/common";
12
+ import { z } from "zod";
13
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
14
+ import { REDIS } from "../infra/tokens.js";
15
+ import { isSafeReturnPath, publicUrlRequired } from "../tools/oauth/flow-paths.js";
16
+ import { APP_SCHEME_RE } from "./app-schemes.js";
17
+ import { HANDOFF_PAGE_PATH } from "./handoff-paths.js";
18
+ export { HANDOFF_DONE_PATH, handoffDonePath } from "./handoff-paths.js";
19
+ /** A ticket's lifetime (seconds): the same as the OAuth state and the app sign-in attempt. */
20
+ export const HANDOFF_TTL_SECONDS = 600;
21
+ /** The `cap_` prefix keeps the ticket masked in logged paths and queries. */
22
+ const TICKET_PREFIX = "cap_ho_";
23
+ const TICKET_RE = /^cap_ho_[A-Za-z0-9_-]{43}$/;
24
+ /**
25
+ * What a stored record must look like to be redeemed: a value that does not parse (another
26
+ * writer, a format from another version) is treated as no ticket, never trusted as written.
27
+ */
28
+ const ReturnTo = z.string().refine(isSafeReturnPath);
29
+ const ReturnScheme = z.string().regex(APP_SCHEME_RE).optional();
30
+ const HandoffRecordSchema = z.discriminatedUnion("kind", [
31
+ z.object({
32
+ kind: z.literal("connector"),
33
+ accountId: z.string().min(1),
34
+ orgId: z.string().min(1),
35
+ connectorId: z.string().min(1),
36
+ returnTo: ReturnTo,
37
+ returnScheme: ReturnScheme,
38
+ }),
39
+ z.object({
40
+ kind: z.literal("identity-link"),
41
+ accountId: z.string().min(1),
42
+ plugin: z.string().min(1),
43
+ returnTo: ReturnTo,
44
+ returnScheme: ReturnScheme,
45
+ }),
46
+ ]);
47
+ const sha256 = (s) => createHash("sha256").update(s).digest("base64url");
48
+ /** Redis holds only the ticket's hash: reading Redis gives no usable ticket. */
49
+ const ticketKey = (ticket) => `capk:handoff:${sha256(ticket)}`;
50
+ /**
51
+ * Browser handoff tickets (shell external authorization spec §1): a native shell's start stores
52
+ * what it checked and gets a single-use ticket for the web page `/handoff/<ticket>`, which the
53
+ * person opens in the system browser. 32 random bytes, stored hashed in Redis for 10 minutes,
54
+ * taken with GETDEL (one redeem wins across replicas). Nothing lives in process memory.
55
+ */
56
+ let HandoffTickets = class HandoffTickets {
57
+ redis;
58
+ config;
59
+ constructor(redis, config) {
60
+ this.redis = redis;
61
+ this.config = config;
62
+ }
63
+ /** Stores the record and returns its ticket. */
64
+ async create(rec) {
65
+ const ticket = `${TICKET_PREFIX}${randomBytes(32).toString("base64url")}`;
66
+ await this.redis.set(ticketKey(ticket), JSON.stringify(rec), "EX", HANDOFF_TTL_SECONDS);
67
+ return ticket;
68
+ }
69
+ /**
70
+ * Takes the ticket's record and deletes it in one step; null when the ticket is malformed,
71
+ * unknown or used, or the stored value is not a handoff record.
72
+ */
73
+ async take(ticket) {
74
+ if (!TICKET_RE.test(ticket))
75
+ return null;
76
+ const raw = await this.redis.getdel(ticketKey(ticket));
77
+ if (raw === null)
78
+ return null;
79
+ let value;
80
+ try {
81
+ value = JSON.parse(raw);
82
+ }
83
+ catch {
84
+ return null;
85
+ }
86
+ const parsed = HandoffRecordSchema.safeParse(value);
87
+ if (!parsed.success)
88
+ return null;
89
+ const { returnScheme, ...rest } = parsed.data;
90
+ return { ...rest, ...(returnScheme !== undefined && { returnScheme }) };
91
+ }
92
+ /** The web page that redeems the ticket; needs `http.publicUrl`. */
93
+ url(ticket) {
94
+ const publicUrl = this.config.get().http.publicUrl;
95
+ if (!publicUrl)
96
+ throw publicUrlRequired();
97
+ return `${publicUrl.replace(/\/+$/, "")}${HANDOFF_PAGE_PATH}/${ticket}`;
98
+ }
99
+ };
100
+ HandoffTickets = __decorate([
101
+ Injectable(),
102
+ __param(0, Inject(REDIS)),
103
+ __param(1, Inject(KernelConfigService))
104
+ ], HandoffTickets);
105
+ export { HandoffTickets };
106
+ let HandoffTicketsModule = class HandoffTicketsModule {
107
+ };
108
+ HandoffTicketsModule = __decorate([
109
+ Module({ providers: [HandoffTickets], exports: [HandoffTickets] })
110
+ ], HandoffTicketsModule);
111
+ export { HandoffTicketsModule };
@@ -0,0 +1,24 @@
1
+ import type { FastifyReply, FastifyRequest } from "fastify";
2
+ import { type Principal } from "../identity/principal.js";
3
+ import { SsoFlow } from "../identity/sso.js";
4
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
+ import { type HandoffRedeemBody, type HandoffRedeemResponse } from "./handoff.schemas.js";
6
+ import { HandoffService } from "./handoff.service.js";
7
+ /**
8
+ * Browser handoffs (shell external authorization spec §2): the web page `/handoff/<ticket>`,
9
+ * opened by a native shell in the system browser, redeems its ticket here.
10
+ */
11
+ export declare class HandoffController {
12
+ private readonly handoffs;
13
+ private readonly config;
14
+ private readonly sso;
15
+ constructor(handoffs: HandoffService, config: KernelConfigService, sso: SsoFlow);
16
+ /**
17
+ * Redeems a ticket in this signed-in browser (web session only, so the CSRF header of the global
18
+ * guard applies): starts the ticket's OAuth connect or login-method link here, writes this
19
+ * browser's binding cookie (`cap_oauth` / `cap_sso`, the same as the normal starts) and answers
20
+ * where the browser goes next. Errors: `handoff.invalid`, `handoff.account_mismatch`, and for a
21
+ * connector the start's own (`org.not_found`, `forbidden`, `connector.*`).
22
+ */
23
+ redeem(principal: Principal, body: HandoffRedeemBody, req: FastifyRequest, reply: FastifyReply): Promise<HandoffRedeemResponse>;
24
+ }
@@ -0,0 +1,74 @@
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 { Controller, HttpCode, Inject, Post, Req, Res } from "@nestjs/common";
11
+ import { CurrentPrincipal, requireUser, SessionOnly, } from "../identity/principal.js";
12
+ import { setSsoBindingCookie } from "../identity/sso.controller.js";
13
+ import { SSO_BINDING_COOKIE, SsoFlow } from "../identity/sso.js";
14
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
15
+ import { createZodDto } from "../infra/validation/create-zod-dto.js";
16
+ import { ZBody } from "../infra/validation/zod-params.js";
17
+ import { OAUTH_BINDING_COOKIE } from "../tools/oauth/flow.js";
18
+ import { setOAuthBindingCookie } from "../tools/oauth/oauth.controller.js";
19
+ import { HandoffRedeemBodySchema, } from "./handoff.schemas.js";
20
+ import { HandoffService } from "./handoff.service.js";
21
+ class RedeemBody extends createZodDto(HandoffRedeemBodySchema, "HandoffRedeemBody") {
22
+ }
23
+ /**
24
+ * Browser handoffs (shell external authorization spec §2): the web page `/handoff/<ticket>`,
25
+ * opened by a native shell in the system browser, redeems its ticket here.
26
+ */
27
+ let HandoffController = class HandoffController {
28
+ handoffs;
29
+ config;
30
+ sso;
31
+ constructor(handoffs, config, sso) {
32
+ this.handoffs = handoffs;
33
+ this.config = config;
34
+ this.sso = sso;
35
+ }
36
+ /**
37
+ * Redeems a ticket in this signed-in browser (web session only, so the CSRF header of the global
38
+ * guard applies): starts the ticket's OAuth connect or login-method link here, writes this
39
+ * browser's binding cookie (`cap_oauth` / `cap_sso`, the same as the normal starts) and answers
40
+ * where the browser goes next. Errors: `handoff.invalid`, `handoff.account_mismatch`, and for a
41
+ * connector the start's own (`org.not_found`, `forbidden`, `connector.*`).
42
+ */
43
+ async redeem(principal, body, req, reply) {
44
+ const p = requireUser(principal);
45
+ reply.header("cache-control", "no-store");
46
+ const out = await this.handoffs.redeem(body.ticket, p, {
47
+ oauth: req.cookies[OAUTH_BINDING_COOKIE],
48
+ sso: req.cookies[SSO_BINDING_COOKIE],
49
+ });
50
+ if (out.binding.flow === "oauth") {
51
+ setOAuthBindingCookie(reply, out.binding.value, this.config.get());
52
+ }
53
+ else {
54
+ setSsoBindingCookie(reply, out.binding.value, this.sso.cookieSecure());
55
+ }
56
+ return { location: out.location };
57
+ }
58
+ };
59
+ __decorate([
60
+ Post("redeem"),
61
+ SessionOnly(),
62
+ HttpCode(200),
63
+ __param(0, CurrentPrincipal()),
64
+ __param(1, ZBody(RedeemBody)),
65
+ __param(2, Req()),
66
+ __param(3, Res({ passthrough: true }))
67
+ ], HandoffController.prototype, "redeem", null);
68
+ HandoffController = __decorate([
69
+ Controller("api/v1/auth/handoffs"),
70
+ __param(0, Inject(HandoffService)),
71
+ __param(1, Inject(KernelConfigService)),
72
+ __param(2, Inject(SsoFlow))
73
+ ], HandoffController);
74
+ export { HandoffController };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Browser handoffs (shell external authorization spec): the redeem that starts a ticket's OAuth
3
+ * connect (`ToolsModule`'s `OAuthFlow`) or login-method link (`IdentityModule`'s `SsoFlow`) in the
4
+ * person's signed-in browser. The tickets themselves are `HandoffTicketsModule`'s.
5
+ */
6
+ export declare class HandoffModule {
7
+ }
@@ -0,0 +1,26 @@
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
+ import { Module } from "@nestjs/common";
8
+ import { IdentityModule } from "../identity/identity.module.js";
9
+ import { ToolsModule } from "../tools/tools.module.js";
10
+ import { HandoffService } from "./handoff.service.js";
11
+ import { HandoffTicketsModule } from "./handoff-tickets.js";
12
+ /**
13
+ * Browser handoffs (shell external authorization spec): the redeem that starts a ticket's OAuth
14
+ * connect (`ToolsModule`'s `OAuthFlow`) or login-method link (`IdentityModule`'s `SsoFlow`) in the
15
+ * person's signed-in browser. The tickets themselves are `HandoffTicketsModule`'s.
16
+ */
17
+ let HandoffModule = class HandoffModule {
18
+ };
19
+ HandoffModule = __decorate([
20
+ Module({
21
+ imports: [IdentityModule, ToolsModule, HandoffTicketsModule],
22
+ providers: [HandoffService],
23
+ exports: [HandoffService],
24
+ })
25
+ ], HandoffModule);
26
+ export { HandoffModule };
@@ -0,0 +1,13 @@
1
+ import { z } from "zod";
2
+ /** `POST /api/v1/auth/handoffs/redeem`: the ticket from the web page's path `/handoff/<ticket>`. */
3
+ export declare const HandoffRedeemBodySchema: z.ZodObject<{
4
+ ticket: z.ZodString;
5
+ }, z.core.$strict>;
6
+ export type HandoffRedeemBody = z.infer<typeof HandoffRedeemBodySchema>;
7
+ /**
8
+ * The redeem's answer: where this browser goes next (the authorization server's or identity
9
+ * source's authorize URL, or the handoff done page with `?error=<code>` when a link cannot start).
10
+ */
11
+ export type HandoffRedeemResponse = {
12
+ location: string;
13
+ };
@@ -0,0 +1,3 @@
1
+ import { z } from "zod";
2
+ /** `POST /api/v1/auth/handoffs/redeem`: the ticket from the web page's path `/handoff/<ticket>`. */
3
+ export const HandoffRedeemBodySchema = z.object({ ticket: z.string().max(100) }).strict();