@camstack/server 1.2.716 → 1.2.718

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/CHANGELOG.md CHANGED
@@ -7,6 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.718] - 2026-11-01
11
+
12
+ ### Changed
13
+
14
+ - Migration capability gains the owner-driven declare, start and finish calls for addon catalogues
15
+ - Allowed browser origins (CORS) are read live from the new auth.corsOrigins setting; config.yaml server.corsOrigins and CAMSTACK_CORS_ORIGINS are ignored with a boot warning
16
+ - A terminal (camstack login, the MCP setup tool) signs in by browser approval: begin and poll are public, approval needs a fresh sign-in.
17
+ - Terminal sign-in approval: audit lines, soft global cap and the requester's User-Agent and address shown to the approver
18
+
19
+ ## [1.2.717] - 2026-10-31
20
+
21
+ ### Changed
22
+
23
+ - Rebuilt against updated dependencies.
24
+
10
25
  ## [1.2.716] - 2026-10-31
11
26
 
12
27
  ### Changed
@@ -0,0 +1,145 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createCliLoginProcedures = createCliLoginProcedures;
4
+ const zod_1 = require("zod");
5
+ const auth_limits_js_1 = require("./auth-limits.js");
6
+ const trpc_middleware_js_1 = require("../trpc/trpc.middleware.js");
7
+ const user_error_js_1 = require("../trpc/user-error.js");
8
+ const auth_reauth_procedures_js_1 = require("./auth-reauth.procedures.js");
9
+ const UserCodeInput = zod_1.z.string().min(4).max(16);
10
+ const ClientLabelInput = zod_1.z.string().min(1).max(80);
11
+ const RequestViewSchema = zod_1.z.object({
12
+ requestId: zod_1.z.string(),
13
+ ip: zod_1.z.string().nullable(),
14
+ client: zod_1.z.string().nullable(),
15
+ userAgent: zod_1.z.string().nullable(),
16
+ createdAt: zod_1.z.number(),
17
+ expiresAt: zod_1.z.number(),
18
+ });
19
+ const PollOutputSchema = (loginResult) => zod_1.z.object({
20
+ status: zod_1.z.enum(['pending', 'slow_down', 'approved', 'denied', 'expired']),
21
+ intervalSec: zod_1.z.number().optional(),
22
+ session: loginResult.optional(),
23
+ });
24
+ /** What an audit line may say about a requester — never the code or the secret. */
25
+ function auditOf(requester) {
26
+ return { ip: requester.ip, client: requester.client, userAgent: requester.userAgent };
27
+ }
28
+ function refusal(message) {
29
+ return (0, user_error_js_1.trpcUserError)('NOT_FOUND', 'auth.cli-login-unknown', undefined, message);
30
+ }
31
+ function createCliLoginProcedures(deps) {
32
+ const { cliApprovals } = deps;
33
+ const limit = (path, userId) => (0, auth_limits_js_1.limitByUser)(deps.selfLimiter, path, userId);
34
+ return {
35
+ /** PUBLIC — a terminal asks to be signed in. Returns the code to show and a secret to poll with. */
36
+ cliLoginBegin: deps.beginProcedure
37
+ .input(zod_1.z.object({ client: ClientLabelInput.optional() }).optional())
38
+ .output(zod_1.z.object({
39
+ userCode: zod_1.z.string(),
40
+ deviceSecret: zod_1.z.string(),
41
+ expiresAt: zod_1.z.number(),
42
+ intervalSec: zod_1.z.number(),
43
+ }))
44
+ .mutation(({ input, ctx }) => cliApprovals.begin(deps.requesterOf(ctx.req, input?.client))),
45
+ /** PUBLIC — the terminal polls. The first poll after an approval mints the session, once. */
46
+ cliLoginPoll: deps.pollProcedure
47
+ .input(zod_1.z.object({ deviceSecret: zod_1.z.string().min(1).max(256) }))
48
+ .output(PollOutputSchema(deps.loginResultSchema))
49
+ .mutation(async ({ input }) => {
50
+ const result = cliApprovals.poll(input.deviceSecret);
51
+ if (result.status === 'unknown') {
52
+ throw (0, user_error_js_1.trpcUserError)('UNAUTHORIZED', 'auth.cli-login-invalid', undefined, 'Unknown or already used sign-in request');
53
+ }
54
+ if (result.status === 'pending' || result.status === 'slow_down') {
55
+ return { status: result.status, intervalSec: result.intervalSec };
56
+ }
57
+ if (result.status !== 'approved')
58
+ return { status: result.status };
59
+ // Refreshable on purpose: every CLI session (password login included) renews through its
60
+ // refresh token; a non-refreshable one would be a single long-lived bearer token instead.
61
+ const sessionClient = result.requester.userAgent ?? result.requester.client;
62
+ const minted = await deps.mintSession(result.userId, {
63
+ method: 'cli-approval',
64
+ refreshable: true,
65
+ ...(sessionClient !== undefined ? { client: sessionClient } : {}),
66
+ ...(result.requester.ip !== undefined ? { ip: result.requester.ip } : {}),
67
+ });
68
+ deps.logger?.info('Terminal sign-in approved and session opened', {
69
+ tags: { userId: result.userId },
70
+ meta: { requestId: result.requestId, ...auditOf(result.requester) },
71
+ });
72
+ return { status: 'approved', session: minted };
73
+ }),
74
+ /** The operator typed a code: who is asking? */
75
+ cliLoginDescribe: trpc_middleware_js_1.protectedProcedure
76
+ .input(zod_1.z.object({ userCode: UserCodeInput }))
77
+ .output(RequestViewSchema.extend({ approverIp: zod_1.z.string().nullable() }))
78
+ .query(({ ctx, input }) => {
79
+ deps.assertRealUserSession(ctx.user, 'Approving a terminal sign-in');
80
+ limit('cliLoginDescribe', ctx.user.id);
81
+ const view = cliApprovals.describe(input.userCode);
82
+ if (view === null)
83
+ throw refusal('No pending sign-in request with that code');
84
+ return { ...view, approverIp: deps.requesterOf(ctx.req, undefined).ip ?? null };
85
+ }),
86
+ cliLoginApprove: trpc_middleware_js_1.protectedProcedure
87
+ .input(zod_1.z.object({ userCode: UserCodeInput, reauthToken: auth_reauth_procedures_js_1.ReauthTokenInput.optional() }))
88
+ .output(zod_1.z.object({ ok: zod_1.z.literal(true) }))
89
+ .mutation(({ ctx, input }) => {
90
+ deps.assertRealUserSession(ctx.user, 'Approving a terminal sign-in');
91
+ limit('cliLoginApprove', ctx.user.id);
92
+ deps.assertFreshAuthentication(ctx.user, input.reauthToken);
93
+ const view = cliApprovals.describe(input.userCode);
94
+ const outcome = cliApprovals.approve(input.userCode, ctx.user.id);
95
+ const meta = {
96
+ requestId: view?.requestId,
97
+ ip: view?.ip ?? undefined,
98
+ client: view?.client ?? undefined,
99
+ userAgent: view?.userAgent ?? undefined,
100
+ approverIp: deps.requesterOf(ctx.req, undefined).ip,
101
+ };
102
+ if (outcome !== 'ok') {
103
+ deps.logger?.warn('Terminal sign-in approval refused', {
104
+ tags: { userId: ctx.user.id },
105
+ meta: { ...meta, reason: outcome },
106
+ });
107
+ throw refusal('That sign-in request is unknown, expired or already decided');
108
+ }
109
+ deps.logger?.info('Terminal sign-in approved', { tags: { userId: ctx.user.id }, meta });
110
+ return { ok: true };
111
+ }),
112
+ /** Deny by the typed code, or by the id a pending list shows. */
113
+ cliLoginDeny: trpc_middleware_js_1.protectedProcedure
114
+ .input(zod_1.z.union([
115
+ zod_1.z.object({ userCode: UserCodeInput }),
116
+ zod_1.z.object({ requestId: zod_1.z.string().min(1) }),
117
+ ]))
118
+ .output(zod_1.z.object({ ok: zod_1.z.literal(true) }))
119
+ .mutation(({ ctx, input }) => {
120
+ deps.assertRealUserSession(ctx.user, 'Denying a terminal sign-in');
121
+ limit('cliLoginDeny', ctx.user.id);
122
+ const view = 'userCode' in input
123
+ ? cliApprovals.describe(input.userCode)
124
+ : cliApprovals.describeById(input.requestId);
125
+ const outcome = cliApprovals.deny(input);
126
+ if (outcome !== 'ok')
127
+ throw refusal('That sign-in request is unknown, expired or already decided');
128
+ deps.logger?.info('Terminal sign-in denied', {
129
+ tags: { userId: ctx.user.id },
130
+ meta: {
131
+ requestId: view?.requestId,
132
+ ip: view?.ip ?? undefined,
133
+ client: view?.client ?? undefined,
134
+ userAgent: view?.userAgent ?? undefined,
135
+ },
136
+ });
137
+ return { ok: true };
138
+ }),
139
+ /** Requests waiting for a decision — no codes, so a list can only deny. */
140
+ cliLoginPending: trpc_middleware_js_1.protectedProcedure.output(zod_1.z.array(RequestViewSchema)).query(({ ctx }) => {
141
+ deps.assertRealUserSession(ctx.user, 'Listing terminal sign-ins');
142
+ return [...cliApprovals.listPending()];
143
+ }),
144
+ };
145
+ }
@@ -15,7 +15,7 @@
15
15
  * to (superseding the removed `auth.listProviders`).
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.EXCHANGE_SESSION_HEADER = exports.BROWSER_HANDOFF_PATH = void 0;
18
+ exports.EXCHANGE_SESSION_HEADER = exports.LoginResultSchema = exports.BROWSER_HANDOFF_PATH = void 0;
19
19
  exports.createAuthRouter = createAuthRouter;
20
20
  const types_1 = require("@camstack/types");
21
21
  const server_1 = require("@trpc/server");
@@ -32,6 +32,8 @@ const session_cookie_js_1 = require("../../auth/session-cookie.js");
32
32
  const hub_sessions_js_1 = require("../../auth/hub-sessions.js");
33
33
  const session_mint_js_1 = require("../../auth/session-mint.js");
34
34
  const handoff_code_service_js_1 = require("../../core/auth/handoff-code.service.js");
35
+ const cli_approval_service_js_1 = require("../../core/auth/cli-approval.service.js");
36
+ const auth_cli_login_procedures_js_1 = require("./auth-cli-login.procedures.js");
35
37
  const trpc_middleware_js_1 = require("../trpc/trpc.middleware.js");
36
38
  const auth_limits_js_1 = require("./auth-limits.js");
37
39
  const auth_audit_procedures_js_1 = require("./auth-audit.procedures.js");
@@ -106,7 +108,7 @@ exports.BROWSER_HANDOFF_PATH = '/api/auth/browser-handoff';
106
108
  * `requiresTotp` is retained (`= secondFactors.includes('totp')`) for
107
109
  * backward compatibility with older SDK builds that branch on it.
108
110
  */
109
- const LoginResultSchema = zod_1.z.object({
111
+ exports.LoginResultSchema = zod_1.z.object({
110
112
  token: zod_1.z.string(),
111
113
  user: zod_1.z.object({
112
114
  id: zod_1.z.string(),
@@ -266,6 +268,7 @@ function createAuthRouter(auth, registry, moleculer = null, handoffCodes = new h
266
268
  /** Challenge-minting begin-legs — looser, they verify nothing. */
267
269
  const ceremonyProcedure = makeRateLimitedProcedure(limiters.ceremony, network);
268
270
  const credentialTokens = options.credentialTokens ?? null;
271
+ const cliApprovals = new cli_approval_service_js_1.CliApprovalService();
269
272
  /**
270
273
  * THE session mint (`auth/session-mint.ts`, D712) — the single shared tail
271
274
  * of every successful login leg, including `/api/auth/sso/finish`. It
@@ -520,7 +523,7 @@ function createAuthRouter(auth, registry, moleculer = null, handoffCodes = new h
520
523
  return (0, trpc_middleware_js_1.trpcRouter)({
521
524
  login: credentialProcedure
522
525
  .input(zod_1.z.object({ username: zod_1.z.string(), password: zod_1.z.string(), refreshable: RefreshableInput }))
523
- .output(LoginResultSchema)
526
+ .output(exports.LoginResultSchema)
524
527
  .mutation(async ({ input, ctx }) => {
525
528
  const userMgmt = registry?.getSingleton('user-management');
526
529
  if (!userMgmt) {
@@ -586,7 +589,7 @@ function createAuthRouter(auth, registry, moleculer = null, handoffCodes = new h
586
589
  */
587
590
  loginVerifyTotp: credentialProcedure
588
591
  .input(zod_1.z.object({ challengeToken: zod_1.z.string(), code: zod_1.z.string(), refreshable: RefreshableInput }))
589
- .output(LoginResultSchema)
592
+ .output(exports.LoginResultSchema)
590
593
  .mutation(async ({ input, ctx }) => {
591
594
  const claims = auth.verifyTotpChallengeToken(input.challengeToken);
592
595
  if (!claims) {
@@ -639,7 +642,7 @@ function createAuthRouter(auth, registry, moleculer = null, handoffCodes = new h
639
642
  response: zod_1.z.record(zod_1.z.string(), zod_1.z.unknown()),
640
643
  refreshable: RefreshableInput,
641
644
  }))
642
- .output(LoginResultSchema)
645
+ .output(exports.LoginResultSchema)
643
646
  .mutation(async ({ input, ctx }) => {
644
647
  const claims = auth.verifyTotpChallengeToken(input.challengeToken);
645
648
  if (!claims) {
@@ -696,7 +699,7 @@ function createAuthRouter(auth, registry, moleculer = null, handoffCodes = new h
696
699
  */
697
700
  passkeyLoginFinish: credentialProcedure
698
701
  .input(zod_1.z.object({ response: zod_1.z.record(zod_1.z.string(), zod_1.z.unknown()), refreshable: RefreshableInput }))
699
- .output(LoginResultSchema)
702
+ .output(exports.LoginResultSchema)
700
703
  .mutation(async ({ input, ctx }) => {
701
704
  const provider = (0, passkey_provider_js_1.resolvePasskeyProvider)(registry, moleculer);
702
705
  if (!provider)
@@ -751,7 +754,7 @@ function createAuthRouter(auth, registry, moleculer = null, handoffCodes = new h
751
754
  */
752
755
  exchangeSession: credentialProcedure
753
756
  .input(zod_1.z.object({ refreshable: RefreshableInput }).optional())
754
- .output(LoginResultSchema)
757
+ .output(exports.LoginResultSchema)
755
758
  .mutation(async ({ ctx, input }) => {
756
759
  if (readRequestHeader(ctx.req, exports.EXCHANGE_SESSION_HEADER) !== '1') {
757
760
  throw new server_1.TRPCError({
@@ -850,7 +853,7 @@ function createAuthRouter(auth, registry, moleculer = null, handoffCodes = new h
850
853
  codeVerifier: zod_1.z.string().min(1).max(256).optional(),
851
854
  state: zod_1.z.string().min(1).max(256).optional(),
852
855
  }))
853
- .output(LoginResultSchema)
856
+ .output(exports.LoginResultSchema)
854
857
  .mutation(async ({ input, ctx }) => {
855
858
  const redeemed = handoffCodes.redeemWithReason(input.code, {
856
859
  ...(input.codeVerifier !== undefined ? { codeVerifier: input.codeVerifier } : {}),
@@ -1137,6 +1140,26 @@ function createAuthRouter(auth, registry, moleculer = null, handoffCodes = new h
1137
1140
  });
1138
1141
  }),
1139
1142
  ...(0, auth_sessions_procedures_js_1.createSessionProcedures)({ registry, minter, credentialProcedure }),
1143
+ ...(0, auth_cli_login_procedures_js_1.createCliLoginProcedures)({
1144
+ cliApprovals: options.cliApprovals ?? cliApprovals,
1145
+ beginProcedure: credentialProcedure,
1146
+ pollProcedure: ceremonyProcedure,
1147
+ selfLimiter: SELF_CODE_LIMITER,
1148
+ ...(options.logger !== undefined ? { logger: options.logger } : {}),
1149
+ requesterOf: (req, label) => {
1150
+ const ip = network.clientAddress(req).ip;
1151
+ const userAgent = clientLabel(req);
1152
+ return {
1153
+ ...(ip !== null ? { ip } : {}),
1154
+ ...(label !== undefined ? { client: label } : {}),
1155
+ ...(userAgent !== undefined ? { userAgent } : {}),
1156
+ };
1157
+ },
1158
+ mintSession: mintSessionOrUnauthorized,
1159
+ assertFreshAuthentication,
1160
+ assertRealUserSession,
1161
+ loginResultSchema: exports.LoginResultSchema,
1162
+ }),
1140
1163
  ...(0, auth_device_cert_procedures_js_1.createDeviceCertProcedures)({
1141
1164
  registry,
1142
1165
  minter,
@@ -1,4 +1,11 @@
1
1
  "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CORS_PREFLIGHT_MAX_AGE_SEC = exports.CORS_EXPOSED_HEADERS = exports.CORS_ALLOWED_HEADERS = exports.CORS_ALLOWED_METHODS = exports.VIEWER_PWA_ORIGIN = exports.OPAQUE_ORIGIN = exports.normalizeOrigin = void 0;
4
+ exports.parseConfiguredOrigins = parseConfiguredOrigins;
5
+ exports.builtInOrigins = builtInOrigins;
6
+ exports.judgeCorsOrigin = judgeCorsOrigin;
7
+ exports.corsResponseHeaders = corsResponseHeaders;
8
+ exports.appendVary = appendVary;
2
9
  /**
3
10
  * cors-policy — which browser origins may READ this hub's responses (D707).
4
11
  *
@@ -18,9 +25,10 @@
18
25
  * - {@link OPAQUE_ORIGIN} (`null`): the native app's OTA-bundled embed is a
19
26
  * `file://` page inside a WKWebView, whose origin is opaque. Removing it
20
27
  * breaks live view on iOS;
21
- * - the operator's extras (`server.corsOrigins` in config.yaml /
22
- * `CAMSTACK_CORS_ORIGINS`). The hub's own public address needs no entry:
23
- * a browser on it is the `own-host` case above.
28
+ * - the operator's extras (`auth.corsOrigins`, System → Authentication,
29
+ * read live from the settings store). The built-ins above are a floor that
30
+ * holds before the store is open. The hub's own public address needs no
31
+ * entry: a browser on it is the `own-host` case above.
24
32
  *
25
33
  * The answer to an allowed origin REFLECTS it exactly — never `*` — and never
26
34
  * carries `Access-Control-Allow-Credentials`. The cross-origin viewer
@@ -32,21 +40,11 @@
32
40
  *
33
41
  * Pure: no Fastify, no I/O — `register-cors-policy.ts` is the glue.
34
42
  */
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.CORS_PREFLIGHT_MAX_AGE_SEC = exports.CORS_EXPOSED_HEADERS = exports.CORS_ALLOWED_HEADERS = exports.CORS_ALLOWED_METHODS = exports.OPAQUE_ORIGIN = exports.VIEWER_PWA_ORIGIN = void 0;
37
- exports.normalizeOrigin = normalizeOrigin;
38
- exports.parseConfiguredOrigins = parseConfiguredOrigins;
39
- exports.builtInOrigins = builtInOrigins;
40
- exports.judgeCorsOrigin = judgeCorsOrigin;
41
- exports.corsResponseHeaders = corsResponseHeaders;
42
- exports.appendVary = appendVary;
43
+ const system_1 = require("@camstack/system");
44
+ Object.defineProperty(exports, "normalizeOrigin", { enumerable: true, get: function () { return system_1.normalizeOrigin; } });
45
+ Object.defineProperty(exports, "OPAQUE_ORIGIN", { enumerable: true, get: function () { return system_1.OPAQUE_ORIGIN; } });
43
46
  /** The hosted viewer PWA (operator decision 2026-10-06). */
44
47
  exports.VIEWER_PWA_ORIGIN = 'https://camstack.zentik.app';
45
- /**
46
- * The serialisation of an opaque origin. The native app's OTA embed
47
- * (`assets/embed/camstack-embed.html`, loaded from `file://`) sends it.
48
- */
49
- exports.OPAQUE_ORIGIN = 'null';
50
48
  /** Every method a hub route answers. */
51
49
  exports.CORS_ALLOWED_METHODS = 'GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS';
52
50
  /**
@@ -66,45 +64,17 @@ exports.CORS_ALLOWED_HEADERS = 'authorization, content-type, range, if-range, if
66
64
  exports.CORS_EXPOSED_HEADERS = 'content-range, accept-ranges, content-length, content-disposition, etag, retry-after, x-camstack-reason, x-camstack-reason-code, x-camstack-disposition';
67
65
  /** Preflight cache. Chromium caps at 7200 s; Firefox honours up to 86400. */
68
66
  exports.CORS_PREFLIGHT_MAX_AGE_SEC = 7200;
69
- /**
70
- * The canonical serialisation of an origin (`scheme://host[:port]`, lower
71
- * case, default port dropped), or `null` when `raw` is not an http(s) origin.
72
- * `null` (the opaque origin) is accepted verbatim.
73
- */
74
- function normalizeOrigin(raw) {
75
- const trimmed = raw.trim();
76
- if (trimmed === exports.OPAQUE_ORIGIN)
77
- return exports.OPAQUE_ORIGIN;
78
- let url;
79
- try {
80
- url = new URL(trimmed);
81
- }
82
- catch {
83
- return null;
84
- }
85
- if (url.protocol !== 'https:' && url.protocol !== 'http:')
86
- return null;
87
- // An origin has no path, query, fragment or credentials. Accept a bare
88
- // trailing slash (a common paste), refuse anything that names more.
89
- if (url.username !== '' || url.password !== '')
90
- return null;
91
- if ((url.pathname !== '/' && url.pathname !== '') || url.search !== '' || url.hash !== '') {
92
- return null;
93
- }
94
- return url.origin;
95
- }
96
- /** Read the configured value (array from YAML, already split from env). */
67
+ /** Read the stored `auth.corsOrigins` value (a list, or one comma/space separated string). */
97
68
  function parseConfiguredOrigins(value) {
98
- if (!Array.isArray(value))
99
- return { origins: [], rejected: [] };
69
+ const entries = Array.isArray(value) ? value : (0, system_1.readOriginSetting)(value);
100
70
  const origins = [];
101
71
  const rejected = [];
102
- for (const entry of value) {
72
+ for (const entry of entries) {
103
73
  if (typeof entry !== 'string') {
104
74
  rejected.push(String(entry));
105
75
  continue;
106
76
  }
107
- const normalized = normalizeOrigin(entry);
77
+ const normalized = (0, system_1.normalizeOrigin)(entry);
108
78
  if (normalized === null)
109
79
  rejected.push(entry);
110
80
  else
@@ -114,7 +84,7 @@ function parseConfiguredOrigins(value) {
114
84
  }
115
85
  /** The built-in entries. */
116
86
  function builtInOrigins() {
117
- return [exports.VIEWER_PWA_ORIGIN, exports.OPAQUE_ORIGIN];
87
+ return [exports.VIEWER_PWA_ORIGIN, system_1.OPAQUE_ORIGIN];
118
88
  }
119
89
  /** The first value of a possibly comma-joined forwarding header, lower case. */
120
90
  function firstHost(value) {
@@ -125,7 +95,7 @@ function firstHost(value) {
125
95
  }
126
96
  /** `host[:port]` of an http(s) origin, or null. */
127
97
  function hostOfOrigin(origin) {
128
- if (origin === exports.OPAQUE_ORIGIN)
98
+ if (origin === system_1.OPAQUE_ORIGIN)
129
99
  return null;
130
100
  try {
131
101
  return new URL(origin).host.toLowerCase();
@@ -142,7 +112,7 @@ function judgeCorsOrigin(facts, listed) {
142
112
  const raw = facts.origin;
143
113
  if (raw === undefined || raw.length === 0)
144
114
  return { kind: 'no-origin' };
145
- const normalized = normalizeOrigin(raw);
115
+ const normalized = (0, system_1.normalizeOrigin)(raw);
146
116
  if (normalized === null)
147
117
  return { kind: 'denied', origin: raw };
148
118
  if (listed.has(normalized))
@@ -24,14 +24,20 @@ function createCorsPolicy(deps) {
24
24
  let listed = new Set(builtIns);
25
25
  const loggedDenials = new Set();
26
26
  const currentList = () => {
27
- const configured = deps.configuredOrigins();
27
+ let configured;
28
+ try {
29
+ configured = deps.configuredOrigins();
30
+ }
31
+ catch {
32
+ configured = undefined;
33
+ }
28
34
  if (configured === lastConfigured)
29
35
  return listed;
30
36
  lastConfigured = configured;
31
37
  const parsed = (0, cors_policy_js_1.parseConfiguredOrigins)(configured);
32
38
  if (parsed.rejected.length > 0) {
33
39
  deps.logger.warn('cors: ignored configured origins that are not http(s) origins', {
34
- meta: { rejected: parsed.rejected, setting: 'server.corsOrigins' },
40
+ meta: { rejected: parsed.rejected, setting: 'auth.corsOrigins' },
35
41
  });
36
42
  }
37
43
  listed = new Set([...builtIns, ...parsed.origins]);
@@ -51,7 +57,7 @@ function createCorsPolicy(deps) {
51
57
  meta: {
52
58
  origin: verdict.origin,
53
59
  host: headerValue(headers.host) ?? null,
54
- hint: 'add it to server.corsOrigins (config.yaml) or CAMSTACK_CORS_ORIGINS',
60
+ hint: 'add it under System → Authentication → Allowed browser origins',
55
61
  },
56
62
  });
57
63
  }
@@ -6630,6 +6630,33 @@ function createCapRouter_migrations(getProvider, createRemoteProxy) {
6630
6630
  // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
6631
6631
  return p.restorePreMigration(methodInput);
6632
6632
  }),
6633
+ declareOwner: trpc_middleware_js_1.adminProcedure
6634
+ .input(types_84.migrationsCapability.methods.declareOwner.input.loose())
6635
+ .output(types_84.migrationsCapability.methods.declareOwner.output)
6636
+ .mutation(async ({ input, ctx }) => {
6637
+ const { nodeId, ...methodInput } = input;
6638
+ const p = resolveProvider('migrations', nodeId, () => getProvider(ctx), createRemoteProxy);
6639
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
6640
+ return p.declareOwner(methodInput);
6641
+ }),
6642
+ startMigration: trpc_middleware_js_1.adminProcedure
6643
+ .input(types_84.migrationsCapability.methods.startMigration.input.loose())
6644
+ .output(types_84.migrationsCapability.methods.startMigration.output)
6645
+ .mutation(async ({ input, ctx }) => {
6646
+ const { nodeId, ...methodInput } = input;
6647
+ const p = resolveProvider('migrations', nodeId, () => getProvider(ctx), createRemoteProxy);
6648
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
6649
+ return p.startMigration(methodInput);
6650
+ }),
6651
+ finishMigration: trpc_middleware_js_1.adminProcedure
6652
+ .input(types_84.migrationsCapability.methods.finishMigration.input.loose())
6653
+ .output(types_84.migrationsCapability.methods.finishMigration.output)
6654
+ .mutation(async ({ input, ctx }) => {
6655
+ const { nodeId, ...methodInput } = input;
6656
+ const p = resolveProvider('migrations', nodeId, () => getProvider(ctx), createRemoteProxy);
6657
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
6658
+ return p.finishMigration(methodInput);
6659
+ }),
6633
6660
  });
6634
6661
  }
6635
6662
  function createCapRouter_modelConvert(getProvider, createRemoteProxy) {
@@ -38,6 +38,7 @@ var __importStar = (this && this.__importStar) || (function () {
38
38
  };
39
39
  })();
40
40
  Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.retiredCorsSources = retiredCorsSources;
41
42
  exports.ignoredTlsCertSources = ignoredTlsCertSources;
42
43
  exports.retiredSecretSources = retiredSecretSources;
43
44
  exports.loadBootstrapConfig = loadBootstrapConfig;
@@ -84,6 +85,23 @@ const RETIRED_SECRET_ENV = [
84
85
  ];
85
86
  /** `config.yaml` `auth.*` keys that once held a credential — ignored too (D797). */
86
87
  const RETIRED_AUTH_KEYS = ['jwtSecret', 'adminUsername', 'adminPassword'];
88
+ /**
89
+ * The extra browser origins moved to the `auth.corsOrigins` setting (D707):
90
+ * edited in System → Authentication, read live. These two former sources are
91
+ * ignored, and named at boot so a stale value is told, never silently
92
+ * honoured.
93
+ */
94
+ const RETIRED_CORS_ENV = 'CAMSTACK_CORS_ORIGINS';
95
+ const RETIRED_CORS_YAML_KEY = 'server.corsOrigins';
96
+ /** The retired CORS sources still present (names only, never the values). */
97
+ function retiredCorsSources(env, raw) {
98
+ const fromEnv = (env[RETIRED_CORS_ENV] ?? '') !== '' ? [RETIRED_CORS_ENV] : [];
99
+ const server = (0, types_1.asJsonObject)(raw['server']) ?? {};
100
+ const fromYaml = server['corsOrigins'] !== undefined && server['corsOrigins'] !== null
101
+ ? [RETIRED_CORS_YAML_KEY]
102
+ : [];
103
+ return [...fromEnv, ...fromYaml];
104
+ }
87
105
  /**
88
106
  * Env variables that once set the node's certificate. Ignored since D726:
89
107
  * the admin UI (Network → Local access) is the one way to set it. Still
@@ -201,6 +219,12 @@ function loadBootstrapConfig(configPath) {
201
219
  'keychain; a fresh hub seeds admin / changeme. ' +
202
220
  'Remove these entries — after importing their values with scripts/ops/keychain-migrate-hub.mjs.');
203
221
  }
222
+ const retiredCors = retiredCorsSources(process.env, raw);
223
+ if (retiredCors.length > 0) {
224
+ console.warn(`[Phase1] WARN ${retiredCors.join(', ')} ignored — the allowed browser origins are set ` +
225
+ 'only in the admin UI (System → Authentication → Allowed browser origins, D707). ' +
226
+ 'Re-enter them there and remove the entry.');
227
+ }
204
228
  const ignored = ignoredTlsCertSources(process.env, raw);
205
229
  if (ignored.length > 0) {
206
230
  console.warn(`[Phase1] WARN ${ignored.join(', ')} ignored — the certificate is set only in the admin UI. ` +
@@ -0,0 +1,282 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.CliApprovalService = exports.CLI_APPROVAL_MAX_PENDING_PER_IP = exports.CLI_APPROVAL_MAX_PENDING = exports.CLI_APPROVAL_SLOW_DOWN_SEC = exports.CLI_APPROVAL_INTERVAL_SEC = exports.CLI_APPROVAL_TTL_MS = exports.CLI_APPROVAL_SECRET_PREFIX = void 0;
37
+ exports.normalizeUserCode = normalizeUserCode;
38
+ const types_1 = require("@camstack/types");
39
+ /**
40
+ * CliApprovalService — the browser-approval login of a terminal client
41
+ * (`camstack login`, the MCP `setup_login`), in the shape of RFC 8628.
42
+ *
43
+ * Flow: the CLI calls `begin` (public, rate limited) and gets a short user
44
+ * code to show the operator and a long device secret it keeps. The operator
45
+ * opens `/approve` in an already signed-in admin UI, types the code, sees who
46
+ * asked (ip, client) and approves or denies. The CLI polls with its secret;
47
+ * the first poll after an approval hands the approving user id to the router,
48
+ * which mints a normal session through the single session mint.
49
+ *
50
+ * Design mirrors {@link HandoffCodeService}:
51
+ * - the device secret and the user code are kept ONLY as SHA-256 hashes;
52
+ * - TTL 5 min, single use (an approved entry is consumed by the poll that
53
+ * collects it, an expired or denied one by the poll that reports it);
54
+ * - in-memory and bounded (global and per requesting ip).
55
+ */
56
+ const crypto = __importStar(require("node:crypto"));
57
+ /** Wire prefix of the device secret (`cda_` = CamStack Device Approval; redeemable once for a session). */
58
+ exports.CLI_APPROVAL_SECRET_PREFIX = 'cda_';
59
+ exports.CLI_APPROVAL_TTL_MS = 5 * 60_000;
60
+ exports.CLI_APPROVAL_INTERVAL_SEC = 3;
61
+ /** Added to the poll interval each time a client polls faster than allowed. */
62
+ exports.CLI_APPROVAL_SLOW_DOWN_SEC = 2;
63
+ exports.CLI_APPROVAL_MAX_PENDING = 200;
64
+ exports.CLI_APPROVAL_MAX_PENDING_PER_IP = 5;
65
+ /** Requests with no known address share one bucket, so "unknown" is never uncapped. */
66
+ const UNKNOWN_IP_BUCKET = '(unknown)';
67
+ /** Crockford base32: no I, L, O, U. */
68
+ const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
69
+ const USER_CODE_LENGTH = 8;
70
+ function sha256(value) {
71
+ return crypto.createHash('sha256').update(value).digest('hex');
72
+ }
73
+ /** Uppercase, drop separators and spaces, fold Crockford's look-alikes (I/L→1, O→0). */
74
+ function normalizeUserCode(raw) {
75
+ return raw
76
+ .toUpperCase()
77
+ .replace(/[^0-9A-Z]/g, '')
78
+ .replace(/[IL]/g, '1')
79
+ .replace(/O/g, '0');
80
+ }
81
+ function formatUserCode(code) {
82
+ return `${code.slice(0, 4)}-${code.slice(4)}`;
83
+ }
84
+ function randomUserCode() {
85
+ let out = '';
86
+ for (let i = 0; i < USER_CODE_LENGTH; i += 1)
87
+ out += CROCKFORD[crypto.randomInt(CROCKFORD.length)];
88
+ return out;
89
+ }
90
+ class CliApprovalService {
91
+ now;
92
+ ttlMs;
93
+ /** Keyed by SHA-256(device secret). */
94
+ bySecret = new Map();
95
+ /** SHA-256(normalized user code) → SHA-256(device secret). */
96
+ byCode = new Map();
97
+ constructor(now = Date.now, ttlMs = exports.CLI_APPROVAL_TTL_MS) {
98
+ this.now = now;
99
+ this.ttlMs = ttlMs;
100
+ }
101
+ begin(requester = {}) {
102
+ this.prune();
103
+ const ip = requester.ip ?? null;
104
+ const bucket = ip ?? UNKNOWN_IP_BUCKET;
105
+ if (this.countFor(bucket) >= exports.CLI_APPROVAL_MAX_PENDING_PER_IP) {
106
+ throw (0, types_1.userError)('server.cli-approval-busy', undefined, 'Too many pending sign-in requests from this address');
107
+ }
108
+ // The global bound is soft: a full table drops the oldest request of the
109
+ // busiest address, so a flood from many addresses cannot lock everyone out.
110
+ while (this.bySecret.size >= exports.CLI_APPROVAL_MAX_PENDING)
111
+ this.evictOne();
112
+ let code = randomUserCode();
113
+ while (this.byCode.has(sha256(code)))
114
+ code = randomUserCode();
115
+ const deviceSecret = `${exports.CLI_APPROVAL_SECRET_PREFIX}${crypto.randomBytes(32).toString('hex')}`;
116
+ const createdAt = this.now();
117
+ const expiresAt = createdAt + this.ttlMs;
118
+ const secretHash = sha256(deviceSecret);
119
+ const userCodeHash = sha256(code);
120
+ this.bySecret.set(secretHash, {
121
+ requestId: crypto.randomBytes(8).toString('hex'),
122
+ userCodeHash,
123
+ ip,
124
+ client: requester.client ?? null,
125
+ userAgent: requester.userAgent ?? null,
126
+ createdAt,
127
+ expiresAt,
128
+ state: { kind: 'pending' },
129
+ intervalSec: exports.CLI_APPROVAL_INTERVAL_SEC,
130
+ lastPollAt: null,
131
+ });
132
+ this.byCode.set(userCodeHash, secretHash);
133
+ return {
134
+ userCode: formatUserCode(code),
135
+ deviceSecret,
136
+ expiresAt,
137
+ intervalSec: exports.CLI_APPROVAL_INTERVAL_SEC,
138
+ };
139
+ }
140
+ /** The request behind a typed user code, or null (unknown or expired). */
141
+ describe(userCode) {
142
+ const entry = this.entryOfCode(userCode);
143
+ if (entry === null || entry.state.kind !== 'pending')
144
+ return null;
145
+ return this.viewOf(entry);
146
+ }
147
+ /** Requests still waiting for a decision (no code: it is never enough to approve from a list). */
148
+ listPending() {
149
+ this.prune();
150
+ const out = [];
151
+ for (const entry of this.bySecret.values()) {
152
+ if (entry.state.kind === 'pending')
153
+ out.push(this.viewOf(entry));
154
+ }
155
+ return out.sort((a, b) => b.createdAt - a.createdAt);
156
+ }
157
+ /** The pending request behind an id a list showed, or null. */
158
+ describeById(requestId) {
159
+ const entry = [...this.bySecret.values()].find((e) => e.requestId === requestId);
160
+ return entry === undefined || entry.state.kind !== 'pending' || this.now() > entry.expiresAt
161
+ ? null
162
+ : this.viewOf(entry);
163
+ }
164
+ approve(userCode, userId) {
165
+ return this.decide(this.entryOfCode(userCode), { kind: 'approved', userId });
166
+ }
167
+ deny(ref) {
168
+ const entry = 'userCode' in ref
169
+ ? this.entryOfCode(ref.userCode)
170
+ : ([...this.bySecret.values()].find((e) => e.requestId === ref.requestId) ?? null);
171
+ return this.decide(entry, { kind: 'denied' });
172
+ }
173
+ /** The device's poll. A terminal answer (approved, denied, expired) consumes the entry. */
174
+ poll(deviceSecret) {
175
+ const key = sha256(deviceSecret);
176
+ const entry = this.bySecret.get(key);
177
+ if (!entry)
178
+ return { status: 'unknown' };
179
+ const now = this.now();
180
+ if (now > entry.expiresAt) {
181
+ this.remove(key, entry);
182
+ return { status: 'expired' };
183
+ }
184
+ if (entry.state.kind === 'approved') {
185
+ this.remove(key, entry);
186
+ return {
187
+ status: 'approved',
188
+ userId: entry.state.userId,
189
+ requestId: entry.requestId,
190
+ requester: {
191
+ ...(entry.ip !== null ? { ip: entry.ip } : {}),
192
+ ...(entry.client !== null ? { client: entry.client } : {}),
193
+ ...(entry.userAgent !== null ? { userAgent: entry.userAgent } : {}),
194
+ },
195
+ };
196
+ }
197
+ if (entry.state.kind === 'denied') {
198
+ this.remove(key, entry);
199
+ return { status: 'denied' };
200
+ }
201
+ const tooSoon = entry.lastPollAt !== null && now - entry.lastPollAt < entry.intervalSec * 1000;
202
+ entry.lastPollAt = now;
203
+ if (tooSoon) {
204
+ entry.intervalSec += exports.CLI_APPROVAL_SLOW_DOWN_SEC;
205
+ return { status: 'slow_down', intervalSec: entry.intervalSec };
206
+ }
207
+ return { status: 'pending', intervalSec: entry.intervalSec };
208
+ }
209
+ get pendingCount() {
210
+ return this.bySecret.size;
211
+ }
212
+ decide(entry, next) {
213
+ if (entry === null)
214
+ return 'unknown';
215
+ if (this.now() > entry.expiresAt)
216
+ return 'expired';
217
+ if (entry.state.kind !== 'pending')
218
+ return 'already-decided';
219
+ entry.state = next;
220
+ return 'ok';
221
+ }
222
+ entryOfCode(userCode) {
223
+ const secretHash = this.byCode.get(sha256(normalizeUserCode(userCode)));
224
+ if (secretHash === undefined)
225
+ return null;
226
+ const entry = this.bySecret.get(secretHash);
227
+ if (!entry || this.now() > entry.expiresAt)
228
+ return null;
229
+ return entry;
230
+ }
231
+ viewOf(entry) {
232
+ return {
233
+ requestId: entry.requestId,
234
+ ip: entry.ip,
235
+ client: entry.client,
236
+ userAgent: entry.userAgent,
237
+ createdAt: entry.createdAt,
238
+ expiresAt: entry.expiresAt,
239
+ };
240
+ }
241
+ countFor(bucket) {
242
+ let n = 0;
243
+ for (const entry of this.bySecret.values())
244
+ if ((entry.ip ?? UNKNOWN_IP_BUCKET) === bucket)
245
+ n += 1;
246
+ return n;
247
+ }
248
+ /** Drop the oldest entry of the address holding the most entries. */
249
+ evictOne() {
250
+ const counts = new Map();
251
+ for (const entry of this.bySecret.values()) {
252
+ const bucket = entry.ip ?? UNKNOWN_IP_BUCKET;
253
+ counts.set(bucket, (counts.get(bucket) ?? 0) + 1);
254
+ }
255
+ let busiest = UNKNOWN_IP_BUCKET;
256
+ let most = -1;
257
+ for (const [bucket, n] of counts) {
258
+ if (n > most) {
259
+ busiest = bucket;
260
+ most = n;
261
+ }
262
+ }
263
+ for (const [key, entry] of this.bySecret) {
264
+ if ((entry.ip ?? UNKNOWN_IP_BUCKET) === busiest) {
265
+ this.remove(key, entry);
266
+ return;
267
+ }
268
+ }
269
+ }
270
+ remove(key, entry) {
271
+ this.bySecret.delete(key);
272
+ this.byCode.delete(entry.userCodeHash);
273
+ }
274
+ prune() {
275
+ const now = this.now();
276
+ for (const [key, entry] of this.bySecret) {
277
+ if (now > entry.expiresAt)
278
+ this.remove(key, entry);
279
+ }
280
+ }
281
+ }
282
+ exports.CliApprovalService = CliApprovalService;
package/dist/main.js CHANGED
@@ -390,14 +390,14 @@ async function bootstrap() {
390
390
  const fastify = app.getHttpAdapter().getInstance();
391
391
  // Which browser origins may read hub responses, and open the /trpc socket
392
392
  // (D707): the hub's own, the hosted viewer PWA, the native embed's opaque
393
- // `null`, and the operator's `server.corsOrigins`. First hook on the
393
+ // `null`, and the operator's `auth.corsOrigins` setting (read live). First hook on the
394
394
  // instance so every route — and every OPTIONS — is judged.
395
395
  if (publicUrlWarning !== undefined) {
396
396
  app.get(logging_service_1.LoggingService).createLogger('public-url').warn(publicUrlWarning);
397
397
  }
398
398
  const corsConfig = app.get(config_service_1.ConfigService);
399
399
  const corsPolicy = (0, register_cors_policy_1.createCorsPolicy)({
400
- configuredOrigins: () => corsConfig.get('server.corsOrigins'),
400
+ configuredOrigins: () => corsConfig.get('auth.corsOrigins'),
401
401
  logger: app.get(logging_service_1.LoggingService).createLogger('cors'),
402
402
  });
403
403
  (0, register_cors_policy_1.registerCorsPolicy)(fastify, corsPolicy);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/server",
3
- "version": "1.2.716",
3
+ "version": "1.2.718",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -50,19 +50,19 @@
50
50
  ]
51
51
  },
52
52
  "dependencies": {
53
- "@camstack/addon-admin-ui": "1.2.539",
53
+ "@camstack/addon-admin-ui": "1.2.541",
54
54
  "@camstack/addon-agent-ui": "1.2.306",
55
55
  "@camstack/addon-auth": "1.2.174",
56
56
  "@camstack/addon-benchmark": "1.2.304",
57
57
  "@camstack/addon-decoder-nodeav": "1.2.144",
58
58
  "@camstack/addon-notifiers": "1.2.625",
59
59
  "@camstack/addon-pipeline": "1.2.636",
60
- "@camstack/addon-pipeline-orchestrator": "1.2.646",
60
+ "@camstack/addon-pipeline-orchestrator": "1.2.647",
61
61
  "@camstack/addon-post-analysis": "1.2.656",
62
- "@camstack/develop": "0.1.41",
62
+ "@camstack/develop": "0.1.42",
63
63
  "@camstack/sdk": "1.2.154",
64
- "@camstack/system": "1.2.535",
65
- "@camstack/types": "1.2.460",
64
+ "@camstack/system": "1.2.537",
65
+ "@camstack/types": "1.2.462",
66
66
  "@camstack/ui-library": "1.2.364",
67
67
  "@fastify/compress": "^9.0.0",
68
68
  "@fastify/cookie": "^11.0.2",