nucleus-core-ts 0.10.258 → 0.10.260
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/.build-ok +1 -1
- package/dist/fe/components/Replay/_components/ReplayChapters/index.js +12 -0
- package/dist/fe/components/Replay/_components/ReplayPlayer/ReplayView.js +2 -0
- package/dist/fe/components/Replay/_components/ReplayStage/index.js +3 -2
- package/dist/fe/components/Replay/_components/ReplayStage/types.d.ts +3 -0
- package/dist/fe/components/Replay/_hooks/useCameraPan.js +8 -5
- package/dist/fe/components/Replay/_hooks/useStageScale.js +11 -4
- package/dist/fe/components/Replay/_store/replayStore.js +8 -0
- package/dist/fe/components/Replay/_types/player.d.ts +9 -0
- package/dist/fe/components/Replay/_utils/chapterRow.d.ts +8 -0
- package/dist/fe/components/Replay/_utils/chapterRow.js +17 -0
- package/dist/fe/components/Replay/_utils/controller.js +13 -4
- package/dist/fe/components/Replay/_utils/controllerReports.d.ts +2 -1
- package/dist/fe/components/Replay/_utils/controllerReports.js +8 -1
- package/dist/fe/components/Replay/_utils/frameBridge.js +25 -8
- package/dist/fe/components/Replay/_utils/framePrelude.d.ts +3 -1
- package/dist/fe/components/Replay/_utils/framePrelude.js +2 -1
- package/dist/fe/components/Replay/_utils/replayProgress.d.ts +2 -0
- package/dist/fe/components/Replay/_utils/replayProgress.js +4 -0
- package/dist/fe/components/Replay/_utils/stageViewport.d.ts +5 -2
- package/dist/fe/components/Replay/_utils/stageViewport.js +6 -3
- package/dist/index.js +1 -1
- package/dist/server.js +1 -1
- package/dist/src/Client/Replay/channel/channel.d.ts +9 -0
- package/dist/src/Client/Replay/channel/channel.js +15 -2
- package/package.json +1 -1
package/dist/.build-ok
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
0.10.
|
|
1
|
+
0.10.260
|
|
@@ -1,9 +1,20 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useEffect, useEffectEvent, useRef } from 'react';
|
|
4
|
+
import { revealInRow } from '../../_utils/chapterRow';
|
|
3
5
|
import { REPLAY_COPY } from '../../_utils/copy';
|
|
4
6
|
import { pickLocalized } from '../../_utils/frameUrl';
|
|
5
7
|
import { chapterMinutes, chapterProgress } from '../../_utils/replayProgress';
|
|
6
8
|
/** The chapters as a list: each one seeks to its start; the current one is marked and shows how far the playhead is in it. */ export function ReplayChapters({ chapters, locale, chapterId, playhead, onSeek }) {
|
|
9
|
+
const row = useRef(null);
|
|
10
|
+
// The row scrolls sideways: the current chapter is brought into it, and only it (never the page).
|
|
11
|
+
const reveal = useEffectEvent(()=>{
|
|
12
|
+
const item = row.current?.querySelector('[aria-current="step"]');
|
|
13
|
+
if (row.current && item) revealInRow(row.current, item);
|
|
14
|
+
});
|
|
15
|
+
useEffect(()=>reveal(), [
|
|
16
|
+
chapterId
|
|
17
|
+
]);
|
|
7
18
|
return /*#__PURE__*/ _jsxs("nav", {
|
|
8
19
|
className: "nc-replay__chapters",
|
|
9
20
|
"aria-label": REPLAY_COPY.chapters,
|
|
@@ -14,6 +25,7 @@ import { chapterMinutes, chapterProgress } from '../../_utils/replayProgress';
|
|
|
14
25
|
children: REPLAY_COPY.chapters
|
|
15
26
|
}),
|
|
16
27
|
/*#__PURE__*/ _jsx("ol", {
|
|
28
|
+
ref: row,
|
|
17
29
|
className: "nc-replay__chapter-list",
|
|
18
30
|
children: chapters.map((chapter, i)=>{
|
|
19
31
|
const current = chapter.id === chapterId;
|
|
@@ -54,6 +54,7 @@ import { ReplayStage } from '../ReplayStage';
|
|
|
54
54
|
className: `nc-replay${className ? ` ${className}` : ''}`,
|
|
55
55
|
"data-theme": theme,
|
|
56
56
|
"data-replay-status": status,
|
|
57
|
+
"data-replay-skipped": state.skipped.length,
|
|
57
58
|
children: [
|
|
58
59
|
/*#__PURE__*/ _jsx("style", {
|
|
59
60
|
children: REPLAY_CSS
|
|
@@ -65,6 +66,7 @@ import { ReplayStage } from '../ReplayStage';
|
|
|
65
66
|
frameRef: player.frameRef,
|
|
66
67
|
cursor: state.cursor,
|
|
67
68
|
rate: state.rate,
|
|
69
|
+
chapterId: state.chapterId,
|
|
68
70
|
onArrive: player.cursorArrived,
|
|
69
71
|
loading: status === 'loading',
|
|
70
72
|
children: overlay
|
|
@@ -5,6 +5,7 @@ import { useCameraPan } from '../../_hooks/useCameraPan';
|
|
|
5
5
|
import { useStageScale } from '../../_hooks/useStageScale';
|
|
6
6
|
import { REPLAY_COPY } from '../../_utils/copy';
|
|
7
7
|
import { pickLocalized } from '../../_utils/frameUrl';
|
|
8
|
+
import { effectiveRate } from '../../_utils/replayProgress';
|
|
8
9
|
import { cameraOffset, cameraShot, restingFocus, stageViewport } from '../../_utils/stageViewport';
|
|
9
10
|
import { ReplayCursorLayer } from '../ReplayCursor';
|
|
10
11
|
import { ReplayVeil } from './ReplayVeil';
|
|
@@ -17,7 +18,7 @@ import { ReplayVeil } from './ReplayVeil';
|
|
|
17
18
|
* it show what happens. The cursor layer shares the world's box and the frame's scale, so a point of the frame lands
|
|
18
19
|
* on the same spot of the layer.
|
|
19
20
|
*/ export function ReplayStage(props) {
|
|
20
|
-
const { manifest, locale, frameSrc, frameRef, cursor, rate, onArrive, loading, children } = props;
|
|
21
|
+
const { manifest, locale, frameSrc, frameRef, cursor, rate, chapterId, onArrive, loading, children } = props;
|
|
21
22
|
const frame = stageViewport();
|
|
22
23
|
const fit = useStageScale(frame);
|
|
23
24
|
const [whole, setWhole] = useState(false);
|
|
@@ -103,7 +104,7 @@ import { ReplayVeil } from './ReplayVeil';
|
|
|
103
104
|
/*#__PURE__*/ _jsx(ReplayCursorLayer, {
|
|
104
105
|
cursor: cursor,
|
|
105
106
|
scale: scale,
|
|
106
|
-
rate: rate,
|
|
107
|
+
rate: effectiveRate(manifest, chapterId, rate),
|
|
107
108
|
onArrive: onArrive
|
|
108
109
|
})
|
|
109
110
|
]
|
|
@@ -9,7 +9,10 @@ export interface ReplayStageProps {
|
|
|
9
9
|
/** Where the player finds the frame's window. */
|
|
10
10
|
frameRef: RefObject<HTMLIFrameElement | null>;
|
|
11
11
|
cursor: ReplayCursor | null;
|
|
12
|
+
/** The visitor's speed. */
|
|
12
13
|
rate: number;
|
|
14
|
+
/** The chapter on screen; its own pace multiplies `rate` for the cursor, as it does for the frame's clock. */
|
|
15
|
+
chapterId: string | null;
|
|
13
16
|
onArrive: (mark: number) => void;
|
|
14
17
|
/** Shows the loading veil over the frame. */
|
|
15
18
|
loading: boolean;
|
|
@@ -13,11 +13,14 @@ gsap.registerPlugin(useGSAP);
|
|
|
13
13
|
x: 0,
|
|
14
14
|
y: 0
|
|
15
15
|
};
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
16
|
+
// A jump must end any glide still under way, or the glide would carry the world on past it.
|
|
17
|
+
if (reduced || !on) {
|
|
18
|
+
gsap.killTweensOf(el);
|
|
19
|
+
gsap.set(el, {
|
|
20
|
+
x: to.x,
|
|
21
|
+
y: to.y
|
|
22
|
+
});
|
|
23
|
+
} else gsap.to(el, {
|
|
21
24
|
x: to.x,
|
|
22
25
|
y: to.y,
|
|
23
26
|
duration: 0.7,
|
|
@@ -3,13 +3,14 @@ import { useEffect, useEffectEvent, useRef, useState } from 'react';
|
|
|
3
3
|
import { CAMERA_BELOW_WIDTH, fitFrame } from '../_utils/stageViewport';
|
|
4
4
|
const FIT_HEIGHT_QUERY = '(min-width:1024px)';
|
|
5
5
|
const FIT_GAP = 4;
|
|
6
|
-
/** The height left for the frame: the window minus everything else of the player, minus the host's own offset. */ function roomHeight(box) {
|
|
6
|
+
/** The height left for the frame (0: not limited here): the window minus everything else of the player, minus the host's own offset. */ function roomHeight(box) {
|
|
7
7
|
if (typeof window === 'undefined' || !window.matchMedia(FIT_HEIGHT_QUERY).matches) return 0;
|
|
8
8
|
const root = box.closest('.nc-replay');
|
|
9
9
|
const view = box.firstElementChild;
|
|
10
10
|
if (!root || !(view instanceof HTMLElement)) return 0;
|
|
11
11
|
const offset = Number.parseFloat(getComputedStyle(root).getPropertyValue('--replay-fit-offset')) || 0;
|
|
12
|
-
|
|
12
|
+
// At least 1: 0 means "not limited" to `fitFrame`, and a window with no room left must still be floored, not unbounded.
|
|
13
|
+
return Math.max(1, window.innerHeight - (root.offsetHeight - view.offsetHeight) - offset - FIT_GAP);
|
|
13
14
|
}
|
|
14
15
|
/**
|
|
15
16
|
* The scale that fits `frame` into the element the returned ref points at: by width everywhere, and from 1024 px up
|
|
@@ -21,12 +22,18 @@ const FIT_GAP = 4;
|
|
|
21
22
|
width: 0,
|
|
22
23
|
height: 0
|
|
23
24
|
});
|
|
25
|
+
const last = useRef(room);
|
|
24
26
|
const measure = useEffectEvent(()=>{
|
|
25
27
|
const box = boxRef.current;
|
|
26
|
-
if (box)
|
|
28
|
+
if (!box) return;
|
|
29
|
+
const next = {
|
|
27
30
|
width: box.clientWidth,
|
|
28
31
|
height: roomHeight(box)
|
|
29
|
-
}
|
|
32
|
+
};
|
|
33
|
+
// Only a changed value is set: the fit resizes the view, which the observer sees, which measures again.
|
|
34
|
+
if (last.current.width === next.width && last.current.height === next.height) return;
|
|
35
|
+
last.current = next;
|
|
36
|
+
setRoom(next);
|
|
30
37
|
});
|
|
31
38
|
useEffect(()=>{
|
|
32
39
|
const box = boxRef.current;
|
|
@@ -11,6 +11,7 @@ export const initialReplayState = {
|
|
|
11
11
|
locale: 'en',
|
|
12
12
|
cursor: null,
|
|
13
13
|
unanswered: [],
|
|
14
|
+
skipped: [],
|
|
14
15
|
failure: null
|
|
15
16
|
};
|
|
16
17
|
/** The store's methods as creators over a plain state object, so tests can run them without React. */ export const replayMethodCreators = {
|
|
@@ -18,6 +19,7 @@ export const initialReplayState = {
|
|
|
18
19
|
Object.assign(s, {
|
|
19
20
|
...initialReplayState,
|
|
20
21
|
unanswered: [],
|
|
22
|
+
skipped: [],
|
|
21
23
|
locale: s.locale
|
|
22
24
|
});
|
|
23
25
|
},
|
|
@@ -59,6 +61,12 @@ export const initialReplayState = {
|
|
|
59
61
|
key
|
|
60
62
|
];
|
|
61
63
|
},
|
|
64
|
+
reportSkipped: (s)=>(skip)=>{
|
|
65
|
+
s.skipped = [
|
|
66
|
+
...s.skipped,
|
|
67
|
+
skip
|
|
68
|
+
];
|
|
69
|
+
},
|
|
62
70
|
fail: (s)=>(failure)=>{
|
|
63
71
|
s.failure = failure;
|
|
64
72
|
s.status = 'failed';
|
|
@@ -17,6 +17,12 @@ export interface ReplayCursor {
|
|
|
17
17
|
box: PointBox;
|
|
18
18
|
arrived: boolean;
|
|
19
19
|
}
|
|
20
|
+
/** An action the tape played on without: the player never stops for it, the page can read the list. */
|
|
21
|
+
export interface ReplaySkip {
|
|
22
|
+
stepId: string;
|
|
23
|
+
actionIndex: number;
|
|
24
|
+
reason: FailureReason;
|
|
25
|
+
}
|
|
20
26
|
export type ReplayPlayerState = {
|
|
21
27
|
status: ReplayStatus;
|
|
22
28
|
manifest: ReplayManifest | null;
|
|
@@ -30,6 +36,8 @@ export type ReplayPlayerState = {
|
|
|
30
36
|
cursor: ReplayCursor | null;
|
|
31
37
|
/** Endpoint keys the recording could not answer, each once: the audit wants none. */
|
|
32
38
|
unanswered: string[];
|
|
39
|
+
/** Every action skipped so far (a public tour keeps playing); `skipped.length` is the diagnostic count. */
|
|
40
|
+
skipped: ReplaySkip[];
|
|
33
41
|
failure: ReplayFailure | null;
|
|
34
42
|
};
|
|
35
43
|
export type ReplayPlayerMethods = {
|
|
@@ -44,6 +52,7 @@ export type ReplayPlayerMethods = {
|
|
|
44
52
|
setLocale: (locale: string) => void;
|
|
45
53
|
setCursor: (cursor: ReplayCursor | null) => void;
|
|
46
54
|
reportUnanswered: (key: string) => void;
|
|
55
|
+
reportSkipped: (skip: ReplaySkip) => void;
|
|
47
56
|
fail: (failure: ReplayFailure) => void;
|
|
48
57
|
clearFailure: () => void;
|
|
49
58
|
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `scrollLeft` that brings an item fully into a horizontally scrolling row, moving as little as possible: the row
|
|
3
|
+
* stays where it is when the item is already inside, and a row that cannot scroll that far is clamped by the browser.
|
|
4
|
+
* All four numbers are in the row's own scrolled pixels (the item's left edge counts from the row's content start).
|
|
5
|
+
*/
|
|
6
|
+
export declare function scrollLeftToReveal(current: number, viewWidth: number, itemLeft: number, itemWidth: number): number;
|
|
7
|
+
/** Scrolls `row` (never the page) so `item` is inside it. Returns the new `scrollLeft`. */
|
|
8
|
+
export declare function revealInRow(row: HTMLElement, item: HTMLElement): number;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `scrollLeft` that brings an item fully into a horizontally scrolling row, moving as little as possible: the row
|
|
3
|
+
* stays where it is when the item is already inside, and a row that cannot scroll that far is clamped by the browser.
|
|
4
|
+
* All four numbers are in the row's own scrolled pixels (the item's left edge counts from the row's content start).
|
|
5
|
+
*/ export function scrollLeftToReveal(current, viewWidth, itemLeft, itemWidth) {
|
|
6
|
+
if (itemLeft < current) return Math.max(0, itemLeft);
|
|
7
|
+
if (itemLeft + itemWidth > current + viewWidth) return Math.max(0, itemLeft + itemWidth - viewWidth);
|
|
8
|
+
return current;
|
|
9
|
+
}
|
|
10
|
+
/** Scrolls `row` (never the page) so `item` is inside it. Returns the new `scrollLeft`. */ export function revealInRow(row, item) {
|
|
11
|
+
const rowBox = row.getBoundingClientRect();
|
|
12
|
+
const itemBox = item.getBoundingClientRect();
|
|
13
|
+
const left = itemBox.left - rowBox.left + row.scrollLeft;
|
|
14
|
+
const next = scrollLeftToReveal(row.scrollLeft, row.clientWidth, left, itemBox.width);
|
|
15
|
+
if (next !== row.scrollLeft) row.scrollLeft = next;
|
|
16
|
+
return next;
|
|
17
|
+
}
|
|
@@ -75,8 +75,12 @@ const realClock = {
|
|
|
75
75
|
stopPlaying: ()=>{
|
|
76
76
|
wants.playing = false;
|
|
77
77
|
},
|
|
78
|
-
onReady: (recordingId)=>{
|
|
78
|
+
onReady: (recordingId, preparing)=>{
|
|
79
79
|
if (recordingId !== store.manifest?.id) return;
|
|
80
|
+
if (preparing) {
|
|
81
|
+
if (!ready) armGiveUp(); // alive but not ready: the wait starts over, play and seek stay queued
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
80
84
|
const first = !ready;
|
|
81
85
|
ready = true;
|
|
82
86
|
if (first) store.setStatus(wants.playing ? 'playing' : 'ready');
|
|
@@ -98,13 +102,18 @@ const realClock = {
|
|
|
98
102
|
if (message && !disposed) handle(message);
|
|
99
103
|
};
|
|
100
104
|
listen.addEventListener('message', onMessage);
|
|
101
|
-
|
|
102
|
-
|
|
105
|
+
let giveUp = null;
|
|
106
|
+
function armGiveUp() {
|
|
107
|
+
if (giveUp !== null) cancel(giveUp);
|
|
108
|
+
giveUp = after(options.readyTimeoutMs ?? READY_TIMEOUT_MS, ()=>{
|
|
103
109
|
if (!ready) failWith('frame_timeout', null);
|
|
104
110
|
});
|
|
111
|
+
}
|
|
112
|
+
const awaitFrame = ()=>{
|
|
113
|
+
armGiveUp();
|
|
105
114
|
const ask = ()=>{
|
|
106
115
|
if (ready || disposed) {
|
|
107
|
-
cancel(giveUp);
|
|
116
|
+
if (giveUp !== null) cancel(giveUp);
|
|
108
117
|
return;
|
|
109
118
|
}
|
|
110
119
|
send((e)=>({
|
|
@@ -5,7 +5,8 @@ export interface ReportDeps {
|
|
|
5
5
|
store: ReplayStoreApi;
|
|
6
6
|
send: SendToFrame;
|
|
7
7
|
/** The frame announced itself for this recording. */
|
|
8
|
-
|
|
8
|
+
/** `preparing`: the frame heard the hello but is still rebuilding its start state; it is not ready to play. */
|
|
9
|
+
onReady: (recordingId: string, preparing: boolean) => void;
|
|
9
10
|
isReady: () => boolean;
|
|
10
11
|
/** The visitor's intent to play ends with the run (failure, end). */
|
|
11
12
|
stopPlaying: () => void;
|
|
@@ -26,7 +26,7 @@ function chapterAt(manifest, at) {
|
|
|
26
26
|
return (message)=>{
|
|
27
27
|
const manifest = store.manifest;
|
|
28
28
|
if (message.type === 'ready') {
|
|
29
|
-
deps.onReady(message.recordingId);
|
|
29
|
+
deps.onReady(message.recordingId, message.preparing === true);
|
|
30
30
|
return;
|
|
31
31
|
}
|
|
32
32
|
if (!manifest || !deps.isReady()) return;
|
|
@@ -61,6 +61,13 @@ function chapterAt(manifest, at) {
|
|
|
61
61
|
case 'tick':
|
|
62
62
|
onTick(manifest, message.at, message.playing);
|
|
63
63
|
break;
|
|
64
|
+
case 'skipped':
|
|
65
|
+
store.reportSkipped({
|
|
66
|
+
stepId: message.stepId,
|
|
67
|
+
actionIndex: message.actionIndex,
|
|
68
|
+
reason: message.reason
|
|
69
|
+
});
|
|
70
|
+
break;
|
|
64
71
|
case 'unanswered':
|
|
65
72
|
store.reportUnanswered(message.key);
|
|
66
73
|
break;
|
|
@@ -19,7 +19,7 @@ const MAX_KEY_LENGTH = 200;
|
|
|
19
19
|
let generation = 0;
|
|
20
20
|
let abortWait = ()=>{};
|
|
21
21
|
const clock = createFrameHold(timeline);
|
|
22
|
-
// True while the state before the start chapter is
|
|
22
|
+
// True while the state before the start chapter is rebuilt: ticks stop, only the hello is answered (`preparing`).
|
|
23
23
|
let preluding = false;
|
|
24
24
|
let stopped = false;
|
|
25
25
|
const send = (build)=>{
|
|
@@ -28,8 +28,21 @@ const MAX_KEY_LENGTH = 200;
|
|
|
28
28
|
const announce = ()=>send((e)=>({
|
|
29
29
|
...e,
|
|
30
30
|
type: 'ready',
|
|
31
|
-
recordingId: manifest.id
|
|
31
|
+
recordingId: manifest.id,
|
|
32
|
+
...preluding ? {
|
|
33
|
+
preparing: true
|
|
34
|
+
} : {}
|
|
32
35
|
}));
|
|
36
|
+
const reportSkip = (stepId, actionIndex, reason)=>{
|
|
37
|
+
win.console?.warn(`[replay] step ${stepId} action ${actionIndex} skipped: ${reason}`);
|
|
38
|
+
send((e)=>({
|
|
39
|
+
...e,
|
|
40
|
+
type: 'skipped',
|
|
41
|
+
stepId,
|
|
42
|
+
actionIndex,
|
|
43
|
+
reason
|
|
44
|
+
}));
|
|
45
|
+
};
|
|
33
46
|
const tick = ()=>{
|
|
34
47
|
if (!preluding) send((e)=>({
|
|
35
48
|
...e,
|
|
@@ -77,7 +90,7 @@ const MAX_KEY_LENGTH = 200;
|
|
|
77
90
|
waitForFrame: options.waitForFrame,
|
|
78
91
|
waitUntil: (at)=>timeline.waitUntil(at),
|
|
79
92
|
hold: clock.hold,
|
|
80
|
-
onSkip: options.skipFailedSteps === false ? undefined : ({ actionIndex, reason })=>
|
|
93
|
+
onSkip: options.skipFailedSteps === false ? undefined : ({ actionIndex, reason })=>reportSkip(step.id, actionIndex, reason)
|
|
81
94
|
});
|
|
82
95
|
if (gen !== generation) return false;
|
|
83
96
|
if (result.ok) {
|
|
@@ -128,11 +141,14 @@ const MAX_KEY_LENGTH = 200;
|
|
|
128
141
|
peer: options.parent,
|
|
129
142
|
nonce: options.nonce
|
|
130
143
|
});
|
|
131
|
-
if (!message
|
|
144
|
+
if (!message) return;
|
|
145
|
+
// The hello is answered even while preluding (so the parent knows the frame is alive); the rest waits.
|
|
146
|
+
if (message.type === 'hello') {
|
|
147
|
+
announce();
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (preluding) return;
|
|
132
151
|
switch(message.type){
|
|
133
|
-
case 'hello':
|
|
134
|
-
announce();
|
|
135
|
-
break;
|
|
136
152
|
case 'play':
|
|
137
153
|
clock.play();
|
|
138
154
|
break;
|
|
@@ -187,7 +203,8 @@ const MAX_KEY_LENGTH = 200;
|
|
|
187
203
|
targetTimeoutMs,
|
|
188
204
|
settle,
|
|
189
205
|
cancelled: ()=>stopped
|
|
190
|
-
}
|
|
206
|
+
},
|
|
207
|
+
onSkip: options.skipFailedSteps === false ? undefined : reportSkip
|
|
191
208
|
}).then(()=>{
|
|
192
209
|
preluding = false;
|
|
193
210
|
if (!stopped) begin();
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type Ms, type ReplayStep, type Timeline, type VisibleCheck, type Win } from '../../../../src/Client/Replay';
|
|
1
|
+
import { type FailureReason, type Ms, type ReplayStep, type Timeline, type VisibleCheck, type Win } from '../../../../src/Client/Replay';
|
|
2
2
|
export interface FramePreludeOptions {
|
|
3
3
|
win: Win;
|
|
4
4
|
attribute: string;
|
|
@@ -11,6 +11,8 @@ export interface FramePreludeOptions {
|
|
|
11
11
|
visible?: VisibleCheck;
|
|
12
12
|
targetTimeoutMs?: number;
|
|
13
13
|
settle: () => Promise<void>;
|
|
14
|
+
/** Told of a step the prelude dropped (its target never appeared); `actionIndex` is the action that failed. */
|
|
15
|
+
onSkip?: (stepId: string, actionIndex: number, reason: FailureReason) => void;
|
|
14
16
|
/** True once the frame was stopped: the prelude ends at the next action. */
|
|
15
17
|
cancelled: () => boolean;
|
|
16
18
|
}
|
|
@@ -17,7 +17,7 @@ import { runStep } from '../../../../src/Client/Replay';
|
|
|
17
17
|
const actions = step.actions.filter(changesState);
|
|
18
18
|
if (actions.length === 0) continue;
|
|
19
19
|
timeline.jumpTo(Math.min(step.at, options.until));
|
|
20
|
-
await runStep({
|
|
20
|
+
const result = await runStep({
|
|
21
21
|
...step,
|
|
22
22
|
actions
|
|
23
23
|
}, {
|
|
@@ -32,5 +32,6 @@ import { runStep } from '../../../../src/Client/Replay';
|
|
|
32
32
|
waitForFrame: async ()=>{},
|
|
33
33
|
waitUntil: async (at)=>timeline.jumpTo(Math.min(at, options.until))
|
|
34
34
|
});
|
|
35
|
+
if (!result.ok) options.onSkip?.(step.id, result.actionIndex, result.reason);
|
|
35
36
|
}
|
|
36
37
|
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { Ms, ReplayChapter, ReplayManifest } from '../../../../src/Client/Replay';
|
|
2
2
|
/** How far the playhead is through a chapter, 0 to 1. */
|
|
3
3
|
export declare function chapterProgress(chapter: ReplayChapter, playhead: Ms): number;
|
|
4
|
+
/** The speed the drawn cursor moves at: the visitor's speed times the current chapter's own pace, as the frame's clock runs. */
|
|
5
|
+
export declare function effectiveRate(manifest: ReplayManifest, chapterId: string | null, visitorRate: number): number;
|
|
4
6
|
/** The 1-based position of a step among the recording's steps, or null when there is no current step. */
|
|
5
7
|
export declare function stepPosition(manifest: ReplayManifest, stepId: string | null): {
|
|
6
8
|
index: number;
|
|
@@ -3,6 +3,10 @@
|
|
|
3
3
|
if (span <= 0) return playhead >= chapter.to ? 1 : 0;
|
|
4
4
|
return Math.min(1, Math.max(0, (playhead - chapter.from) / span));
|
|
5
5
|
}
|
|
6
|
+
/** The speed the drawn cursor moves at: the visitor's speed times the current chapter's own pace, as the frame's clock runs. */ export function effectiveRate(manifest, chapterId, visitorRate) {
|
|
7
|
+
const chapter = manifest.chapters.find((item)=>item.id === chapterId) ?? manifest.chapters[0];
|
|
8
|
+
return visitorRate * (chapter?.rate ?? 1);
|
|
9
|
+
}
|
|
6
10
|
/** The 1-based position of a step among the recording's steps, or null when there is no current step. */ export function stepPosition(manifest, stepId) {
|
|
7
11
|
if (stepId === null) return null;
|
|
8
12
|
const at = manifest.steps.findIndex((step)=>step.id === stepId);
|
|
@@ -26,10 +26,13 @@ export interface FrameFit {
|
|
|
26
26
|
width: number;
|
|
27
27
|
height: number;
|
|
28
28
|
}
|
|
29
|
+
/** The smallest scale the height fit may shrink the frame to: below it the text is unreadable, so the page scrolls instead. */
|
|
30
|
+
export declare const MIN_FIT_SCALE = 0.35;
|
|
29
31
|
/**
|
|
30
32
|
* The scale that keeps the whole frame visible: the smaller of the width fit and the height fit. `availableHeight` is
|
|
31
|
-
* the height left for the frame
|
|
32
|
-
*
|
|
33
|
+
* the height left for the frame: 0 (or not a number) means the height is not limited and the width fit is used, e.g. a
|
|
34
|
+
* phone, where the page scrolls. A room that is too small (negative, or under `MIN_FIT_SCALE` of the frame) is raised to
|
|
35
|
+
* that floor, so the frame never collapses. The result is letterboxed by the caller and never wider than the box.
|
|
33
36
|
*/
|
|
34
37
|
export declare function fitFrame(boxWidth: number, availableHeight: number, frame: StageViewport): FrameFit;
|
|
35
38
|
/** The stage width under which the whole frame would be an unreadable thumbnail, so a camera follows the action. */
|
|
@@ -18,13 +18,16 @@
|
|
|
18
18
|
/** The uniform scale that fits a frame of `frameWidth` px into a box `boxWidth` px wide; 1 until the box is measured. */ export function fitScale(boxWidth, frameWidth) {
|
|
19
19
|
return boxWidth > 0 && frameWidth > 0 ? boxWidth / frameWidth : 1;
|
|
20
20
|
}
|
|
21
|
+
/** The smallest scale the height fit may shrink the frame to: below it the text is unreadable, so the page scrolls instead. */ export const MIN_FIT_SCALE = 0.35;
|
|
21
22
|
/**
|
|
22
23
|
* The scale that keeps the whole frame visible: the smaller of the width fit and the height fit. `availableHeight` is
|
|
23
|
-
* the height left for the frame
|
|
24
|
-
*
|
|
24
|
+
* the height left for the frame: 0 (or not a number) means the height is not limited and the width fit is used, e.g. a
|
|
25
|
+
* phone, where the page scrolls. A room that is too small (negative, or under `MIN_FIT_SCALE` of the frame) is raised to
|
|
26
|
+
* that floor, so the frame never collapses. The result is letterboxed by the caller and never wider than the box.
|
|
25
27
|
*/ export function fitFrame(boxWidth, availableHeight, frame) {
|
|
26
28
|
const byWidth = fitScale(boxWidth, frame.width);
|
|
27
|
-
const
|
|
29
|
+
const limited = Number.isFinite(availableHeight) && availableHeight !== 0 && frame.height > 0;
|
|
30
|
+
const byHeight = limited ? Math.max(availableHeight, frame.height * MIN_FIT_SCALE) / frame.height : Number.POSITIVE_INFINITY;
|
|
28
31
|
const scale = Math.min(byWidth, byHeight);
|
|
29
32
|
return {
|
|
30
33
|
scale,
|
package/dist/index.js
CHANGED
|
@@ -119,7 +119,7 @@ end
|
|
|
119
119
|
redis.call('ZADD', KEYS[1], now, ARGV[4])
|
|
120
120
|
redis.call('PEXPIRE', KEYS[1], windowMs + 1000)
|
|
121
121
|
return {1, count + 1}
|
|
122
|
-
`,hashIdentity=(identity)=>createHash3("sha256").update(identity.trim().toLowerCase()).digest("base64url").slice(0,16),RateLimiterBackendError,DEFAULT_AUTH_LOGIN,DEFAULT_AUTH_REGISTER,DEFAULT_AUTH_PASSWORD_RESET,DEFAULT_AUTH_PASSWORD_RESET_CONFIRM,DEFAULT_AUTH_MAGIC_LINK,DEFAULT_CONFIG4;var init_RateLimiter=__esm(()=>{RateLimiterBackendError=class RateLimiterBackendError extends Error{constructor(message){super(message);this.name="RateLimiterBackendError"}};DEFAULT_AUTH_LOGIN={window:"15m",max:5,perAddressMax:100,blockDuration:"30m"},DEFAULT_AUTH_REGISTER={window:"1h",max:3,perAddressMax:30,blockDuration:"1h"},DEFAULT_AUTH_PASSWORD_RESET={window:"1h",max:3,perAddressMax:30,blockDuration:"1h"},DEFAULT_AUTH_PASSWORD_RESET_CONFIRM={window:"1h",max:10,perAddressMax:30,blockDuration:"15m"},DEFAULT_AUTH_MAGIC_LINK={window:"1h",max:5,perAddressMax:30,blockDuration:"1h"},DEFAULT_CONFIG4={enabled:!0,strategy:"sliding-window",keyPrefix:"rl:",authRoutes:{window:"1m",max:10,login:DEFAULT_AUTH_LOGIN,register:DEFAULT_AUTH_REGISTER,passwordReset:DEFAULT_AUTH_PASSWORD_RESET,passwordResetConfirm:DEFAULT_AUTH_PASSWORD_RESET_CONFIRM,magicLink:DEFAULT_AUTH_MAGIC_LINK},publicRoutes:{window:"1m",max:3000},privateRoutes:{window:"1m",max:3000},byIp:!0,byUserId:!0,byEndpoint:!1,skipSuccessfulRequests:!1,headers:{remaining:"X-RateLimit-Remaining",reset:"X-RateLimit-Reset",limit:"X-RateLimit-Limit"},whitelist:[],blacklist:[]}});import{createCipheriv as createCipheriv2,createDecipheriv as createDecipheriv2,randomBytes as randomBytes3,scryptSync as scryptSync2,timingSafeEqual as timingSafeEqual2}from"crypto";var VERSION="v1",IV_LEN2=12,KEY_LEN=32,SCRYPT_SALT="nucleus-secrets-v1",keyCache,deriveKey2=(masterKey)=>{let cached=keyCache.get(masterKey);if(cached)return cached;let key2=scryptSync2(masterKey,SCRYPT_SALT,KEY_LEN);return keyCache.set(masterKey,key2),key2},encryptSecret=(plaintext,masterKey)=>{if(!masterKey)throw Error("secrets encryption key is empty");let iv=randomBytes3(IV_LEN2),cipher=createCipheriv2("aes-256-gcm",deriveKey2(masterKey),iv),ciphertext=Buffer.concat([cipher.update(plaintext,"utf-8"),cipher.final()]),tag=cipher.getAuthTag();return[VERSION,iv.toString("base64"),tag.toString("base64"),ciphertext.toString("base64")].join(":")},decryptSecret=(envelope,masterKey)=>{if(!masterKey)throw Error("secrets encryption key is empty");let[version,ivB64,tagB64,ctB64,...extra]=envelope.split(":");if(version!==VERSION||ivB64===void 0||tagB64===void 0||ctB64===void 0||extra.length>0)throw Error("not an encrypted secret envelope");let decipher=createDecipheriv2("aes-256-gcm",deriveKey2(masterKey),Buffer.from(ivB64,"base64"));return decipher.setAuthTag(Buffer.from(tagB64,"base64")),Buffer.concat([decipher.update(Buffer.from(ctB64,"base64")),decipher.final()]).toString("utf-8")},previewOf=(plaintext)=>{let len=plaintext.length;if(len===0)return"";if(len<12)return`\u2022\u2022\u2022\u2022${len}`;return`\u2022\u2022\u2022\u2022${plaintext.slice(-4)}`};var init_crypto=__esm(()=>{keyCache=new Map});function discoverSlots(source){let config=isPlainObject(source)?source:{},slots=new Map,add=(slot)=>{let id=`${slot.scope}.${slot.key}`;if(!slots.has(id))slots.set(id,slot)},valueAt=(scope,key2)=>{let node=config;for(let segment of scope.split(".")){if(!isPlainObject(node))return;node=node[segment]}if(!isPlainObject(node))return;let value2=node[key2];if(typeof value2==="string")return value2;if(Array.isArray(value2)&&value2.every((entry)=>typeof entry==="string"))return value2.length>0?value2.join(","):void 0;return};for(let descriptor of SECRET_SLOT_DESCRIPTORS)for(let scope of expandPath(config,descriptor.path,descriptor.always===!0)){let leaf=scope.split(".").pop()??descriptor.group,group=descriptor.path.endsWith("*")?`${descriptor.group}:${leaf}`:descriptor.group;for(let declared of descriptor.keys)add({scope,key:declared.key,kind:declared.kind??kindFor(declared.key),label:declared.label,group,required:declared.required??!1,requiredWhen:declared.requiredWhen,hint:declared.hint,secret:declared.secret??descriptor.secret??!0,configValue:valueAt(scope,declared.key)})}let walk=(node,path,depth)=>{if(depth>6)return;for(let[key2,value2]of Object.entries(node)){if(SKIP_SECTIONS.has(key2))continue;let childPath=path?`${path}.${key2}`:key2;if(isPlainObject(value2)){walk(value2,childPath,depth+1);continue}if(typeof value2!=="string"&&value2!==void 0&&value2!==null)continue;if(!CREDENTIAL_KEY_PATTERN.test(key2))continue;if(NOT_A_CREDENTIAL.has(key2.toLowerCase()))continue;if(BOOT_ONLY_PATHS.has(`${path}.${key2}`))continue;let owner=path.split(".").pop(),label=owner&&owner.toLowerCase()!==key2.toLowerCase()?`${humanize(owner)} \u2014 ${humanize(key2)}`:humanize(key2);add({scope:path,key:key2,kind:kindFor(key2),label,group:path.split(".")[0]??"other",required:!1,secret:!0,configValue:typeof value2==="string"?value2:void 0})}};return walk(config,"",0),[...slots.values()].sort((a,b)=>a.group.localeCompare(b.group)||a.scope.localeCompare(b.scope)||a.key.localeCompare(b.key))}var CREDENTIAL_KEY_PATTERN,NOT_A_CREDENTIAL,BOOT_ONLY_PATHS,SKIP_SECTIONS,kindFor=(key2)=>{let k=key2.toLowerCase();if(k.includes("json"))return"json";if(k.includes("connection"))return"connection_string";if(k.includes("privatekey")||k.includes("private_key"))return"pem";if(k.includes("clientid")||k.includes("client_id"))return"text";return"password"},humanize=(key2)=>key2.replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/\b\w/g,(c)=>c.toUpperCase()),SECRET_SLOT_DESCRIPTORS,isPlainObject=(value2)=>typeof value2==="object"&&value2!==null&&!Array.isArray(value2),expandPath=(config,path,always=!1)=>{let segments=path.split("."),scopes2=[{path:"",node:config}];for(let segment of segments){let next=[];for(let current of scopes2){if(!isPlainObject(current.node))continue;if(segment==="*")for(let[childKey,childValue]of Object.entries(current.node))next.push({path:current.path?`${current.path}.${childKey}`:childKey,node:childValue});else if(segment in current.node)next.push({path:current.path?`${current.path}.${segment}`:segment,node:current.node[segment]});else if(always)next.push({path:current.path?`${current.path}.${segment}`:segment,node:{}})}scopes2=next}return scopes2.filter((s)=>isPlainObject(s.node)).map((s)=>s.path)},looksLikeEnvName=(value2)=>!!value2&&/^[A-Z][A-Z0-9_]{2,}$/.test(value2);var init_registry2=__esm(()=>{CREDENTIAL_KEY_PATTERN=/(secret|password|passwd|apikey|api_key|accesskey|access_key|privatekey|private_key|token|credential|connection_string|connectionstring|clientid|client_id|encryptionkey|encryption_key|servicekey|service_key|json_file_path|jsonfilepath)$/i,NOT_A_CREDENTIAL=new Set(["preventapikeymanagement","allowapplicationkeys","maxkeysperuser","tokenurl","accesstoken","refreshtoken","sessiontoken"]),BOOT_ONLY_PATHS=new Set(["authorization.godminPassword","authorization.godminEmail","authentication.accessToken.secret","authentication.refreshToken.secret","authentication.sessionToken.secret","backup.encryptionKey","notification.channels.telegram.botToken","notification.channels.webhook.headers","domains.cloudflare.apiToken"]),SKIP_SECTIONS=new Set(["entities","systemTables","system_tables","tables","columns","indexes","routes","cors","swagger","secrets"]),SECRET_SLOT_DESCRIPTORS=[{path:"authentication.oauth.providers.*",group:"oauth",label:"OAuth / SSO",keys:[{key:"clientId",kind:"text",label:"Client ID",required:!0},{key:"clientSecret",kind:"password",label:"Client Secret",required:!0},{key:"tenantId",kind:"text",label:"Tenant ID"},{key:"redirectUri",kind:"text",secret:!1,required:!0,label:"Reply URL (Redirect URI)",hint:"The return address registered with the provider. It must be written identically on the provider side too (e.g. Entra > Authentication > Redirect URIs)."}]},{always:!0,path:"email.gmail",group:"email",label:"Gmail (service account)",keys:[{key:"service_account_json",kind:"json",label:"Service Account JSON",required:!0,requiredWhen:"enabled"}]},{always:!0,path:"email.azure",group:"email",label:"Azure Communication Services",keys:[{key:"connection_string",kind:"connection_string",label:"Connection String",required:!0,requiredWhen:"enabled"}]},{always:!0,path:"email.smtp",group:"email",label:"SMTP (Microsoft 365, Exchange, corporate mail)",keys:[{key:"enabled",kind:"boolean",secret:!1,label:"Send through this provider",hint:"The provider that is switched on carries the mail. If the panel cannot read this flag, the card stays \u201CNot set\u201D even when the details are filled in."},{key:"host",kind:"text",label:"Server",required:!0,requiredWhen:"enabled",hint:"smtp.office365.com for Microsoft 365"},{key:"port",kind:"text",label:"Port",hint:"Left empty this is 587 (STARTTLS). 465 means implicit TLS."},{key:"user",kind:"text",label:"Mailbox",required:!0,requiredWhen:"enabled",hint:"The address the password belongs to. It is also the sender address."},{key:"password",kind:"password",label:"Password / app password",required:!0,requiredWhen:"enabled",hint:"If the account has multi-factor authentication, the app password Microsoft generated. In Exchange Online, SMTP AUTH is off per tenant by default and a correct password is refused too \u2014 ask IT to turn it on for that mailbox."},{key:"sender_address",kind:"text",label:"Sender address (optional)",hint:"Left empty, the mailbox itself is used. If you enter a different address, Exchange requires that mailbox to have been granted \u201CSend As\u201D for it; without that the send is refused."},{key:"from_name",kind:"text",label:"Display name",hint:"The name the recipient reads in their inbox, e.g. the name of the portal."}]},{always:!0,path:"service",group:"service",label:"The server\u2019s own key",keys:[{key:"api_key",kind:"password",label:"Service API key",hint:"Some work the server has to do in its OWN name \u2014 counting how many people answered a survey, for instance. That cannot be done with an employee\u2019s permissions, and should not be. Generate the key in the admin panel and paste it here; it carries its owner\u2019s roles, not godmin\u2019s. Left empty, this work is skipped silently."}]},{always:!0,path:"storage.smb",group:"storage",label:"SMB / CIFS share",keys:[{key:"username",kind:"text",label:"Username",required:!0},{key:"password",kind:"password",label:"Password",required:!0}]},{secret:!1,always:!0,path:"storage",group:"storage",label:"File store",keys:[{key:"provider",kind:"text",label:"Storage kind",hint:"local (the server\u2019s own disk) or smb (a corporate file server). The change takes effect immediately."}]},{secret:!1,always:!0,path:"storage.smb",group:"storage",label:"SMB / CIFS share",keys:[{key:"url",kind:"text",label:"Share address",hint:"Paste it exactly as the customer sent it: smb://server/share \u2014 the server and the share name are read from this."},{key:"domain",kind:"text",label:"Domain",hint:"The domain part when the user is written as DOMAIN\\user. Leave empty if it is not needed."},{key:"base_path",kind:"text",label:"Folder inside the share",hint:"The subfolder uploads are gathered in. Empty means the root of the share."}]},{path:"payment.providers.*",group:"payment",label:"Payment provider",keys:[{key:"apiKey",kind:"password",label:"API Key",required:!0},{key:"secretKey",kind:"password",label:"Secret Key",required:!0},{key:"webhookSecret",kind:"password",label:"Webhook Secret"}]},{path:"captcha",group:"captcha",label:"Captcha",keys:[{key:"secretKey",kind:"password",label:"Secret Key"}]},{secret:!1,path:"authentication",group:"portal",label:"Portal address",keys:[{key:"trustedAppOrigins",kind:"list",label:"Trusted origins",required:!0,hint:"The address(es) the portal is installed at. Password-reset and SSO return links are built from these. Wildcard: *.company.com"}]},{secret:!1,always:!0,path:"email",group:"email",label:"Email provider",keys:[{key:"provider",kind:"text",label:"Provider to use",hint:"azure or gmail. Left empty, whichever provider is switched on is used."}]},{secret:!1,always:!0,path:"email.azure",group:"email",label:"Azure Communication Services",keys:[{key:"enabled",kind:"boolean",label:"Azure email enabled",hint:"Entering the connection string is not enough on its own \u2014 sending is turned on by this switch."},{key:"sender_address",kind:"text",label:"Sender address"},{key:"from_name",kind:"text",label:"Sender name",hint:"The name the recipient sees in their inbox in place of the address. Empty means the address shows."}]},{secret:!1,always:!0,path:"email.gmail",group:"email",label:"Gmail (service account)",keys:[{key:"enabled",kind:"boolean",label:"Gmail email enabled"},{key:"from_email",kind:"text",label:"Sender address"},{key:"from_name",kind:"text",label:"Sender name",hint:"The name the recipient sees in their inbox in place of the address. Empty means the address shows."}]}]});import{and as and12,eq as eq17}from"drizzle-orm";class SecretsStore{db;resolveTable;masterKey;constructor(deps){this.db=deps.db,this.resolveTable=deps.resolveTable,this.masterKey=deps.masterKey}table(schemaName){return this.resolveTable(SECRETS_TABLE,schemaName)}async loadAll(schemaName){let values=new Map,failed2=[],table=this.table(schemaName);if(!table)return{values,failed:failed2,tableMissing:!0};let rows;try{rows=(await this.db.select().from(table).where(eq17(col(table,"isActive"),!0))).map(secretRowOf)}catch(error3){if(isMissingTableError(error3))return{values,failed:failed2,tableMissing:!0};throw error3}for(let row of rows)try{values.set(cacheKeyOf(row.scope,row.key),decryptSecret(row.valueEnc,this.masterKey))}catch{failed2.push(`${row.scope}.${row.key}`)}return{values,failed:failed2}}async list(schemaName){let table=this.table(schemaName);if(!table)return[];try{return(await this.db.select().from(table)).map(secretRowOf).filter((r)=>r.isActive!==!1).map(rowToMeta)}catch(error3){if(isMissingTableError(error3))return[];throw error3}}async get(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return null;let row=(await this.db.select().from(table).where(and12(eq17(col(table,"scope"),scope),eq17(col(table,"key"),key2))).limit(1))[0];return row?secretRowOf(row):null}async set(params,schemaName){let table=this.table(schemaName);if(!table)return null;let existing=await this.get(params.scope,params.key,schemaName),valueEnc=encryptSecret(params.value,this.masterKey),preview=previewOf(params.value),now=new Date;if(existing)await this.db.update(table).set({valueEnc,previousEnc:existing.valueEnc,preview,kind:params.kind??existing.kind??"text",description:params.description??existing.description,version:(existing.version??1)+1,rotatedAt:now,isActive:!0,updatedAt:now,updatedBy:params.actorId??null}).where(eq17(col(table,"id"),existing.id));else await this.db.insert(table).values({scope:params.scope,key:params.key,valueEnc,preview,kind:params.kind??"text",description:params.description??null,version:1,isActive:!0,createdBy:params.actorId??null,updatedBy:params.actorId??null});let saved=await this.get(params.scope,params.key,schemaName);return saved?rowToMeta(saved):null}async rollback(scope,key2,actorId,schemaName){let table=this.table(schemaName);if(!table)return null;let existing=await this.get(scope,key2,schemaName);if(!existing?.previousEnc)return null;let plaintext=decryptSecret(existing.previousEnc,this.masterKey),now=new Date;await this.db.update(table).set({valueEnc:existing.previousEnc,previousEnc:existing.valueEnc,preview:previewOf(plaintext),version:(existing.version??1)+1,rotatedAt:now,updatedAt:now,updatedBy:actorId??null}).where(eq17(col(table,"id"),existing.id));let saved=await this.get(scope,key2,schemaName);return saved?rowToMeta(saved):null}async remove(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return!1;let existing=await this.get(scope,key2,schemaName);if(!existing)return!1;return await this.db.delete(table).where(eq17(col(table,"id"),existing.id)),!0}async touch(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return;await this.db.update(table).set({lastUsedAt:new Date}).where(and12(eq17(col(table,"scope"),scope),eq17(col(table,"key"),key2)))}async reencryptAll(newMasterKey,schemaName){let table=this.table(schemaName);if(!table)return{migrated:0,failed:[]};let rows=(await this.db.select().from(table)).map(secretRowOf),failed2=[],planned=[];for(let row of rows)try{let plaintext=decryptSecret(row.valueEnc,this.masterKey),previous=row.previousEnc?encryptSecret(decryptSecret(row.previousEnc,this.masterKey),newMasterKey):null;planned.push({id:row.id,valueEnc:encryptSecret(plaintext,newMasterKey),previousEnc:previous})}catch{failed2.push(`${row.scope}.${row.key}`)}if(failed2.length>0)return{migrated:0,failed:failed2};return await this.db.transaction(async(tx)=>{for(let row of planned)await tx.update(table).set({valueEnc:row.valueEnc,previousEnc:row.previousEnc}).where(eq17(col(table,"id"),row.id))}),this.masterKey=newMasterKey,{migrated:planned.length,failed:failed2}}}var SECRETS_TABLE="nucleusSecrets",col,SECRET_KINDS,isSecretKind=(value2)=>Object.hasOwn(SECRET_KINDS,value2),secretRowOf=(source)=>{let row=rowOf(source);return{id:asText(row.id)??"",scope:asText(row.scope)??"",key:asText(row.key)??"",valueEnc:asText(row.valueEnc)??"",previousEnc:asText(row.previousEnc)??null,preview:asText(row.preview)??null,kind:asText(row.kind)??null,description:asText(row.description)??null,version:asNumber(row.version)??1,rotatedAt:asDate(row.rotatedAt)??null,lastUsedAt:asDate(row.lastUsedAt)??null,updatedAt:asDate(row.updatedAt)??null,updatedBy:asText(row.updatedBy)??null,isActive:asBoolean(row.isActive)??null}},toIso=(value2)=>value2?new Date(value2).toISOString():null,UNDEFINED_TABLE="42P01",isMissingTableError=(error3)=>{let seen=new Set,current=typeof error3==="object"&&error3!==null?error3:void 0;while(current&&!seen.has(current)){if(seen.add(current),fieldOf(current,"code")===UNDEFINED_TABLE)return!0;let message=fieldOf(current,"message");if(typeof message==="string"&&/relation .* does not exist/i.test(message))return!0;let cause=fieldOf(current,"cause");current=typeof cause==="object"&&cause!==null?cause:void 0}return!1},rowToMeta=(row)=>({id:row.id,scope:row.scope,key:row.key,kind:row.kind!==null&&isSecretKind(row.kind)?row.kind:"text",preview:row.preview??"",description:row.description,version:row.version??1,canRollback:!!row.previousEnc,rotatedAt:toIso(row.rotatedAt),lastUsedAt:toIso(row.lastUsedAt),updatedAt:toIso(row.updatedAt),updatedBy:row.updatedBy}),cacheKeyOf=(scope,key2)=>`${scope}.${key2}`;var init_store3=__esm(()=>{init_crypto();col=columnOf,SECRET_KINDS={text:!0,password:!0,json:!0,connection_string:!0,pem:!0,boolean:!0,list:!0}});class SecretsService{store;logger;getRedis;refreshIntervalMs;schemaName;cache=new Map;timer=null;localRevision=0;loaded=!1;tableMissing=!1;warnedTableMissing=!1;constructor(deps){this.store=deps.store,this.logger=deps.logger,this.getRedis=deps.getRedis,this.refreshIntervalMs=deps.refreshIntervalMs??DEFAULT_REFRESH_MS,this.schemaName=deps.schemaName}async start(){if(await this.refresh(),this.timer)return;let timer=setInterval(()=>{this.refreshIfStale()},this.refreshIntervalMs);timer.unref?.(),this.timer=timer}stop(){if(this.timer)clearInterval(this.timer);this.timer=null}isReady(){return this.loaded}size(){return this.cache.size}isTableMissing(){return this.tableMissing}async refresh(){try{let{values,failed:failed2,tableMissing}=await this.store.loadAll(this.schemaName);if(tableMissing){if(this.tableMissing=!0,!this.warnedTableMissing)this.warnedTableMissing=!0,this.logger.warn("[Secrets] nucleus_secrets does not exist yet \u2014 env and literal values resolve normally; "+"the store activates automatically once the schema sync creates it");return}if(this.tableMissing)this.tableMissing=!1,this.warnedTableMissing=!1,this.logger.info("[Secrets] nucleus_secrets is now available \u2014 credential store active");if(this.cache=values,this.loaded=!0,failed2.length>0)this.logger.error("[Secrets] Credentials failed to decrypt and were skipped",{slots:failed2,hint:"master key changed without re-encrypting \u2014 POST /secrets/reencrypt with the old key"})}catch(error3){this.logger.warn("[Secrets] Refresh failed, keeping cached values",{error:error3 instanceof Error?error3.message:String(error3)})}}async refreshIfStale(){let redis=this.getRedis?.();if(!redis)return this.refresh();try{let result=await redis.read(REVISION_KEY),remote=Number(result.data??0);if(Number.isFinite(remote)&&remote===this.localRevision&&this.loaded)return;await this.refresh(),this.localRevision=Number.isFinite(remote)?remote:this.localRevision}catch{await this.refresh()}}async bumpRevision(){let redis=this.getRedis?.();if(!redis)return;try{let next=Date.now();this.localRevision=next,await redis.create(REVISION_KEY,next)}catch{}}get(scope,key2){return this.cache.get(cacheKeyOf(scope,key2))}has(scope,key2){return this.cache.has(cacheKeyOf(scope,key2))}resolve(scope,key2,configValue){let fromDb=this.cache.get(cacheKeyOf(scope,key2));if(fromDb)return{value:fromDb,source:"db"};if(configValue){let fromEnv=process.env[configValue];if(fromEnv)return{value:fromEnv,source:"env"};if(looksLikeEnvName(configValue))return{value:void 0,source:"missing"};return{value:configValue,source:"literal"}}return{value:void 0,source:"missing"}}value(scope,key2,configValue){return this.resolve(scope,key2,configValue).value}listValue(scope,key2,configValue){let fallback=Array.isArray(configValue)?configValue.join(","):configValue,raw=this.value(scope,key2,fallback);if(!raw)return Array.isArray(configValue)?configValue:[];return raw.split(/[,;\n\r]+/).map((entry)=>entry.trim()).filter(Boolean)}flag(scope,key2,configValue){let raw=this.get(scope,key2);if(raw===void 0)return configValue===!0;return raw==="true"||raw==="1"}liveConfig(scope,node,keys){let live={...node};for(let key2 of keys){let declared=fieldOf(node,key2),configValue=typeof declared==="string"?declared:void 0;Object.defineProperty(live,key2,{get:()=>this.resolve(scope,key2,configValue).value,enumerable:!0,configurable:!0})}return live}async describe(config,slots){let discovered=slots??discoverSlots(config),stored=await this.store.list(this.schemaName),byId=new Map(stored.map((s)=>[cacheKeyOf(s.scope,s.key),s]));return discovered.map((slot)=>{let id=cacheKeyOf(slot.scope,slot.key),record3=byId.get(id),{value:value2,source}=this.resolve(slot.scope,slot.key,slot.configValue),envName=looksLikeEnvName(slot.configValue)?slot.configValue:void 0,gate=slot.requiredWhen?this.flag(slot.scope,slot.requiredWhen,configFlagAt(config,slot.scope,slot.requiredWhen)):!0;return{...slot,required:slot.required&&gate,configValue:envName,source,value:slot.secret?void 0:value2,preview:slot.secret?source==="db"&&record3?record3.preview:value2?previewOf(value2):"":value2??"",envName,version:record3?.version,rotatedAt:record3?.rotatedAt??null,canRollback:record3?.canRollback??!1}})}async list(){return this.store.list(this.schemaName)}async set(params){let saved=await this.store.set(params,this.schemaName);return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential stored",{scope:params.scope,key:params.key,version:saved?.version,actor:params.actorId}),saved}async rollback(scope,key2,actorId){let saved=await this.store.rollback(scope,key2,actorId,this.schemaName);if(!saved)return null;return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential rolled back",{scope,key:key2,actor:actorId}),saved}async remove(scope,key2,actorId){if(!await this.store.remove(scope,key2,this.schemaName))return!1;return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential removed",{scope,key:key2,actor:actorId}),!0}async reencryptAll(newMasterKey){let result=await this.store.reencryptAll(newMasterKey,this.schemaName);return await this.refresh(),await this.bumpRevision(),result}}var REVISION_KEY="nucleus:secrets:revision",DEFAULT_REFRESH_MS=30000,configFlagAt=(config,scope,key2)=>{let node=config;for(let segment of scope.split(".")){if(typeof node!=="object"||node===null)return;node=fieldOf(node,segment)}if(typeof node!=="object"||node===null)return;let value2=fieldOf(node,key2);if(typeof value2==="boolean")return value2;if(typeof value2==="string")return value2==="true"||value2==="1";return};var init_SecretsService=__esm(()=>{init_crypto();init_registry2();init_store3()});var resolveMasterKey=(configured)=>{if(configured){let fromEnv=process.env[configured];if(fromEnv)return fromEnv;if(!/^[A-Z][A-Z0-9_]{2,}$/.test(configured))return configured}return process.env.NUCLEUS_SECRETS_KEY||void 0};var init_Secrets=__esm(()=>{init_crypto();init_registry2();init_SecretsService();init_store3()});var rowToTenantRecord=(source)=>{let row=rowOf(source);return{id:String(row.id||""),subdomain:String(row.subdomain||""),schemaName:String(row.schemaName||row.schema_name||""),companyId:String(row.companyId||row.company_id||""),companyName:row.companyName!=null?String(row.companyName):row.company_name!=null?String(row.company_name):null,godAdminEmail:String(row.godAdminEmail||row.god_admin_email||""),status:parseStatus(row.status),plan:row.plan!=null?String(row.plan):null,domain:row.domain!=null?String(row.domain):null,settings:parseJsonbToConfig(row.settings),trustedSources:parseTrustedSources(row.trustedSources||row.trusted_sources),maxUsers:row.maxUsers!=null?Number(row.maxUsers):row.max_users!=null?Number(row.max_users):null,provisionedAt:row.provisionedAt!=null?String(row.provisionedAt):row.provisioned_at!=null?String(row.provisioned_at):null,suspendedAt:row.suspendedAt!=null?String(row.suspendedAt):row.suspended_at!=null?String(row.suspended_at):null,suspendedReason:row.suspendedReason!=null?String(row.suspendedReason):row.suspended_reason!=null?String(row.suspended_reason):null}},rowToFeatureRecord=(source,parseConfig)=>{let row=rowOf(source);return{id:String(row.id||""),tenantId:String(row.tenantId||row.tenant_id||""),featureName:String(row.featureName||row.feature_name||""),enabled:Boolean(row.enabled),featureConfig:parseConfig(row.config)}},parseStatus=(value2)=>{let valid=["provisioning","active","suspended","archived"],str2=String(value2||"provisioning");return valid.find((status)=>status===str2)??"provisioning"},parseJsonbToConfig=(value2)=>{if(!value2||typeof value2!=="object")return{};let result={};for(let[k,v]of Object.entries(rowOf(value2)))if(typeof v==="string"||typeof v==="number"||typeof v==="boolean")result[k]=v;return result},parseTrustedSources=(value2)=>{if(!Array.isArray(value2))return[];return value2.map((item)=>{let entry=typeof item==="object"&&item!==null?rowOf(item):{};return{allowHeaderAuth:entry.allowHeaderAuth===!0||entry.allow_header_auth===!0,allowedIps:textEntries(entry.allowedIps||entry.allowed_ips),allowedServices:textEntries(entry.allowedServices||entry.allowed_services)}})},textEntries=(value2)=>Array.isArray(value2)?value2.filter((entry)=>typeof entry==="string"):void 0,normalizeHost=(host)=>{return((host||"").split(":")[0]||"").toLowerCase().replace(/\.$/,"")},extractSubdomain=(host)=>{let hostWithoutPort=host.split(":")[0]||"";if(hostWithoutPort==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(hostWithoutPort))return null;let parts=hostWithoutPort.split(".");if(parts.length<3)return null;let subdomain=parts[0]||"";if(!subdomain||subdomain==="www")return null;return subdomain},toIPv4Octets=(address)=>{let bare=address.startsWith("::ffff:")?address.slice(7):address;if(bare.includes(":"))return null;let parts=bare.split(".");if(parts.length!==4)return null;let[a,b,c,d]=parts.map((part)=>/^\d{1,3}$/.test(part)?Number(part):Number.NaN);if(a===void 0||b===void 0||c===void 0||d===void 0)return null;let octets=[a,b,c,d];return octets.every((o)=>Number.isInteger(o)&&o>=0&&o<=255)?octets:null},isIpInCidr=(ip,cidr)=>{let[cidrIp,prefixStr]=cidr.split("/");if(!cidrIp||!prefixStr)return!1;let prefix=Number.parseInt(prefixStr,10);if(Number.isNaN(prefix)||prefix<0||prefix>32)return!1;let ipParts=toIPv4Octets(ip),cidrParts=toIPv4Octets(cidrIp);if(!ipParts||!cidrParts)return!1;let toNumber=([a,b,c,d])=>(a<<24|b<<16|c<<8|d)>>>0,ipNum=toNumber(ipParts),cidrNum=toNumber(cidrParts),mask=prefix===0?0:~((1<<32-prefix)-1)>>>0;return(ipNum&mask)===(cidrNum&mask)},isTrustedSource=(tenant,request,authMode,fallbackSources,vettedClientIp)=>{let ownSources=tenant.trustedSources,trustedSources=Array.isArray(ownSources)&&ownSources.length>0?ownSources:fallbackSources;if(!trustedSources||!Array.isArray(trustedSources)||trustedSources.length===0)return!1;let clientIp=vettedClientIp?.trim()||"",serviceId=request.headers.get("x-service-id")||"";for(let source of trustedSources){if(!source.allowHeaderAuth)continue;if(source.allowedIps&&source.allowedIps.length>0){if(source.allowedIps.some((allowedIp)=>{if(allowedIp.includes("/"))return isIpInCidr(clientIp,allowedIp);return clientIp===allowedIp}))return!0}if(source.allowedServices&&source.allowedServices.length>0){if(source.allowedServices.includes(serviceId))return!0}}return!1},pickRequestHost=(request,hostHeader,hostHeaderTrusted)=>{if(hostHeader&&hostHeaderTrusted){let forwarded=request.headers.get(hostHeader)?.split(",")[0]?.trim();if(forwarded)return forwarded}return request.headers.get("host")||new URL(request.url).host||""};var init_helpers2=()=>{};import{pgSchema}from"drizzle-orm/pg-core";function createProvisionedSchemas(deps){let cache=new Map;return(schemaName)=>{let tenant=deps.tenantOf(schemaName);if(!tenant||!PROVISIONED_STATUSES.has(tenant.status))return;let cached=cache.get(schemaName);if(cached)return cached;let schema3=pgSchema(schemaName),built={tables:deps.createTables(schema3),relations:deps.createRelations?deps.createRelations(schema3):{}};return cache.set(schemaName,built),built}}function hostTablesResolver(mainSchema,mainTables,source){return(schemaName)=>{if(schemaName===mainSchema)return mainTables;return source()?.getProvisionedSchema(schemaName)?.tables}}function hostRelationsResolver(mainSchema,mainRelations,source){return(schemaName)=>{if(schemaName===mainSchema)return mainRelations;return source()?.getProvisionedSchema(schemaName)?.relations??{}}}var PROVISIONED_STATUSES;var init_provisionedSchemas=__esm(()=>{PROVISIONED_STATUSES=new Set(["provisioning","active","suspended","archived"])});async function withDeadline(promise3,timeoutMs,message){promise3.catch(()=>{});let timer,deadline=new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(Error(message)),timeoutMs)});try{return await Promise.race([promise3,deadline])}finally{if(timer)clearTimeout(timer)}}var exports_schemaReconcile={};__export(exports_schemaReconcile,{undeclaredTables:()=>undeclaredTables,setDefaultStatement:()=>setDefaultStatement,renderDefaultLiteral:()=>renderDefaultLiteral,reconcileMissingColumns:()=>reconcileMissingColumns,readActualSchemaDetailed:()=>readActualSchemaDetailed,readActualSchema:()=>readActualSchema,planRepair:()=>planRepair,findDrift:()=>findDrift,expectedFromTables:()=>expectedFromTables,describeRepair:()=>describeRepair,createMissingTables:()=>createMissingTables,addColumnStatement:()=>addColumnStatement});import{getTableColumns as getTableColumns2,sql as sql10}from"drizzle-orm";function findDrift(expected,actual,actualDefaults){let missingTables=[],missingColumns=[],columnsMissingDefault=[];for(let table of expected){let have=actual[table.name];if(!have){missingTables.push(table.name);continue}let haveDefault=actualDefaults?.[table.name];for(let column of table.columns){if(!have.has(column.name)){missingColumns.push({table:table.name,column});continue}if(haveDefault&&column.hasDefault&&column.defaultLiteral!==void 0&&!haveDefault.has(column.name))columnsMissingDefault.push({table:table.name,column})}}return{missingTables,missingColumns,columnsMissingDefault}}function addColumnStatement(schema3,table,column){if(column.notNull&&!column.hasDefault)return null;return[`alter table "${schema3}"."${table}"`,`add column if not exists "${column.name}" ${column.sqlType}`].join(" ")}function setDefaultStatement(schema3,table,column){if(column.defaultLiteral===void 0)return null;return`alter table "${schema3}"."${table}" alter column "${column.name}" set default ${column.defaultLiteral}`}function planRepair(schema3,drift){let statements=[],unsafe3=[];for(let{table,column}of drift.missingColumns){let statement=addColumnStatement(schema3,table,column);if(statement)statements.push(statement);else unsafe3.push({table,column:column.name,why:"declared NOT NULL with no default, and the table already has rows to fill"})}for(let{table,column}of drift.columnsMissingDefault){let statement=setDefaultStatement(schema3,table,column);if(statement)statements.push(statement)}return{statements,unsafe:unsafe3,missingTables:drift.missingTables,createdTables:[],undeclaredTables:[]}}function undeclaredTables(expected,actual){let declared=new Set(expected.map((t)=>t.name));return Object.keys(actual).filter((name)=>!declared.has(name)).sort()}function isAlreadyExists(error3){if(typeof error3==="object"&&error3!==null&&"code"in error3){let code=error3.code;if(typeof code==="string"&&ALREADY_EXISTS.has(code))return!0}return/already exists/i.test(errorMessage2(error3))}async function createMissingTables(options){let{run,tables:tables2,missing,schemaObject,logger:logger2,timeoutMs=60000}=options;if(missing.length===0)return{applied:0,errors:[]};let wanted=new Set(missing),imports={};for(let[key2,table]of Object.entries(tables2)){if(!table||typeof table!=="object")continue;let name=tableNameOf(table);if(name&&wanted.has(name))imports[key2]=table}if(schemaObject)imports.__nucleusSchema=schemaObject;let statements;try{let{generateDrizzleJson,generateMigration}=await import("drizzle-kit/api"),realExit=process.exit;try{process.exit=(code)=>{throw Error(`drizzle-kit called process.exit(${code??0}) while generating table DDL`)},statements=await withDeadline(generateMigration(generateDrizzleJson({}),generateDrizzleJson(imports)),timeoutMs,`generating CREATE TABLE statements did not finish within ${timeoutMs}ms`)}finally{process.exit=realExit}}catch(error3){let message=error3 instanceof Error?error3.message:String(error3);return logger2.error(`[Schema] CREATE TABLE statements could not be generated: ${message}`),{applied:0,errors:[message]}}let applied=0,errors2=[];for(let statement of statements)try{await run(statement),applied+=1}catch(error3){if(isAlreadyExists(error3))continue;let message=error3 instanceof Error?error3.message:String(error3);errors2.push(message),logger2.error(`[Schema] could not apply generated DDL: ${statement} \u2014 ${message}`)}return{applied,errors:errors2}}function describeRepair(plan,applied){let lines=[];if(applied>0)lines.push(`[Schema] The push applied nothing, so ${applied} missing column(s) were added directly. `+"This is additive only \u2014 nothing was dropped or altered.");if(plan.createdTables.length>0)lines.push(`[Schema] ${plan.createdTables.length} table(s) the push did not create were created directly: ${plan.createdTables.join(", ")}. Verified present in the database afterwards, not assumed from the statements that ran.`);if(plan.missingTables.length>0){if(lines.push(`[Schema] ${plan.missingTables.length} table(s) the code expects still do not exist: ${plan.missingTables.join(", ")}. Every read of these will fail. The additive repair tried `+"and could not create them \u2014 this needs a human."),plan.undeclaredTables.length>0)lines.push(`[Schema] The push is ambiguous because the database has ${plan.undeclaredTables.length} table(s) the model does not declare: ${plan.undeclaredTables.join(", ")}. drizzle-kit cannot tell a new table from a rename of one of these, and cannot ask without a TTY. Drop the stale one, or declare it, and the push stops aborting.`)}for(let item of plan.unsafe)lines.push(`[Schema] "${item.table}"."${item.column}" could not be added: ${item.why}. Give the column a default, or add it by hand with a backfill.`);return lines}function expectedFromTables(tables2){let out=[];for(let value2 of Object.values(tables2)){let table=asTable(value2);if(!table)continue;let columns;try{columns=getTableColumns2(table)}catch{continue}if(!columns)continue;let list2=Object.values(columns),name=tableNameOf(table);if(!name||list2.length===0)continue;out.push({name,columns:list2.map((column)=>({name:column.name,sqlType:typeof column.getSQLType==="function"?column.getSQLType():"text",notNull:column.notNull===!0,hasDefault:column.hasDefault===!0,defaultLiteral:renderDefaultLiteral(column.default)}))})}return out}function renderDefaultLiteral(value2){if(typeof value2==="string")return`'${value2.replace(/'/g,"''")}'`;if(typeof value2==="number")return Number.isFinite(value2)?String(value2):void 0;if(typeof value2==="boolean")return value2?"true":"false";return}function tableNameOf(table){for(let key2 of Object.getOwnPropertySymbols(table))if(String(key2).includes("Name")&&!String(key2).includes("Schema")){let value2=Reflect.get(table,key2);if(typeof value2==="string"&&value2.length>0)return value2}return null}async function readActualSchema(execute2,schema3){return(await readActualSchemaDetailed(execute2,schema3)).columns}async function readActualSchemaDetailed(execute2,schema3){let result=await execute2(`select table_name, column_name, column_default from information_schema.columns where table_schema = '${schema3.replace(/'/g,"''")}'`),rows=Array.isArray(result)?result:result.rows??[],columns={},withDefault={};for(let source of rows){let row=rowOf(source),tableName=asText(row.table_name),columnName=asText(row.column_name);if(!tableName||!columnName)continue;if(columns[tableName]??=new Set,columns[tableName]?.add(columnName),withDefault[tableName]??=new Set,row.column_default!==null&&row.column_default!==void 0)withDefault[tableName]?.add(columnName)}return{columns,withDefault}}async function reconcileMissingColumns(options){let{db,schema:schema3,tables:tables2,logger:logger2,schemaObject}=options,run=(statement)=>db.execute(sql10.raw(statement));try{let expected=expectedFromTables(tables2);if(expected.length===0)return null;let{columns:actual,withDefault}=await readActualSchemaDetailed(run,schema3),drift=findDrift(expected,actual,withDefault),plan=planRepair(schema3,drift);if(plan.undeclaredTables=undeclaredTables(expected,actual),drift.missingTables.length>0){await createMissingTables({run,tables:tables2,missing:drift.missingTables,schemaObject,logger:logger2});let after=await readActualSchema(run,schema3);plan.createdTables=drift.missingTables.filter((name)=>after[name]),plan.missingTables=drift.missingTables.filter((name)=>!after[name])}let applied=0;for(let statement of plan.statements)try{await run(statement),applied+=1}catch(error3){logger2.error(`[Schema] could not add a missing column: ${statement} \u2014 ${error3 instanceof Error?error3.message:String(error3)}`)}for(let line of describeRepair(plan,applied))if(plan.missingTables.length>0||plan.unsafe.length>0)logger2.error(line);else logger2.info(line);return{applied,plan}}catch(error3){return logger2.error(`[Schema] the additive repair could not run: ${error3 instanceof Error?error3.message:String(error3)}`),null}}var ALREADY_EXISTS;var init_schemaReconcile=__esm(()=>{ALREADY_EXISTS=new Set(["42P06","42P07","42710","42723","23505"])});var ambiguousColumnTables=(expected,actual)=>{let found=[];for(let table of expected){let have=actual[table.name];if(!have)continue;let declared=new Set(table.columns.map((column)=>column.name)),added=table.columns.filter((column)=>!have.has(column.name)).map((c)=>c.name),extra=[...have].filter((name)=>!declared.has(name));if(added.length>0&&extra.length>0)found.push({table:table.name,added,extra})}return found};var trapDepth=0,realExit=null,withExitTrapped=async(work)=>{if(trapDepth===0)realExit=process.exit,process.exit=(code)=>{throw Error(`drizzle-kit called process.exit(${code??0}) during the schema push`)};trapDepth+=1;try{return await work()}finally{if(trapDepth-=1,trapDepth===0&&realExit)process.exit=realExit,realExit=null}};import{drizzle as drizzle3}from"drizzle-orm/node-postgres";import{Pool}from"pg";async function withPushDb(db,schemaName,logger2,work,openPool=(config)=>new Pool(config)){let config=pushPoolConfig(db);if(!config)return logger2.warn(`[Schema] ${schemaName}: the connection settings of the database handle cannot be read; the push uses the host pool and its connection timeout.`),work(db,!1);let pool=openPool(config);pool.on("error",(error3)=>{logger2.warn(`[Schema] ${schemaName}: push pool connection error \u2014 ${reasonOf(error3)}`)});try{return await work(drizzle3(pool),!0)}finally{await pool.end().catch((error3)=>{logger2.warn(`[Schema] ${schemaName}: push pool did not close cleanly \u2014 ${reasonOf(error3)}`)})}}var PUSH_POOL_MAX=4,pushPoolConfig=(db)=>{let client=Reflect.get(db,"$client");if(!(client instanceof Pool))return null;let{options}=client;if(!options.connectionString&&!options.host&&!options.database)return null;return{...options,connectionTimeoutMillis:0,max:PUSH_POOL_MAX}};var init_pushPool=__esm(()=>{init_schema3()});import{sql as sql11}from"drizzle-orm";import{PgDialect}from"drizzle-orm/pg-core";function keyOrderedIntrospection(db){let dialect=new PgDialect;return Object.create(db,{execute:{value:async(query)=>{let result=await db.execute(query),text4=dialect.sqlToQuery(query).sql,target=TABLE_OF_QUERY.exec(text4);if(!target||!text4.includes("constraint_column_usage"))return result;let keys=await uniqueKeyOrder(db,unquote(target[2]??""),unquote(target[1]??""));return{...result,rows:reordered(rowsOf2(result),keys)}}}})}var TABLE_OF_QUERY,unquote=(value2)=>value2.replace(/''/g,"'"),rowsOf2=(result)=>("rows"in result)&&Array.isArray(result.rows)?result.rows:[],uniqueKeyOrder=async(db,schemaName,tableName)=>{let result=await db.execute(sql11`select c.conname as name, a.attname as col
|
|
122
|
+
`,hashIdentity=(identity)=>createHash3("sha256").update(identity.trim().toLowerCase()).digest("base64url").slice(0,16),RateLimiterBackendError,DEFAULT_AUTH_LOGIN,DEFAULT_AUTH_REGISTER,DEFAULT_AUTH_PASSWORD_RESET,DEFAULT_AUTH_PASSWORD_RESET_CONFIRM,DEFAULT_AUTH_MAGIC_LINK,DEFAULT_CONFIG4;var init_RateLimiter=__esm(()=>{RateLimiterBackendError=class RateLimiterBackendError extends Error{constructor(message){super(message);this.name="RateLimiterBackendError"}};DEFAULT_AUTH_LOGIN={window:"15m",max:5,perAddressMax:100,blockDuration:"30m"},DEFAULT_AUTH_REGISTER={window:"1h",max:3,perAddressMax:30,blockDuration:"1h"},DEFAULT_AUTH_PASSWORD_RESET={window:"1h",max:3,perAddressMax:30,blockDuration:"1h"},DEFAULT_AUTH_PASSWORD_RESET_CONFIRM={window:"1h",max:10,perAddressMax:30,blockDuration:"15m"},DEFAULT_AUTH_MAGIC_LINK={window:"1h",max:5,perAddressMax:30,blockDuration:"1h"},DEFAULT_CONFIG4={enabled:!0,strategy:"sliding-window",keyPrefix:"rl:",authRoutes:{window:"1m",max:10,login:DEFAULT_AUTH_LOGIN,register:DEFAULT_AUTH_REGISTER,passwordReset:DEFAULT_AUTH_PASSWORD_RESET,passwordResetConfirm:DEFAULT_AUTH_PASSWORD_RESET_CONFIRM,magicLink:DEFAULT_AUTH_MAGIC_LINK},publicRoutes:{window:"1m",max:3000},privateRoutes:{window:"1m",max:3000},byIp:!0,byUserId:!0,byEndpoint:!1,skipSuccessfulRequests:!1,headers:{remaining:"X-RateLimit-Remaining",reset:"X-RateLimit-Reset",limit:"X-RateLimit-Limit"},whitelist:[],blacklist:[]}});import{createCipheriv as createCipheriv2,createDecipheriv as createDecipheriv2,randomBytes as randomBytes3,scryptSync as scryptSync2,timingSafeEqual as timingSafeEqual2}from"crypto";var VERSION="v1",IV_LEN2=12,KEY_LEN=32,SCRYPT_SALT="nucleus-secrets-v1",keyCache,deriveKey2=(masterKey)=>{let cached=keyCache.get(masterKey);if(cached)return cached;let key2=scryptSync2(masterKey,SCRYPT_SALT,KEY_LEN);return keyCache.set(masterKey,key2),key2},encryptSecret=(plaintext,masterKey)=>{if(!masterKey)throw Error("secrets encryption key is empty");let iv=randomBytes3(IV_LEN2),cipher=createCipheriv2("aes-256-gcm",deriveKey2(masterKey),iv),ciphertext=Buffer.concat([cipher.update(plaintext,"utf-8"),cipher.final()]),tag=cipher.getAuthTag();return[VERSION,iv.toString("base64"),tag.toString("base64"),ciphertext.toString("base64")].join(":")},decryptSecret=(envelope,masterKey)=>{if(!masterKey)throw Error("secrets encryption key is empty");let[version,ivB64,tagB64,ctB64,...extra]=envelope.split(":");if(version!==VERSION||ivB64===void 0||tagB64===void 0||ctB64===void 0||extra.length>0)throw Error("not an encrypted secret envelope");let decipher=createDecipheriv2("aes-256-gcm",deriveKey2(masterKey),Buffer.from(ivB64,"base64"));return decipher.setAuthTag(Buffer.from(tagB64,"base64")),Buffer.concat([decipher.update(Buffer.from(ctB64,"base64")),decipher.final()]).toString("utf-8")},previewOf=(plaintext)=>{let len=plaintext.length;if(len===0)return"";if(len<12)return`\u2022\u2022\u2022\u2022${len}`;return`\u2022\u2022\u2022\u2022${plaintext.slice(-4)}`};var init_crypto=__esm(()=>{keyCache=new Map});function discoverSlots(source){let config=isPlainObject(source)?source:{},slots=new Map,add=(slot)=>{let id=`${slot.scope}.${slot.key}`;if(!slots.has(id))slots.set(id,slot)},valueAt=(scope,key2)=>{let node=config;for(let segment of scope.split(".")){if(!isPlainObject(node))return;node=node[segment]}if(!isPlainObject(node))return;let value2=node[key2];if(typeof value2==="string")return value2;if(Array.isArray(value2)&&value2.every((entry)=>typeof entry==="string"))return value2.length>0?value2.join(","):void 0;return};for(let descriptor of SECRET_SLOT_DESCRIPTORS)for(let scope of expandPath(config,descriptor.path,descriptor.always===!0)){let leaf=scope.split(".").pop()??descriptor.group,group=descriptor.path.endsWith("*")?`${descriptor.group}:${leaf}`:descriptor.group;for(let declared of descriptor.keys)add({scope,key:declared.key,kind:declared.kind??kindFor(declared.key),label:declared.label,group,required:declared.required??!1,requiredWhen:declared.requiredWhen,hint:declared.hint,secret:declared.secret??descriptor.secret??!0,configValue:valueAt(scope,declared.key)})}let walk=(node,path,depth)=>{if(depth>6)return;for(let[key2,value2]of Object.entries(node)){if(SKIP_SECTIONS.has(key2))continue;let childPath=path?`${path}.${key2}`:key2;if(isPlainObject(value2)){walk(value2,childPath,depth+1);continue}if(typeof value2!=="string"&&value2!==void 0&&value2!==null)continue;if(!CREDENTIAL_KEY_PATTERN.test(key2))continue;if(NOT_A_CREDENTIAL.has(key2.toLowerCase()))continue;if(BOOT_ONLY_PATHS.has(`${path}.${key2}`))continue;let owner=path.split(".").pop(),label=owner&&owner.toLowerCase()!==key2.toLowerCase()?`${humanize(owner)} \u2014 ${humanize(key2)}`:humanize(key2);add({scope:path,key:key2,kind:kindFor(key2),label,group:path.split(".")[0]??"other",required:!1,secret:!0,configValue:typeof value2==="string"?value2:void 0})}};return walk(config,"",0),[...slots.values()].sort((a,b)=>a.group.localeCompare(b.group)||a.scope.localeCompare(b.scope)||a.key.localeCompare(b.key))}var CREDENTIAL_KEY_PATTERN,NOT_A_CREDENTIAL,BOOT_ONLY_PATHS,SKIP_SECTIONS,kindFor=(key2)=>{let k=key2.toLowerCase();if(k.includes("json"))return"json";if(k.includes("connection"))return"connection_string";if(k.includes("privatekey")||k.includes("private_key"))return"pem";if(k.includes("clientid")||k.includes("client_id"))return"text";return"password"},humanize=(key2)=>key2.replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/\b\w/g,(c)=>c.toUpperCase()),SECRET_SLOT_DESCRIPTORS,isPlainObject=(value2)=>typeof value2==="object"&&value2!==null&&!Array.isArray(value2),expandPath=(config,path,always=!1)=>{let segments=path.split("."),scopes2=[{path:"",node:config}];for(let segment of segments){let next=[];for(let current of scopes2){if(!isPlainObject(current.node))continue;if(segment==="*")for(let[childKey,childValue]of Object.entries(current.node))next.push({path:current.path?`${current.path}.${childKey}`:childKey,node:childValue});else if(segment in current.node)next.push({path:current.path?`${current.path}.${segment}`:segment,node:current.node[segment]});else if(always)next.push({path:current.path?`${current.path}.${segment}`:segment,node:{}})}scopes2=next}return scopes2.filter((s)=>isPlainObject(s.node)).map((s)=>s.path)},looksLikeEnvName=(value2)=>!!value2&&/^[A-Z][A-Z0-9_]{2,}$/.test(value2);var init_registry2=__esm(()=>{CREDENTIAL_KEY_PATTERN=/(secret|password|passwd|apikey|api_key|accesskey|access_key|privatekey|private_key|token|credential|connection_string|connectionstring|clientid|client_id|encryptionkey|encryption_key|servicekey|service_key|json_file_path|jsonfilepath)$/i,NOT_A_CREDENTIAL=new Set(["preventapikeymanagement","allowapplicationkeys","maxkeysperuser","tokenurl","accesstoken","refreshtoken","sessiontoken"]),BOOT_ONLY_PATHS=new Set(["authorization.godminPassword","authorization.godminEmail","authentication.accessToken.secret","authentication.refreshToken.secret","authentication.sessionToken.secret","backup.encryptionKey","notification.channels.telegram.botToken","notification.channels.webhook.headers","domains.cloudflare.apiToken"]),SKIP_SECTIONS=new Set(["entities","systemTables","system_tables","tables","columns","indexes","routes","cors","swagger","secrets"]),SECRET_SLOT_DESCRIPTORS=[{path:"authentication.oauth.providers.*",group:"oauth",label:"OAuth / SSO",keys:[{key:"clientId",kind:"text",label:"Client ID",required:!0},{key:"clientSecret",kind:"password",label:"Client Secret",required:!0},{key:"tenantId",kind:"text",label:"Tenant ID"},{key:"redirectUri",kind:"text",secret:!1,required:!0,label:"Reply URL (Redirect URI)",hint:"The return address registered with the provider. It must be written identically on the provider side too (e.g. Entra > Authentication > Redirect URIs)."}]},{always:!0,path:"email.gmail",group:"email",label:"Gmail (service account)",keys:[{key:"service_account_json",kind:"json",label:"Service Account JSON",required:!0,requiredWhen:"enabled"}]},{always:!0,path:"email.azure",group:"email",label:"Azure Communication Services",keys:[{key:"connection_string",kind:"connection_string",label:"Connection String",required:!0,requiredWhen:"enabled"}]},{always:!0,path:"email.smtp",group:"email",label:"SMTP (Microsoft 365, Exchange, corporate mail)",keys:[{key:"enabled",kind:"boolean",secret:!1,label:"Send through this provider",hint:"The provider that is switched on carries the mail. If the panel cannot read this flag, the card stays \u201CNot set\u201D even when the details are filled in."},{key:"host",kind:"text",secret:!1,label:"Server",required:!0,requiredWhen:"enabled",hint:"smtp.office365.com for Microsoft 365"},{key:"port",kind:"text",secret:!1,label:"Port",hint:"Left empty this is 587 (STARTTLS). 465 means implicit TLS."},{key:"user",kind:"text",secret:!1,label:"Mailbox",required:!0,requiredWhen:"enabled",hint:"The address the password belongs to. It is also the sender address."},{key:"password",kind:"password",label:"Password / app password",required:!0,requiredWhen:"enabled",hint:"If the account has multi-factor authentication, the app password Microsoft generated. In Exchange Online, SMTP AUTH is off per tenant by default and a correct password is refused too \u2014 ask IT to turn it on for that mailbox."},{key:"sender_address",kind:"text",secret:!1,label:"Sender address (optional)",hint:"Left empty, the mailbox itself is used. If you enter a different address, Exchange requires that mailbox to have been granted \u201CSend As\u201D for it; without that the send is refused."},{key:"from_name",kind:"text",secret:!1,label:"Display name",hint:"The name the recipient reads in their inbox, e.g. the name of the portal."}]},{always:!0,path:"service",group:"service",label:"The server\u2019s own key",keys:[{key:"api_key",kind:"password",label:"Service API key",hint:"Some work the server has to do in its OWN name \u2014 counting how many people answered a survey, for instance. That cannot be done with an employee\u2019s permissions, and should not be. Generate the key in the admin panel and paste it here; it carries its owner\u2019s roles, not godmin\u2019s. Left empty, this work is skipped silently."}]},{always:!0,path:"storage.smb",group:"storage",label:"SMB / CIFS share",keys:[{key:"username",kind:"text",label:"Username",required:!0},{key:"password",kind:"password",label:"Password",required:!0}]},{secret:!1,always:!0,path:"storage",group:"storage",label:"File store",keys:[{key:"provider",kind:"text",label:"Storage kind",hint:"local (the server\u2019s own disk) or smb (a corporate file server). The change takes effect immediately."}]},{secret:!1,always:!0,path:"storage.smb",group:"storage",label:"SMB / CIFS share",keys:[{key:"url",kind:"text",label:"Share address",hint:"Paste it exactly as the customer sent it: smb://server/share \u2014 the server and the share name are read from this."},{key:"domain",kind:"text",label:"Domain",hint:"The domain part when the user is written as DOMAIN\\user. Leave empty if it is not needed."},{key:"base_path",kind:"text",label:"Folder inside the share",hint:"The subfolder uploads are gathered in. Empty means the root of the share."}]},{path:"payment.providers.*",group:"payment",label:"Payment provider",keys:[{key:"apiKey",kind:"password",label:"API Key",required:!0},{key:"secretKey",kind:"password",label:"Secret Key",required:!0},{key:"webhookSecret",kind:"password",label:"Webhook Secret"}]},{path:"captcha",group:"captcha",label:"Captcha",keys:[{key:"secretKey",kind:"password",label:"Secret Key"}]},{secret:!1,path:"authentication",group:"portal",label:"Portal address",keys:[{key:"trustedAppOrigins",kind:"list",label:"Trusted origins",required:!0,hint:"The address(es) the portal is installed at. Password-reset and SSO return links are built from these. Wildcard: *.company.com"}]},{secret:!1,always:!0,path:"email",group:"email",label:"Email provider",keys:[{key:"provider",kind:"text",label:"Provider to use",hint:"azure or gmail. Left empty, whichever provider is switched on is used."}]},{secret:!1,always:!0,path:"email.azure",group:"email",label:"Azure Communication Services",keys:[{key:"enabled",kind:"boolean",label:"Azure email enabled",hint:"Entering the connection string is not enough on its own \u2014 sending is turned on by this switch."},{key:"sender_address",kind:"text",label:"Sender address"},{key:"from_name",kind:"text",label:"Sender name",hint:"The name the recipient sees in their inbox in place of the address. Empty means the address shows."}]},{secret:!1,always:!0,path:"email.gmail",group:"email",label:"Gmail (service account)",keys:[{key:"enabled",kind:"boolean",label:"Gmail email enabled"},{key:"from_email",kind:"text",label:"Sender address"},{key:"from_name",kind:"text",label:"Sender name",hint:"The name the recipient sees in their inbox in place of the address. Empty means the address shows."}]}]});import{and as and12,eq as eq17}from"drizzle-orm";class SecretsStore{db;resolveTable;masterKey;constructor(deps){this.db=deps.db,this.resolveTable=deps.resolveTable,this.masterKey=deps.masterKey}table(schemaName){return this.resolveTable(SECRETS_TABLE,schemaName)}async loadAll(schemaName){let values=new Map,failed2=[],table=this.table(schemaName);if(!table)return{values,failed:failed2,tableMissing:!0};let rows;try{rows=(await this.db.select().from(table).where(eq17(col(table,"isActive"),!0))).map(secretRowOf)}catch(error3){if(isMissingTableError(error3))return{values,failed:failed2,tableMissing:!0};throw error3}for(let row of rows)try{values.set(cacheKeyOf(row.scope,row.key),decryptSecret(row.valueEnc,this.masterKey))}catch{failed2.push(`${row.scope}.${row.key}`)}return{values,failed:failed2}}async list(schemaName){let table=this.table(schemaName);if(!table)return[];try{return(await this.db.select().from(table)).map(secretRowOf).filter((r)=>r.isActive!==!1).map(rowToMeta)}catch(error3){if(isMissingTableError(error3))return[];throw error3}}async get(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return null;let row=(await this.db.select().from(table).where(and12(eq17(col(table,"scope"),scope),eq17(col(table,"key"),key2))).limit(1))[0];return row?secretRowOf(row):null}async set(params,schemaName){let table=this.table(schemaName);if(!table)return null;let existing=await this.get(params.scope,params.key,schemaName),valueEnc=encryptSecret(params.value,this.masterKey),preview=previewOf(params.value),now=new Date;if(existing)await this.db.update(table).set({valueEnc,previousEnc:existing.valueEnc,preview,kind:params.kind??existing.kind??"text",description:params.description??existing.description,version:(existing.version??1)+1,rotatedAt:now,isActive:!0,updatedAt:now,updatedBy:params.actorId??null}).where(eq17(col(table,"id"),existing.id));else await this.db.insert(table).values({scope:params.scope,key:params.key,valueEnc,preview,kind:params.kind??"text",description:params.description??null,version:1,isActive:!0,createdBy:params.actorId??null,updatedBy:params.actorId??null});let saved=await this.get(params.scope,params.key,schemaName);return saved?rowToMeta(saved):null}async rollback(scope,key2,actorId,schemaName){let table=this.table(schemaName);if(!table)return null;let existing=await this.get(scope,key2,schemaName);if(!existing?.previousEnc)return null;let plaintext=decryptSecret(existing.previousEnc,this.masterKey),now=new Date;await this.db.update(table).set({valueEnc:existing.previousEnc,previousEnc:existing.valueEnc,preview:previewOf(plaintext),version:(existing.version??1)+1,rotatedAt:now,updatedAt:now,updatedBy:actorId??null}).where(eq17(col(table,"id"),existing.id));let saved=await this.get(scope,key2,schemaName);return saved?rowToMeta(saved):null}async remove(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return!1;let existing=await this.get(scope,key2,schemaName);if(!existing)return!1;return await this.db.delete(table).where(eq17(col(table,"id"),existing.id)),!0}async touch(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return;await this.db.update(table).set({lastUsedAt:new Date}).where(and12(eq17(col(table,"scope"),scope),eq17(col(table,"key"),key2)))}async reencryptAll(newMasterKey,schemaName){let table=this.table(schemaName);if(!table)return{migrated:0,failed:[]};let rows=(await this.db.select().from(table)).map(secretRowOf),failed2=[],planned=[];for(let row of rows)try{let plaintext=decryptSecret(row.valueEnc,this.masterKey),previous=row.previousEnc?encryptSecret(decryptSecret(row.previousEnc,this.masterKey),newMasterKey):null;planned.push({id:row.id,valueEnc:encryptSecret(plaintext,newMasterKey),previousEnc:previous})}catch{failed2.push(`${row.scope}.${row.key}`)}if(failed2.length>0)return{migrated:0,failed:failed2};return await this.db.transaction(async(tx)=>{for(let row of planned)await tx.update(table).set({valueEnc:row.valueEnc,previousEnc:row.previousEnc}).where(eq17(col(table,"id"),row.id))}),this.masterKey=newMasterKey,{migrated:planned.length,failed:failed2}}}var SECRETS_TABLE="nucleusSecrets",col,SECRET_KINDS,isSecretKind=(value2)=>Object.hasOwn(SECRET_KINDS,value2),secretRowOf=(source)=>{let row=rowOf(source);return{id:asText(row.id)??"",scope:asText(row.scope)??"",key:asText(row.key)??"",valueEnc:asText(row.valueEnc)??"",previousEnc:asText(row.previousEnc)??null,preview:asText(row.preview)??null,kind:asText(row.kind)??null,description:asText(row.description)??null,version:asNumber(row.version)??1,rotatedAt:asDate(row.rotatedAt)??null,lastUsedAt:asDate(row.lastUsedAt)??null,updatedAt:asDate(row.updatedAt)??null,updatedBy:asText(row.updatedBy)??null,isActive:asBoolean(row.isActive)??null}},toIso=(value2)=>value2?new Date(value2).toISOString():null,UNDEFINED_TABLE="42P01",isMissingTableError=(error3)=>{let seen=new Set,current=typeof error3==="object"&&error3!==null?error3:void 0;while(current&&!seen.has(current)){if(seen.add(current),fieldOf(current,"code")===UNDEFINED_TABLE)return!0;let message=fieldOf(current,"message");if(typeof message==="string"&&/relation .* does not exist/i.test(message))return!0;let cause=fieldOf(current,"cause");current=typeof cause==="object"&&cause!==null?cause:void 0}return!1},rowToMeta=(row)=>({id:row.id,scope:row.scope,key:row.key,kind:row.kind!==null&&isSecretKind(row.kind)?row.kind:"text",preview:row.preview??"",description:row.description,version:row.version??1,canRollback:!!row.previousEnc,rotatedAt:toIso(row.rotatedAt),lastUsedAt:toIso(row.lastUsedAt),updatedAt:toIso(row.updatedAt),updatedBy:row.updatedBy}),cacheKeyOf=(scope,key2)=>`${scope}.${key2}`;var init_store3=__esm(()=>{init_crypto();col=columnOf,SECRET_KINDS={text:!0,password:!0,json:!0,connection_string:!0,pem:!0,boolean:!0,list:!0}});class SecretsService{store;logger;getRedis;refreshIntervalMs;schemaName;cache=new Map;timer=null;localRevision=0;loaded=!1;tableMissing=!1;warnedTableMissing=!1;constructor(deps){this.store=deps.store,this.logger=deps.logger,this.getRedis=deps.getRedis,this.refreshIntervalMs=deps.refreshIntervalMs??DEFAULT_REFRESH_MS,this.schemaName=deps.schemaName}async start(){if(await this.refresh(),this.timer)return;let timer=setInterval(()=>{this.refreshIfStale()},this.refreshIntervalMs);timer.unref?.(),this.timer=timer}stop(){if(this.timer)clearInterval(this.timer);this.timer=null}isReady(){return this.loaded}size(){return this.cache.size}isTableMissing(){return this.tableMissing}async refresh(){try{let{values,failed:failed2,tableMissing}=await this.store.loadAll(this.schemaName);if(tableMissing){if(this.tableMissing=!0,!this.warnedTableMissing)this.warnedTableMissing=!0,this.logger.warn("[Secrets] nucleus_secrets does not exist yet \u2014 env and literal values resolve normally; "+"the store activates automatically once the schema sync creates it");return}if(this.tableMissing)this.tableMissing=!1,this.warnedTableMissing=!1,this.logger.info("[Secrets] nucleus_secrets is now available \u2014 credential store active");if(this.cache=values,this.loaded=!0,failed2.length>0)this.logger.error("[Secrets] Credentials failed to decrypt and were skipped",{slots:failed2,hint:"master key changed without re-encrypting \u2014 POST /secrets/reencrypt with the old key"})}catch(error3){this.logger.warn("[Secrets] Refresh failed, keeping cached values",{error:error3 instanceof Error?error3.message:String(error3)})}}async refreshIfStale(){let redis=this.getRedis?.();if(!redis)return this.refresh();try{let result=await redis.read(REVISION_KEY),remote=Number(result.data??0);if(Number.isFinite(remote)&&remote===this.localRevision&&this.loaded)return;await this.refresh(),this.localRevision=Number.isFinite(remote)?remote:this.localRevision}catch{await this.refresh()}}async bumpRevision(){let redis=this.getRedis?.();if(!redis)return;try{let next=Date.now();this.localRevision=next,await redis.create(REVISION_KEY,next)}catch{}}get(scope,key2){return this.cache.get(cacheKeyOf(scope,key2))}has(scope,key2){return this.cache.has(cacheKeyOf(scope,key2))}resolve(scope,key2,configValue){let fromDb=this.cache.get(cacheKeyOf(scope,key2));if(fromDb)return{value:fromDb,source:"db"};if(configValue){let fromEnv=process.env[configValue];if(fromEnv)return{value:fromEnv,source:"env"};if(looksLikeEnvName(configValue))return{value:void 0,source:"missing"};return{value:configValue,source:"literal"}}return{value:void 0,source:"missing"}}value(scope,key2,configValue){return this.resolve(scope,key2,configValue).value}listValue(scope,key2,configValue){let fallback=Array.isArray(configValue)?configValue.join(","):configValue,raw=this.value(scope,key2,fallback);if(!raw)return Array.isArray(configValue)?configValue:[];return raw.split(/[,;\n\r]+/).map((entry)=>entry.trim()).filter(Boolean)}flag(scope,key2,configValue){let raw=this.get(scope,key2);if(raw===void 0)return configValue===!0;return raw==="true"||raw==="1"}liveConfig(scope,node,keys){let live={...node};for(let key2 of keys){let declared=fieldOf(node,key2),configValue=typeof declared==="string"?declared:void 0;Object.defineProperty(live,key2,{get:()=>this.resolve(scope,key2,configValue).value,enumerable:!0,configurable:!0})}return live}async describe(config,slots){let discovered=slots??discoverSlots(config),stored=await this.store.list(this.schemaName),byId=new Map(stored.map((s)=>[cacheKeyOf(s.scope,s.key),s]));return discovered.map((slot)=>{let id=cacheKeyOf(slot.scope,slot.key),record3=byId.get(id),{value:value2,source}=this.resolve(slot.scope,slot.key,slot.configValue),envName=looksLikeEnvName(slot.configValue)?slot.configValue:void 0,gate=slot.requiredWhen?this.flag(slot.scope,slot.requiredWhen,configFlagAt(config,slot.scope,slot.requiredWhen)):!0;return{...slot,required:slot.required&&gate,configValue:envName,source,value:slot.secret?void 0:value2,preview:slot.secret?source==="db"&&record3?record3.preview:value2?previewOf(value2):"":value2??"",envName,version:record3?.version,rotatedAt:record3?.rotatedAt??null,canRollback:record3?.canRollback??!1}})}async list(){return this.store.list(this.schemaName)}async set(params){let saved=await this.store.set(params,this.schemaName);return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential stored",{scope:params.scope,key:params.key,version:saved?.version,actor:params.actorId}),saved}async rollback(scope,key2,actorId){let saved=await this.store.rollback(scope,key2,actorId,this.schemaName);if(!saved)return null;return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential rolled back",{scope,key:key2,actor:actorId}),saved}async remove(scope,key2,actorId){if(!await this.store.remove(scope,key2,this.schemaName))return!1;return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential removed",{scope,key:key2,actor:actorId}),!0}async reencryptAll(newMasterKey){let result=await this.store.reencryptAll(newMasterKey,this.schemaName);return await this.refresh(),await this.bumpRevision(),result}}var REVISION_KEY="nucleus:secrets:revision",DEFAULT_REFRESH_MS=30000,configFlagAt=(config,scope,key2)=>{let node=config;for(let segment of scope.split(".")){if(typeof node!=="object"||node===null)return;node=fieldOf(node,segment)}if(typeof node!=="object"||node===null)return;let value2=fieldOf(node,key2);if(typeof value2==="boolean")return value2;if(typeof value2==="string")return value2==="true"||value2==="1";return};var init_SecretsService=__esm(()=>{init_crypto();init_registry2();init_store3()});var resolveMasterKey=(configured)=>{if(configured){let fromEnv=process.env[configured];if(fromEnv)return fromEnv;if(!/^[A-Z][A-Z0-9_]{2,}$/.test(configured))return configured}return process.env.NUCLEUS_SECRETS_KEY||void 0};var init_Secrets=__esm(()=>{init_crypto();init_registry2();init_SecretsService();init_store3()});var rowToTenantRecord=(source)=>{let row=rowOf(source);return{id:String(row.id||""),subdomain:String(row.subdomain||""),schemaName:String(row.schemaName||row.schema_name||""),companyId:String(row.companyId||row.company_id||""),companyName:row.companyName!=null?String(row.companyName):row.company_name!=null?String(row.company_name):null,godAdminEmail:String(row.godAdminEmail||row.god_admin_email||""),status:parseStatus(row.status),plan:row.plan!=null?String(row.plan):null,domain:row.domain!=null?String(row.domain):null,settings:parseJsonbToConfig(row.settings),trustedSources:parseTrustedSources(row.trustedSources||row.trusted_sources),maxUsers:row.maxUsers!=null?Number(row.maxUsers):row.max_users!=null?Number(row.max_users):null,provisionedAt:row.provisionedAt!=null?String(row.provisionedAt):row.provisioned_at!=null?String(row.provisioned_at):null,suspendedAt:row.suspendedAt!=null?String(row.suspendedAt):row.suspended_at!=null?String(row.suspended_at):null,suspendedReason:row.suspendedReason!=null?String(row.suspendedReason):row.suspended_reason!=null?String(row.suspended_reason):null}},rowToFeatureRecord=(source,parseConfig)=>{let row=rowOf(source);return{id:String(row.id||""),tenantId:String(row.tenantId||row.tenant_id||""),featureName:String(row.featureName||row.feature_name||""),enabled:Boolean(row.enabled),featureConfig:parseConfig(row.config)}},parseStatus=(value2)=>{let valid=["provisioning","active","suspended","archived"],str2=String(value2||"provisioning");return valid.find((status)=>status===str2)??"provisioning"},parseJsonbToConfig=(value2)=>{if(!value2||typeof value2!=="object")return{};let result={};for(let[k,v]of Object.entries(rowOf(value2)))if(typeof v==="string"||typeof v==="number"||typeof v==="boolean")result[k]=v;return result},parseTrustedSources=(value2)=>{if(!Array.isArray(value2))return[];return value2.map((item)=>{let entry=typeof item==="object"&&item!==null?rowOf(item):{};return{allowHeaderAuth:entry.allowHeaderAuth===!0||entry.allow_header_auth===!0,allowedIps:textEntries(entry.allowedIps||entry.allowed_ips),allowedServices:textEntries(entry.allowedServices||entry.allowed_services)}})},textEntries=(value2)=>Array.isArray(value2)?value2.filter((entry)=>typeof entry==="string"):void 0,normalizeHost=(host)=>{return((host||"").split(":")[0]||"").toLowerCase().replace(/\.$/,"")},extractSubdomain=(host)=>{let hostWithoutPort=host.split(":")[0]||"";if(hostWithoutPort==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(hostWithoutPort))return null;let parts=hostWithoutPort.split(".");if(parts.length<3)return null;let subdomain=parts[0]||"";if(!subdomain||subdomain==="www")return null;return subdomain},toIPv4Octets=(address)=>{let bare=address.startsWith("::ffff:")?address.slice(7):address;if(bare.includes(":"))return null;let parts=bare.split(".");if(parts.length!==4)return null;let[a,b,c,d]=parts.map((part)=>/^\d{1,3}$/.test(part)?Number(part):Number.NaN);if(a===void 0||b===void 0||c===void 0||d===void 0)return null;let octets=[a,b,c,d];return octets.every((o)=>Number.isInteger(o)&&o>=0&&o<=255)?octets:null},isIpInCidr=(ip,cidr)=>{let[cidrIp,prefixStr]=cidr.split("/");if(!cidrIp||!prefixStr)return!1;let prefix=Number.parseInt(prefixStr,10);if(Number.isNaN(prefix)||prefix<0||prefix>32)return!1;let ipParts=toIPv4Octets(ip),cidrParts=toIPv4Octets(cidrIp);if(!ipParts||!cidrParts)return!1;let toNumber=([a,b,c,d])=>(a<<24|b<<16|c<<8|d)>>>0,ipNum=toNumber(ipParts),cidrNum=toNumber(cidrParts),mask=prefix===0?0:~((1<<32-prefix)-1)>>>0;return(ipNum&mask)===(cidrNum&mask)},isTrustedSource=(tenant,request,authMode,fallbackSources,vettedClientIp)=>{let ownSources=tenant.trustedSources,trustedSources=Array.isArray(ownSources)&&ownSources.length>0?ownSources:fallbackSources;if(!trustedSources||!Array.isArray(trustedSources)||trustedSources.length===0)return!1;let clientIp=vettedClientIp?.trim()||"",serviceId=request.headers.get("x-service-id")||"";for(let source of trustedSources){if(!source.allowHeaderAuth)continue;if(source.allowedIps&&source.allowedIps.length>0){if(source.allowedIps.some((allowedIp)=>{if(allowedIp.includes("/"))return isIpInCidr(clientIp,allowedIp);return clientIp===allowedIp}))return!0}if(source.allowedServices&&source.allowedServices.length>0){if(source.allowedServices.includes(serviceId))return!0}}return!1},pickRequestHost=(request,hostHeader,hostHeaderTrusted)=>{if(hostHeader&&hostHeaderTrusted){let forwarded=request.headers.get(hostHeader)?.split(",")[0]?.trim();if(forwarded)return forwarded}return request.headers.get("host")||new URL(request.url).host||""};var init_helpers2=()=>{};import{pgSchema}from"drizzle-orm/pg-core";function createProvisionedSchemas(deps){let cache=new Map;return(schemaName)=>{let tenant=deps.tenantOf(schemaName);if(!tenant||!PROVISIONED_STATUSES.has(tenant.status))return;let cached=cache.get(schemaName);if(cached)return cached;let schema3=pgSchema(schemaName),built={tables:deps.createTables(schema3),relations:deps.createRelations?deps.createRelations(schema3):{}};return cache.set(schemaName,built),built}}function hostTablesResolver(mainSchema,mainTables,source){return(schemaName)=>{if(schemaName===mainSchema)return mainTables;return source()?.getProvisionedSchema(schemaName)?.tables}}function hostRelationsResolver(mainSchema,mainRelations,source){return(schemaName)=>{if(schemaName===mainSchema)return mainRelations;return source()?.getProvisionedSchema(schemaName)?.relations??{}}}var PROVISIONED_STATUSES;var init_provisionedSchemas=__esm(()=>{PROVISIONED_STATUSES=new Set(["provisioning","active","suspended","archived"])});async function withDeadline(promise3,timeoutMs,message){promise3.catch(()=>{});let timer,deadline=new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(Error(message)),timeoutMs)});try{return await Promise.race([promise3,deadline])}finally{if(timer)clearTimeout(timer)}}var exports_schemaReconcile={};__export(exports_schemaReconcile,{undeclaredTables:()=>undeclaredTables,setDefaultStatement:()=>setDefaultStatement,renderDefaultLiteral:()=>renderDefaultLiteral,reconcileMissingColumns:()=>reconcileMissingColumns,readActualSchemaDetailed:()=>readActualSchemaDetailed,readActualSchema:()=>readActualSchema,planRepair:()=>planRepair,findDrift:()=>findDrift,expectedFromTables:()=>expectedFromTables,describeRepair:()=>describeRepair,createMissingTables:()=>createMissingTables,addColumnStatement:()=>addColumnStatement});import{getTableColumns as getTableColumns2,sql as sql10}from"drizzle-orm";function findDrift(expected,actual,actualDefaults){let missingTables=[],missingColumns=[],columnsMissingDefault=[];for(let table of expected){let have=actual[table.name];if(!have){missingTables.push(table.name);continue}let haveDefault=actualDefaults?.[table.name];for(let column of table.columns){if(!have.has(column.name)){missingColumns.push({table:table.name,column});continue}if(haveDefault&&column.hasDefault&&column.defaultLiteral!==void 0&&!haveDefault.has(column.name))columnsMissingDefault.push({table:table.name,column})}}return{missingTables,missingColumns,columnsMissingDefault}}function addColumnStatement(schema3,table,column){if(column.notNull&&!column.hasDefault)return null;return[`alter table "${schema3}"."${table}"`,`add column if not exists "${column.name}" ${column.sqlType}`].join(" ")}function setDefaultStatement(schema3,table,column){if(column.defaultLiteral===void 0)return null;return`alter table "${schema3}"."${table}" alter column "${column.name}" set default ${column.defaultLiteral}`}function planRepair(schema3,drift){let statements=[],unsafe3=[];for(let{table,column}of drift.missingColumns){let statement=addColumnStatement(schema3,table,column);if(statement)statements.push(statement);else unsafe3.push({table,column:column.name,why:"declared NOT NULL with no default, and the table already has rows to fill"})}for(let{table,column}of drift.columnsMissingDefault){let statement=setDefaultStatement(schema3,table,column);if(statement)statements.push(statement)}return{statements,unsafe:unsafe3,missingTables:drift.missingTables,createdTables:[],undeclaredTables:[]}}function undeclaredTables(expected,actual){let declared=new Set(expected.map((t)=>t.name));return Object.keys(actual).filter((name)=>!declared.has(name)).sort()}function isAlreadyExists(error3){if(typeof error3==="object"&&error3!==null&&"code"in error3){let code=error3.code;if(typeof code==="string"&&ALREADY_EXISTS.has(code))return!0}return/already exists/i.test(errorMessage2(error3))}async function createMissingTables(options){let{run,tables:tables2,missing,schemaObject,logger:logger2,timeoutMs=60000}=options;if(missing.length===0)return{applied:0,errors:[]};let wanted=new Set(missing),imports={};for(let[key2,table]of Object.entries(tables2)){if(!table||typeof table!=="object")continue;let name=tableNameOf(table);if(name&&wanted.has(name))imports[key2]=table}if(schemaObject)imports.__nucleusSchema=schemaObject;let statements;try{let{generateDrizzleJson,generateMigration}=await import("drizzle-kit/api"),realExit=process.exit;try{process.exit=(code)=>{throw Error(`drizzle-kit called process.exit(${code??0}) while generating table DDL`)},statements=await withDeadline(generateMigration(generateDrizzleJson({}),generateDrizzleJson(imports)),timeoutMs,`generating CREATE TABLE statements did not finish within ${timeoutMs}ms`)}finally{process.exit=realExit}}catch(error3){let message=error3 instanceof Error?error3.message:String(error3);return logger2.error(`[Schema] CREATE TABLE statements could not be generated: ${message}`),{applied:0,errors:[message]}}let applied=0,errors2=[];for(let statement of statements)try{await run(statement),applied+=1}catch(error3){if(isAlreadyExists(error3))continue;let message=error3 instanceof Error?error3.message:String(error3);errors2.push(message),logger2.error(`[Schema] could not apply generated DDL: ${statement} \u2014 ${message}`)}return{applied,errors:errors2}}function describeRepair(plan,applied){let lines=[];if(applied>0)lines.push(`[Schema] The push applied nothing, so ${applied} missing column(s) were added directly. `+"This is additive only \u2014 nothing was dropped or altered.");if(plan.createdTables.length>0)lines.push(`[Schema] ${plan.createdTables.length} table(s) the push did not create were created directly: ${plan.createdTables.join(", ")}. Verified present in the database afterwards, not assumed from the statements that ran.`);if(plan.missingTables.length>0){if(lines.push(`[Schema] ${plan.missingTables.length} table(s) the code expects still do not exist: ${plan.missingTables.join(", ")}. Every read of these will fail. The additive repair tried `+"and could not create them \u2014 this needs a human."),plan.undeclaredTables.length>0)lines.push(`[Schema] The push is ambiguous because the database has ${plan.undeclaredTables.length} table(s) the model does not declare: ${plan.undeclaredTables.join(", ")}. drizzle-kit cannot tell a new table from a rename of one of these, and cannot ask without a TTY. Drop the stale one, or declare it, and the push stops aborting.`)}for(let item of plan.unsafe)lines.push(`[Schema] "${item.table}"."${item.column}" could not be added: ${item.why}. Give the column a default, or add it by hand with a backfill.`);return lines}function expectedFromTables(tables2){let out=[];for(let value2 of Object.values(tables2)){let table=asTable(value2);if(!table)continue;let columns;try{columns=getTableColumns2(table)}catch{continue}if(!columns)continue;let list2=Object.values(columns),name=tableNameOf(table);if(!name||list2.length===0)continue;out.push({name,columns:list2.map((column)=>({name:column.name,sqlType:typeof column.getSQLType==="function"?column.getSQLType():"text",notNull:column.notNull===!0,hasDefault:column.hasDefault===!0,defaultLiteral:renderDefaultLiteral(column.default)}))})}return out}function renderDefaultLiteral(value2){if(typeof value2==="string")return`'${value2.replace(/'/g,"''")}'`;if(typeof value2==="number")return Number.isFinite(value2)?String(value2):void 0;if(typeof value2==="boolean")return value2?"true":"false";return}function tableNameOf(table){for(let key2 of Object.getOwnPropertySymbols(table))if(String(key2).includes("Name")&&!String(key2).includes("Schema")){let value2=Reflect.get(table,key2);if(typeof value2==="string"&&value2.length>0)return value2}return null}async function readActualSchema(execute2,schema3){return(await readActualSchemaDetailed(execute2,schema3)).columns}async function readActualSchemaDetailed(execute2,schema3){let result=await execute2(`select table_name, column_name, column_default from information_schema.columns where table_schema = '${schema3.replace(/'/g,"''")}'`),rows=Array.isArray(result)?result:result.rows??[],columns={},withDefault={};for(let source of rows){let row=rowOf(source),tableName=asText(row.table_name),columnName=asText(row.column_name);if(!tableName||!columnName)continue;if(columns[tableName]??=new Set,columns[tableName]?.add(columnName),withDefault[tableName]??=new Set,row.column_default!==null&&row.column_default!==void 0)withDefault[tableName]?.add(columnName)}return{columns,withDefault}}async function reconcileMissingColumns(options){let{db,schema:schema3,tables:tables2,logger:logger2,schemaObject}=options,run=(statement)=>db.execute(sql10.raw(statement));try{let expected=expectedFromTables(tables2);if(expected.length===0)return null;let{columns:actual,withDefault}=await readActualSchemaDetailed(run,schema3),drift=findDrift(expected,actual,withDefault),plan=planRepair(schema3,drift);if(plan.undeclaredTables=undeclaredTables(expected,actual),drift.missingTables.length>0){await createMissingTables({run,tables:tables2,missing:drift.missingTables,schemaObject,logger:logger2});let after=await readActualSchema(run,schema3);plan.createdTables=drift.missingTables.filter((name)=>after[name]),plan.missingTables=drift.missingTables.filter((name)=>!after[name])}let applied=0;for(let statement of plan.statements)try{await run(statement),applied+=1}catch(error3){logger2.error(`[Schema] could not add a missing column: ${statement} \u2014 ${error3 instanceof Error?error3.message:String(error3)}`)}for(let line of describeRepair(plan,applied))if(plan.missingTables.length>0||plan.unsafe.length>0)logger2.error(line);else logger2.info(line);return{applied,plan}}catch(error3){return logger2.error(`[Schema] the additive repair could not run: ${error3 instanceof Error?error3.message:String(error3)}`),null}}var ALREADY_EXISTS;var init_schemaReconcile=__esm(()=>{ALREADY_EXISTS=new Set(["42P06","42P07","42710","42723","23505"])});var ambiguousColumnTables=(expected,actual)=>{let found=[];for(let table of expected){let have=actual[table.name];if(!have)continue;let declared=new Set(table.columns.map((column)=>column.name)),added=table.columns.filter((column)=>!have.has(column.name)).map((c)=>c.name),extra=[...have].filter((name)=>!declared.has(name));if(added.length>0&&extra.length>0)found.push({table:table.name,added,extra})}return found};var trapDepth=0,realExit=null,withExitTrapped=async(work)=>{if(trapDepth===0)realExit=process.exit,process.exit=(code)=>{throw Error(`drizzle-kit called process.exit(${code??0}) during the schema push`)};trapDepth+=1;try{return await work()}finally{if(trapDepth-=1,trapDepth===0&&realExit)process.exit=realExit,realExit=null}};import{drizzle as drizzle3}from"drizzle-orm/node-postgres";import{Pool}from"pg";async function withPushDb(db,schemaName,logger2,work,openPool=(config)=>new Pool(config)){let config=pushPoolConfig(db);if(!config)return logger2.warn(`[Schema] ${schemaName}: the connection settings of the database handle cannot be read; the push uses the host pool and its connection timeout.`),work(db,!1);let pool=openPool(config);pool.on("error",(error3)=>{logger2.warn(`[Schema] ${schemaName}: push pool connection error \u2014 ${reasonOf(error3)}`)});try{return await work(drizzle3(pool),!0)}finally{await pool.end().catch((error3)=>{logger2.warn(`[Schema] ${schemaName}: push pool did not close cleanly \u2014 ${reasonOf(error3)}`)})}}var PUSH_POOL_MAX=4,pushPoolConfig=(db)=>{let client=Reflect.get(db,"$client");if(!(client instanceof Pool))return null;let{options}=client;if(!options.connectionString&&!options.host&&!options.database)return null;return{...options,connectionTimeoutMillis:0,max:PUSH_POOL_MAX}};var init_pushPool=__esm(()=>{init_schema3()});import{sql as sql11}from"drizzle-orm";import{PgDialect}from"drizzle-orm/pg-core";function keyOrderedIntrospection(db){let dialect=new PgDialect;return Object.create(db,{execute:{value:async(query)=>{let result=await db.execute(query),text4=dialect.sqlToQuery(query).sql,target=TABLE_OF_QUERY.exec(text4);if(!target||!text4.includes("constraint_column_usage"))return result;let keys=await uniqueKeyOrder(db,unquote(target[2]??""),unquote(target[1]??""));return{...result,rows:reordered(rowsOf2(result),keys)}}}})}var TABLE_OF_QUERY,unquote=(value2)=>value2.replace(/''/g,"'"),rowsOf2=(result)=>("rows"in result)&&Array.isArray(result.rows)?result.rows:[],uniqueKeyOrder=async(db,schemaName,tableName)=>{let result=await db.execute(sql11`select c.conname as name, a.attname as col
|
|
123
123
|
from pg_catalog.pg_constraint c
|
|
124
124
|
join pg_catalog.pg_class t on t.oid = c.conrelid
|
|
125
125
|
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
package/dist/server.js
CHANGED
|
@@ -129,7 +129,7 @@ end
|
|
|
129
129
|
redis.call('ZADD', KEYS[1], now, ARGV[4])
|
|
130
130
|
redis.call('PEXPIRE', KEYS[1], windowMs + 1000)
|
|
131
131
|
return {1, count + 1}
|
|
132
|
-
`,hashIdentity=(identity)=>createHash2("sha256").update(identity.trim().toLowerCase()).digest("base64url").slice(0,16),RateLimiterBackendError,DEFAULT_AUTH_LOGIN,DEFAULT_AUTH_REGISTER,DEFAULT_AUTH_PASSWORD_RESET,DEFAULT_AUTH_PASSWORD_RESET_CONFIRM,DEFAULT_AUTH_MAGIC_LINK,DEFAULT_CONFIG4;var init_RateLimiter=__esm(()=>{RateLimiterBackendError=class RateLimiterBackendError extends Error{constructor(message){super(message);this.name="RateLimiterBackendError"}};DEFAULT_AUTH_LOGIN={window:"15m",max:5,perAddressMax:100,blockDuration:"30m"},DEFAULT_AUTH_REGISTER={window:"1h",max:3,perAddressMax:30,blockDuration:"1h"},DEFAULT_AUTH_PASSWORD_RESET={window:"1h",max:3,perAddressMax:30,blockDuration:"1h"},DEFAULT_AUTH_PASSWORD_RESET_CONFIRM={window:"1h",max:10,perAddressMax:30,blockDuration:"15m"},DEFAULT_AUTH_MAGIC_LINK={window:"1h",max:5,perAddressMax:30,blockDuration:"1h"},DEFAULT_CONFIG4={enabled:!0,strategy:"sliding-window",keyPrefix:"rl:",authRoutes:{window:"1m",max:10,login:DEFAULT_AUTH_LOGIN,register:DEFAULT_AUTH_REGISTER,passwordReset:DEFAULT_AUTH_PASSWORD_RESET,passwordResetConfirm:DEFAULT_AUTH_PASSWORD_RESET_CONFIRM,magicLink:DEFAULT_AUTH_MAGIC_LINK},publicRoutes:{window:"1m",max:3000},privateRoutes:{window:"1m",max:3000},byIp:!0,byUserId:!0,byEndpoint:!1,skipSuccessfulRequests:!1,headers:{remaining:"X-RateLimit-Remaining",reset:"X-RateLimit-Reset",limit:"X-RateLimit-Limit"},whitelist:[],blacklist:[]}});function discoverSlots(source){let config=isPlainObject(source)?source:{},slots=new Map,add2=(slot)=>{let id=`${slot.scope}.${slot.key}`;if(!slots.has(id))slots.set(id,slot)},valueAt=(scope,key2)=>{let node=config;for(let segment of scope.split(".")){if(!isPlainObject(node))return;node=node[segment]}if(!isPlainObject(node))return;let value=node[key2];if(typeof value==="string")return value;if(Array.isArray(value)&&value.every((entry)=>typeof entry==="string"))return value.length>0?value.join(","):void 0;return};for(let descriptor of SECRET_SLOT_DESCRIPTORS)for(let scope of expandPath(config,descriptor.path,descriptor.always===!0)){let leaf=scope.split(".").pop()??descriptor.group,group=descriptor.path.endsWith("*")?`${descriptor.group}:${leaf}`:descriptor.group;for(let declared of descriptor.keys)add2({scope,key:declared.key,kind:declared.kind??kindFor(declared.key),label:declared.label,group,required:declared.required??!1,requiredWhen:declared.requiredWhen,hint:declared.hint,secret:declared.secret??descriptor.secret??!0,configValue:valueAt(scope,declared.key)})}let walk=(node,path,depth)=>{if(depth>6)return;for(let[key2,value]of Object.entries(node)){if(SKIP_SECTIONS.has(key2))continue;let childPath=path?`${path}.${key2}`:key2;if(isPlainObject(value)){walk(value,childPath,depth+1);continue}if(typeof value!=="string"&&value!==void 0&&value!==null)continue;if(!CREDENTIAL_KEY_PATTERN.test(key2))continue;if(NOT_A_CREDENTIAL.has(key2.toLowerCase()))continue;if(BOOT_ONLY_PATHS.has(`${path}.${key2}`))continue;let owner=path.split(".").pop(),label=owner&&owner.toLowerCase()!==key2.toLowerCase()?`${humanize(owner)} \u2014 ${humanize(key2)}`:humanize(key2);add2({scope:path,key:key2,kind:kindFor(key2),label,group:path.split(".")[0]??"other",required:!1,secret:!0,configValue:typeof value==="string"?value:void 0})}};return walk(config,"",0),[...slots.values()].sort((a,b)=>a.group.localeCompare(b.group)||a.scope.localeCompare(b.scope)||a.key.localeCompare(b.key))}var CREDENTIAL_KEY_PATTERN,NOT_A_CREDENTIAL,BOOT_ONLY_PATHS,SKIP_SECTIONS,kindFor=(key2)=>{let k=key2.toLowerCase();if(k.includes("json"))return"json";if(k.includes("connection"))return"connection_string";if(k.includes("privatekey")||k.includes("private_key"))return"pem";if(k.includes("clientid")||k.includes("client_id"))return"text";return"password"},humanize=(key2)=>key2.replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/\b\w/g,(c)=>c.toUpperCase()),SECRET_SLOT_DESCRIPTORS,isPlainObject=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value),expandPath=(config,path,always=!1)=>{let segments=path.split("."),scopes2=[{path:"",node:config}];for(let segment of segments){let next=[];for(let current of scopes2){if(!isPlainObject(current.node))continue;if(segment==="*")for(let[childKey,childValue]of Object.entries(current.node))next.push({path:current.path?`${current.path}.${childKey}`:childKey,node:childValue});else if(segment in current.node)next.push({path:current.path?`${current.path}.${segment}`:segment,node:current.node[segment]});else if(always)next.push({path:current.path?`${current.path}.${segment}`:segment,node:{}})}scopes2=next}return scopes2.filter((s)=>isPlainObject(s.node)).map((s)=>s.path)},looksLikeEnvName=(value)=>!!value&&/^[A-Z][A-Z0-9_]{2,}$/.test(value);var init_registry=__esm(()=>{CREDENTIAL_KEY_PATTERN=/(secret|password|passwd|apikey|api_key|accesskey|access_key|privatekey|private_key|token|credential|connection_string|connectionstring|clientid|client_id|encryptionkey|encryption_key|servicekey|service_key|json_file_path|jsonfilepath)$/i,NOT_A_CREDENTIAL=new Set(["preventapikeymanagement","allowapplicationkeys","maxkeysperuser","tokenurl","accesstoken","refreshtoken","sessiontoken"]),BOOT_ONLY_PATHS=new Set(["authorization.godminPassword","authorization.godminEmail","authentication.accessToken.secret","authentication.refreshToken.secret","authentication.sessionToken.secret","backup.encryptionKey","notification.channels.telegram.botToken","notification.channels.webhook.headers","domains.cloudflare.apiToken"]),SKIP_SECTIONS=new Set(["entities","systemTables","system_tables","tables","columns","indexes","routes","cors","swagger","secrets"]),SECRET_SLOT_DESCRIPTORS=[{path:"authentication.oauth.providers.*",group:"oauth",label:"OAuth / SSO",keys:[{key:"clientId",kind:"text",label:"Client ID",required:!0},{key:"clientSecret",kind:"password",label:"Client Secret",required:!0},{key:"tenantId",kind:"text",label:"Tenant ID"},{key:"redirectUri",kind:"text",secret:!1,required:!0,label:"Reply URL (Redirect URI)",hint:"The return address registered with the provider. It must be written identically on the provider side too (e.g. Entra > Authentication > Redirect URIs)."}]},{always:!0,path:"email.gmail",group:"email",label:"Gmail (service account)",keys:[{key:"service_account_json",kind:"json",label:"Service Account JSON",required:!0,requiredWhen:"enabled"}]},{always:!0,path:"email.azure",group:"email",label:"Azure Communication Services",keys:[{key:"connection_string",kind:"connection_string",label:"Connection String",required:!0,requiredWhen:"enabled"}]},{always:!0,path:"email.smtp",group:"email",label:"SMTP (Microsoft 365, Exchange, corporate mail)",keys:[{key:"enabled",kind:"boolean",secret:!1,label:"Send through this provider",hint:"The provider that is switched on carries the mail. If the panel cannot read this flag, the card stays \u201CNot set\u201D even when the details are filled in."},{key:"host",kind:"text",label:"Server",required:!0,requiredWhen:"enabled",hint:"smtp.office365.com for Microsoft 365"},{key:"port",kind:"text",label:"Port",hint:"Left empty this is 587 (STARTTLS). 465 means implicit TLS."},{key:"user",kind:"text",label:"Mailbox",required:!0,requiredWhen:"enabled",hint:"The address the password belongs to. It is also the sender address."},{key:"password",kind:"password",label:"Password / app password",required:!0,requiredWhen:"enabled",hint:"If the account has multi-factor authentication, the app password Microsoft generated. In Exchange Online, SMTP AUTH is off per tenant by default and a correct password is refused too \u2014 ask IT to turn it on for that mailbox."},{key:"sender_address",kind:"text",label:"Sender address (optional)",hint:"Left empty, the mailbox itself is used. If you enter a different address, Exchange requires that mailbox to have been granted \u201CSend As\u201D for it; without that the send is refused."},{key:"from_name",kind:"text",label:"Display name",hint:"The name the recipient reads in their inbox, e.g. the name of the portal."}]},{always:!0,path:"service",group:"service",label:"The server\u2019s own key",keys:[{key:"api_key",kind:"password",label:"Service API key",hint:"Some work the server has to do in its OWN name \u2014 counting how many people answered a survey, for instance. That cannot be done with an employee\u2019s permissions, and should not be. Generate the key in the admin panel and paste it here; it carries its owner\u2019s roles, not godmin\u2019s. Left empty, this work is skipped silently."}]},{always:!0,path:"storage.smb",group:"storage",label:"SMB / CIFS share",keys:[{key:"username",kind:"text",label:"Username",required:!0},{key:"password",kind:"password",label:"Password",required:!0}]},{secret:!1,always:!0,path:"storage",group:"storage",label:"File store",keys:[{key:"provider",kind:"text",label:"Storage kind",hint:"local (the server\u2019s own disk) or smb (a corporate file server). The change takes effect immediately."}]},{secret:!1,always:!0,path:"storage.smb",group:"storage",label:"SMB / CIFS share",keys:[{key:"url",kind:"text",label:"Share address",hint:"Paste it exactly as the customer sent it: smb://server/share \u2014 the server and the share name are read from this."},{key:"domain",kind:"text",label:"Domain",hint:"The domain part when the user is written as DOMAIN\\user. Leave empty if it is not needed."},{key:"base_path",kind:"text",label:"Folder inside the share",hint:"The subfolder uploads are gathered in. Empty means the root of the share."}]},{path:"payment.providers.*",group:"payment",label:"Payment provider",keys:[{key:"apiKey",kind:"password",label:"API Key",required:!0},{key:"secretKey",kind:"password",label:"Secret Key",required:!0},{key:"webhookSecret",kind:"password",label:"Webhook Secret"}]},{path:"captcha",group:"captcha",label:"Captcha",keys:[{key:"secretKey",kind:"password",label:"Secret Key"}]},{secret:!1,path:"authentication",group:"portal",label:"Portal address",keys:[{key:"trustedAppOrigins",kind:"list",label:"Trusted origins",required:!0,hint:"The address(es) the portal is installed at. Password-reset and SSO return links are built from these. Wildcard: *.company.com"}]},{secret:!1,always:!0,path:"email",group:"email",label:"Email provider",keys:[{key:"provider",kind:"text",label:"Provider to use",hint:"azure or gmail. Left empty, whichever provider is switched on is used."}]},{secret:!1,always:!0,path:"email.azure",group:"email",label:"Azure Communication Services",keys:[{key:"enabled",kind:"boolean",label:"Azure email enabled",hint:"Entering the connection string is not enough on its own \u2014 sending is turned on by this switch."},{key:"sender_address",kind:"text",label:"Sender address"},{key:"from_name",kind:"text",label:"Sender name",hint:"The name the recipient sees in their inbox in place of the address. Empty means the address shows."}]},{secret:!1,always:!0,path:"email.gmail",group:"email",label:"Gmail (service account)",keys:[{key:"enabled",kind:"boolean",label:"Gmail email enabled"},{key:"from_email",kind:"text",label:"Sender address"},{key:"from_name",kind:"text",label:"Sender name",hint:"The name the recipient sees in their inbox in place of the address. Empty means the address shows."}]}]});import{and as and14,eq as eq18}from"drizzle-orm";class SecretsStore{db;resolveTable;masterKey;constructor(deps){this.db=deps.db,this.resolveTable=deps.resolveTable,this.masterKey=deps.masterKey}table(schemaName){return this.resolveTable(SECRETS_TABLE,schemaName)}async loadAll(schemaName){let values=new Map,failed2=[],table=this.table(schemaName);if(!table)return{values,failed:failed2,tableMissing:!0};let rows;try{rows=(await this.db.select().from(table).where(eq18(col2(table,"isActive"),!0))).map(secretRowOf)}catch(error){if(isMissingTableError(error))return{values,failed:failed2,tableMissing:!0};throw error}for(let row of rows)try{values.set(cacheKeyOf(row.scope,row.key),decryptSecret(row.valueEnc,this.masterKey))}catch{failed2.push(`${row.scope}.${row.key}`)}return{values,failed:failed2}}async list(schemaName){let table=this.table(schemaName);if(!table)return[];try{return(await this.db.select().from(table)).map(secretRowOf).filter((r)=>r.isActive!==!1).map(rowToMeta)}catch(error){if(isMissingTableError(error))return[];throw error}}async get(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return null;let row=(await this.db.select().from(table).where(and14(eq18(col2(table,"scope"),scope),eq18(col2(table,"key"),key2))).limit(1))[0];return row?secretRowOf(row):null}async set(params,schemaName){let table=this.table(schemaName);if(!table)return null;let existing=await this.get(params.scope,params.key,schemaName),valueEnc=encryptSecret(params.value,this.masterKey),preview=previewOf(params.value),now2=new Date;if(existing)await this.db.update(table).set({valueEnc,previousEnc:existing.valueEnc,preview,kind:params.kind??existing.kind??"text",description:params.description??existing.description,version:(existing.version??1)+1,rotatedAt:now2,isActive:!0,updatedAt:now2,updatedBy:params.actorId??null}).where(eq18(col2(table,"id"),existing.id));else await this.db.insert(table).values({scope:params.scope,key:params.key,valueEnc,preview,kind:params.kind??"text",description:params.description??null,version:1,isActive:!0,createdBy:params.actorId??null,updatedBy:params.actorId??null});let saved=await this.get(params.scope,params.key,schemaName);return saved?rowToMeta(saved):null}async rollback(scope,key2,actorId,schemaName){let table=this.table(schemaName);if(!table)return null;let existing=await this.get(scope,key2,schemaName);if(!existing?.previousEnc)return null;let plaintext=decryptSecret(existing.previousEnc,this.masterKey),now2=new Date;await this.db.update(table).set({valueEnc:existing.previousEnc,previousEnc:existing.valueEnc,preview:previewOf(plaintext),version:(existing.version??1)+1,rotatedAt:now2,updatedAt:now2,updatedBy:actorId??null}).where(eq18(col2(table,"id"),existing.id));let saved=await this.get(scope,key2,schemaName);return saved?rowToMeta(saved):null}async remove(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return!1;let existing=await this.get(scope,key2,schemaName);if(!existing)return!1;return await this.db.delete(table).where(eq18(col2(table,"id"),existing.id)),!0}async touch(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return;await this.db.update(table).set({lastUsedAt:new Date}).where(and14(eq18(col2(table,"scope"),scope),eq18(col2(table,"key"),key2)))}async reencryptAll(newMasterKey,schemaName){let table=this.table(schemaName);if(!table)return{migrated:0,failed:[]};let rows=(await this.db.select().from(table)).map(secretRowOf),failed2=[],planned=[];for(let row of rows)try{let plaintext=decryptSecret(row.valueEnc,this.masterKey),previous=row.previousEnc?encryptSecret(decryptSecret(row.previousEnc,this.masterKey),newMasterKey):null;planned.push({id:row.id,valueEnc:encryptSecret(plaintext,newMasterKey),previousEnc:previous})}catch{failed2.push(`${row.scope}.${row.key}`)}if(failed2.length>0)return{migrated:0,failed:failed2};return await this.db.transaction(async(tx)=>{for(let row of planned)await tx.update(table).set({valueEnc:row.valueEnc,previousEnc:row.previousEnc}).where(eq18(col2(table,"id"),row.id))}),this.masterKey=newMasterKey,{migrated:planned.length,failed:failed2}}}var SECRETS_TABLE="nucleusSecrets",col2,SECRET_KINDS,isSecretKind=(value)=>Object.hasOwn(SECRET_KINDS,value),secretRowOf=(source)=>{let row=rowOf(source);return{id:asText(row.id)??"",scope:asText(row.scope)??"",key:asText(row.key)??"",valueEnc:asText(row.valueEnc)??"",previousEnc:asText(row.previousEnc)??null,preview:asText(row.preview)??null,kind:asText(row.kind)??null,description:asText(row.description)??null,version:asNumber(row.version)??1,rotatedAt:asDate(row.rotatedAt)??null,lastUsedAt:asDate(row.lastUsedAt)??null,updatedAt:asDate(row.updatedAt)??null,updatedBy:asText(row.updatedBy)??null,isActive:asBoolean(row.isActive)??null}},toIso=(value)=>value?new Date(value).toISOString():null,UNDEFINED_TABLE="42P01",isMissingTableError=(error)=>{let seen=new Set,current=typeof error==="object"&&error!==null?error:void 0;while(current&&!seen.has(current)){if(seen.add(current),fieldOf(current,"code")===UNDEFINED_TABLE)return!0;let message=fieldOf(current,"message");if(typeof message==="string"&&/relation .* does not exist/i.test(message))return!0;let cause=fieldOf(current,"cause");current=typeof cause==="object"&&cause!==null?cause:void 0}return!1},rowToMeta=(row)=>({id:row.id,scope:row.scope,key:row.key,kind:row.kind!==null&&isSecretKind(row.kind)?row.kind:"text",preview:row.preview??"",description:row.description,version:row.version??1,canRollback:!!row.previousEnc,rotatedAt:toIso(row.rotatedAt),lastUsedAt:toIso(row.lastUsedAt),updatedAt:toIso(row.updatedAt),updatedBy:row.updatedBy}),cacheKeyOf=(scope,key2)=>`${scope}.${key2}`;var init_store3=__esm(()=>{init_crypto();col2=columnOf,SECRET_KINDS={text:!0,password:!0,json:!0,connection_string:!0,pem:!0,boolean:!0,list:!0}});class SecretsService{store;logger;getRedis;refreshIntervalMs;schemaName;cache=new Map;timer=null;localRevision=0;loaded=!1;tableMissing=!1;warnedTableMissing=!1;constructor(deps){this.store=deps.store,this.logger=deps.logger,this.getRedis=deps.getRedis,this.refreshIntervalMs=deps.refreshIntervalMs??DEFAULT_REFRESH_MS,this.schemaName=deps.schemaName}async start(){if(await this.refresh(),this.timer)return;let timer=setInterval(()=>{this.refreshIfStale()},this.refreshIntervalMs);timer.unref?.(),this.timer=timer}stop(){if(this.timer)clearInterval(this.timer);this.timer=null}isReady(){return this.loaded}size(){return this.cache.size}isTableMissing(){return this.tableMissing}async refresh(){try{let{values,failed:failed2,tableMissing}=await this.store.loadAll(this.schemaName);if(tableMissing){if(this.tableMissing=!0,!this.warnedTableMissing)this.warnedTableMissing=!0,this.logger.warn("[Secrets] nucleus_secrets does not exist yet \u2014 env and literal values resolve normally; "+"the store activates automatically once the schema sync creates it");return}if(this.tableMissing)this.tableMissing=!1,this.warnedTableMissing=!1,this.logger.info("[Secrets] nucleus_secrets is now available \u2014 credential store active");if(this.cache=values,this.loaded=!0,failed2.length>0)this.logger.error("[Secrets] Credentials failed to decrypt and were skipped",{slots:failed2,hint:"master key changed without re-encrypting \u2014 POST /secrets/reencrypt with the old key"})}catch(error){this.logger.warn("[Secrets] Refresh failed, keeping cached values",{error:error instanceof Error?error.message:String(error)})}}async refreshIfStale(){let redis=this.getRedis?.();if(!redis)return this.refresh();try{let result=await redis.read(REVISION_KEY),remote=Number(result.data??0);if(Number.isFinite(remote)&&remote===this.localRevision&&this.loaded)return;await this.refresh(),this.localRevision=Number.isFinite(remote)?remote:this.localRevision}catch{await this.refresh()}}async bumpRevision(){let redis=this.getRedis?.();if(!redis)return;try{let next=Date.now();this.localRevision=next,await redis.create(REVISION_KEY,next)}catch{}}get(scope,key2){return this.cache.get(cacheKeyOf(scope,key2))}has(scope,key2){return this.cache.has(cacheKeyOf(scope,key2))}resolve(scope,key2,configValue){let fromDb=this.cache.get(cacheKeyOf(scope,key2));if(fromDb)return{value:fromDb,source:"db"};if(configValue){let fromEnv=process.env[configValue];if(fromEnv)return{value:fromEnv,source:"env"};if(looksLikeEnvName(configValue))return{value:void 0,source:"missing"};return{value:configValue,source:"literal"}}return{value:void 0,source:"missing"}}value(scope,key2,configValue){return this.resolve(scope,key2,configValue).value}listValue(scope,key2,configValue){let fallback=Array.isArray(configValue)?configValue.join(","):configValue,raw=this.value(scope,key2,fallback);if(!raw)return Array.isArray(configValue)?configValue:[];return raw.split(/[,;\n\r]+/).map((entry)=>entry.trim()).filter(Boolean)}flag(scope,key2,configValue){let raw=this.get(scope,key2);if(raw===void 0)return configValue===!0;return raw==="true"||raw==="1"}liveConfig(scope,node,keys){let live={...node};for(let key2 of keys){let declared=fieldOf(node,key2),configValue=typeof declared==="string"?declared:void 0;Object.defineProperty(live,key2,{get:()=>this.resolve(scope,key2,configValue).value,enumerable:!0,configurable:!0})}return live}async describe(config,slots){let discovered=slots??discoverSlots(config),stored=await this.store.list(this.schemaName),byId=new Map(stored.map((s)=>[cacheKeyOf(s.scope,s.key),s]));return discovered.map((slot)=>{let id=cacheKeyOf(slot.scope,slot.key),record=byId.get(id),{value,source}=this.resolve(slot.scope,slot.key,slot.configValue),envName=looksLikeEnvName(slot.configValue)?slot.configValue:void 0,gate=slot.requiredWhen?this.flag(slot.scope,slot.requiredWhen,configFlagAt(config,slot.scope,slot.requiredWhen)):!0;return{...slot,required:slot.required&&gate,configValue:envName,source,value:slot.secret?void 0:value,preview:slot.secret?source==="db"&&record?record.preview:value?previewOf(value):"":value??"",envName,version:record?.version,rotatedAt:record?.rotatedAt??null,canRollback:record?.canRollback??!1}})}async list(){return this.store.list(this.schemaName)}async set(params){let saved=await this.store.set(params,this.schemaName);return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential stored",{scope:params.scope,key:params.key,version:saved?.version,actor:params.actorId}),saved}async rollback(scope,key2,actorId){let saved=await this.store.rollback(scope,key2,actorId,this.schemaName);if(!saved)return null;return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential rolled back",{scope,key:key2,actor:actorId}),saved}async remove(scope,key2,actorId){if(!await this.store.remove(scope,key2,this.schemaName))return!1;return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential removed",{scope,key:key2,actor:actorId}),!0}async reencryptAll(newMasterKey){let result=await this.store.reencryptAll(newMasterKey,this.schemaName);return await this.refresh(),await this.bumpRevision(),result}}var REVISION_KEY="nucleus:secrets:revision",DEFAULT_REFRESH_MS=30000,configFlagAt=(config,scope,key2)=>{let node=config;for(let segment of scope.split(".")){if(typeof node!=="object"||node===null)return;node=fieldOf(node,segment)}if(typeof node!=="object"||node===null)return;let value=fieldOf(node,key2);if(typeof value==="boolean")return value;if(typeof value==="string")return value==="true"||value==="1";return};var init_SecretsService=__esm(()=>{init_crypto();init_registry();init_store3()});var resolveMasterKey=(configured)=>{if(configured){let fromEnv=process.env[configured];if(fromEnv)return fromEnv;if(!/^[A-Z][A-Z0-9_]{2,}$/.test(configured))return configured}return process.env.NUCLEUS_SECRETS_KEY||void 0};var init_Secrets=__esm(()=>{init_crypto();init_registry();init_SecretsService();init_store3()});var exports_schema={};__export(exports_schema,{validateIdentifier:()=>validateIdentifier,reasonOf:()=>reasonOf,isAlreadyPresent:()=>isAlreadyPresent,isAdditiveStatement:()=>isAdditiveStatement,ensureSchemaExists:()=>ensureSchemaExists,dropsSchemaObject:()=>dropsSchemaObject,applySchemaPush:()=>applySchemaPush});import{sql as sql15}from"drizzle-orm";function reasonOf(error){if(!(error instanceof Error))return String(error);let chain=errorChain(error),parts=[];for(let link of chain){let detail=fieldOf(link,"detail"),hint=fieldOf(link,"hint"),code=fieldOf(link,"code"),message=link.message.startsWith("Failed query:")&&chain.length>1?"":link.message;parts.push(message,detail?`detail: ${String(detail)}`:"",hint?`hint: ${String(hint)}`:"",code?`code: ${String(code)}`:"")}return parts.filter(Boolean).join(" \u2014 ")}function errorChain(error){let chain=[],current=error;while(current&&!chain.includes(current)&&chain.length<5)chain.push(current),current=current.cause instanceof Error?current.cause:void 0;return chain}function isAlreadyPresent(error){if(!(error instanceof Error))return!1;return errorChain(error).some((link)=>{let code=fieldOf(link,"code");return typeof code==="string"&&ALREADY_PRESENT.has(code)})}var validateIdentifier=(name)=>{if(!name||name.length>63)throw Error(`Invalid identifier: must be 1-63 characters, got ${name.length}`);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name))throw Error(`Invalid identifier: "${name}" contains unsafe characters`);return name},ensureSchemaExists=async(db,schemaName)=>{let safeName=validateIdentifier(schemaName),found=await db.execute(sql15`select 1 from pg_catalog.pg_namespace where nspname = ${safeName} limit 1`);if(rowCountOf(found)>0)return;await db.execute(sql15.raw(`CREATE SCHEMA IF NOT EXISTS "${safeName}"`))},rowCountOf=(result)=>{if(Array.isArray(result))return result.length;return"rows"in result&&Array.isArray(result.rows)?result.rows.length:0},ADDITIVE_PREFIXES,ALREADY_PRESENT,isAdditiveStatement=(statement)=>{let normalized=statement.trim().toUpperCase();if(/^ALTER TABLE .+ ADD COLUMN/.test(normalized))return!0;if(/^ALTER TABLE .+ ALTER COLUMN .+ SET DEFAULT /.test(normalized))return!0;if(/^ALTER TABLE .+ ADD CONSTRAINT /.test(normalized))return!0;if(/^ALTER TABLE .+ ALTER COLUMN .+ DROP NOT NULL$/.test(normalized))return!0;return ADDITIVE_PREFIXES.some((prefix)=>normalized.startsWith(prefix))},dropsSchemaObject=(statement)=>{let normalized=statement.trim().toUpperCase();return/^DROP INDEX /.test(normalized)||/^ALTER TABLE .+ DROP CONSTRAINT /.test(normalized)||/^DROP SEQUENCE /.test(normalized)},withoutKeptDrops=(push,opts)=>{let keep=opts.keep??dropsSchemaObject,kept=push.statementsToExecute.filter(keep);if(kept.length===0)return push;opts.logger.warn(`[Schema] Kept ${kept.length} index/constraint/sequence object(s) in "${opts.schemaName}" ${opts.reason??"that the table model does not declare (database.keepUndeclaredObjects). Declare them in the model, or drop them by hand if they are really gone."}`,{statements:kept});let{execute}=opts;if(!execute)return opts.logger.error(`[Schema] The schema push for "${opts.schemaName}" was not applied: keeping undeclared objects needs a statement executor to run the rest of it.`),null;let rest=push.statementsToExecute.filter((statement)=>!keep(statement));return{...push,statementsToExecute:rest,apply:async()=>{for(let statement of rest)await execute(statement)}}},applySchemaPush=async(planned,opts)=>{let{schemaName,allowDataLoss,logger:logger2,execute}=opts,owned=opts.keepObject?withoutKeptDrops(planned,{schemaName,logger:logger2,execute,keep:opts.keepObject,reason:"owned by a migration of the ledger (database.migrations)."}):planned,push=owned&&opts.keepUndeclaredObjects===!0&&!allowDataLoss?withoutKeptDrops(owned,opts):owned;if(!push)return!1;if(push.hasDataLoss&&!allowDataLoss){let additive=push.statementsToExecute.filter(isAdditiveStatement),blocked=push.statementsToExecute.filter((s)=>!isAdditiveStatement(s));if(logger2.error(`[Schema] Destructive changes detected for schema "${schemaName}" but database.allowDataLoss is not enabled \u2014 ${blocked.length} statement(s) skipped. Set database.allowDataLoss: true to apply them.`,{warnings:push.warnings,statements:blocked}),additive.length===0||!execute)return!1;let applied=0;for(let statement of additive)try{await execute(statement),applied++}catch(error){logger2.warn(`[Schema] ${schemaName}: ${statement} \u2014 ${reasonOf(error)}`)}return logger2.info(`[Schema] Applied ${applied}/${additive.length} additive statement(s) for "${schemaName}" despite the destructive changes being held back`),applied>0}if(push.hasDataLoss)logger2.warn(`[Schema] Applying destructive changes to schema "${schemaName}" (database.allowDataLoss=true)`,{warnings:push.warnings});try{return await push.apply(),!0}catch(error){let message=error instanceof Error?error.message:String(error);if(!execute)return logger2.error(`[Schema] Could not apply schema changes to "${schemaName}": ${message}. The database does not match this build, so queries against the missing columns will fail.`,{warnings:push.warnings}),!1;logger2.error(`[Schema] The schema push for "${schemaName}" failed as a batch (${message}) \u2014 retrying its ${push.statementsToExecute.length} statement(s) one at a time so one bad statement does not hold back the rest.`);let applied=0,alreadyPresent=0,failures=[];for(let statement of push.statementsToExecute)try{await execute(statement),applied++}catch(statementError){if(isAlreadyPresent(statementError)){alreadyPresent++;continue}failures.push(statement),logger2.error(`[Schema] ${schemaName}: ${statement} \u2014 ${reasonOf(statementError)}`)}if(alreadyPresent>0)logger2.info(`[Schema] ${alreadyPresent} statement(s) for "${schemaName}" found their object already in place (applied before the batch stopped).`);if(failures.length>0)logger2.error(`[Schema] ${failures.length} of ${push.statementsToExecute.length} statement(s) could not be applied to "${schemaName}". Any query touching what they would have created will fail until they are.`);return applied>0||alreadyPresent>0}};var init_schema=__esm(()=>{ADDITIVE_PREFIXES=["CREATE TABLE IF NOT EXISTS","CREATE TABLE","CREATE SCHEMA IF NOT EXISTS","CREATE SCHEMA","CREATE INDEX IF NOT EXISTS","CREATE INDEX","CREATE UNIQUE INDEX IF NOT EXISTS","CREATE UNIQUE INDEX","CREATE TYPE","DO $$"];ALREADY_PRESENT=new Set(["42P07","42P06","42710","42701","42723"])});var rowToTenantRecord=(source)=>{let row=rowOf(source);return{id:String(row.id||""),subdomain:String(row.subdomain||""),schemaName:String(row.schemaName||row.schema_name||""),companyId:String(row.companyId||row.company_id||""),companyName:row.companyName!=null?String(row.companyName):row.company_name!=null?String(row.company_name):null,godAdminEmail:String(row.godAdminEmail||row.god_admin_email||""),status:parseStatus(row.status),plan:row.plan!=null?String(row.plan):null,domain:row.domain!=null?String(row.domain):null,settings:parseJsonbToConfig(row.settings),trustedSources:parseTrustedSources(row.trustedSources||row.trusted_sources),maxUsers:row.maxUsers!=null?Number(row.maxUsers):row.max_users!=null?Number(row.max_users):null,provisionedAt:row.provisionedAt!=null?String(row.provisionedAt):row.provisioned_at!=null?String(row.provisioned_at):null,suspendedAt:row.suspendedAt!=null?String(row.suspendedAt):row.suspended_at!=null?String(row.suspended_at):null,suspendedReason:row.suspendedReason!=null?String(row.suspendedReason):row.suspended_reason!=null?String(row.suspended_reason):null}},rowToFeatureRecord=(source,parseConfig)=>{let row=rowOf(source);return{id:String(row.id||""),tenantId:String(row.tenantId||row.tenant_id||""),featureName:String(row.featureName||row.feature_name||""),enabled:Boolean(row.enabled),featureConfig:parseConfig(row.config)}},parseStatus=(value)=>{let valid=["provisioning","active","suspended","archived"],str2=String(value||"provisioning");return valid.find((status)=>status===str2)??"provisioning"},parseJsonbToConfig=(value)=>{if(!value||typeof value!=="object")return{};let result={};for(let[k,v]of Object.entries(rowOf(value)))if(typeof v==="string"||typeof v==="number"||typeof v==="boolean")result[k]=v;return result},parseTrustedSources=(value)=>{if(!Array.isArray(value))return[];return value.map((item)=>{let entry=typeof item==="object"&&item!==null?rowOf(item):{};return{allowHeaderAuth:entry.allowHeaderAuth===!0||entry.allow_header_auth===!0,allowedIps:textEntries(entry.allowedIps||entry.allowed_ips),allowedServices:textEntries(entry.allowedServices||entry.allowed_services)}})},textEntries=(value)=>Array.isArray(value)?value.filter((entry)=>typeof entry==="string"):void 0,normalizeHost=(host)=>{return((host||"").split(":")[0]||"").toLowerCase().replace(/\.$/,"")},extractSubdomain=(host)=>{let hostWithoutPort=host.split(":")[0]||"";if(hostWithoutPort==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(hostWithoutPort))return null;let parts=hostWithoutPort.split(".");if(parts.length<3)return null;let subdomain=parts[0]||"";if(!subdomain||subdomain==="www")return null;return subdomain},toIPv4Octets=(address)=>{let bare=address.startsWith("::ffff:")?address.slice(7):address;if(bare.includes(":"))return null;let parts=bare.split(".");if(parts.length!==4)return null;let[a,b,c,d]=parts.map((part)=>/^\d{1,3}$/.test(part)?Number(part):Number.NaN);if(a===void 0||b===void 0||c===void 0||d===void 0)return null;let octets=[a,b,c,d];return octets.every((o)=>Number.isInteger(o)&&o>=0&&o<=255)?octets:null},isIpInCidr=(ip,cidr)=>{let[cidrIp,prefixStr]=cidr.split("/");if(!cidrIp||!prefixStr)return!1;let prefix=Number.parseInt(prefixStr,10);if(Number.isNaN(prefix)||prefix<0||prefix>32)return!1;let ipParts=toIPv4Octets(ip),cidrParts=toIPv4Octets(cidrIp);if(!ipParts||!cidrParts)return!1;let toNumber=([a,b,c,d])=>(a<<24|b<<16|c<<8|d)>>>0,ipNum=toNumber(ipParts),cidrNum=toNumber(cidrParts),mask=prefix===0?0:~((1<<32-prefix)-1)>>>0;return(ipNum&mask)===(cidrNum&mask)},isTrustedSource=(tenant,request,authMode,fallbackSources,vettedClientIp)=>{let ownSources=tenant.trustedSources,trustedSources=Array.isArray(ownSources)&&ownSources.length>0?ownSources:fallbackSources;if(!trustedSources||!Array.isArray(trustedSources)||trustedSources.length===0)return!1;let clientIp=vettedClientIp?.trim()||"",serviceId=request.headers.get("x-service-id")||"";for(let source of trustedSources){if(!source.allowHeaderAuth)continue;if(source.allowedIps&&source.allowedIps.length>0){if(source.allowedIps.some((allowedIp)=>{if(allowedIp.includes("/"))return isIpInCidr(clientIp,allowedIp);return clientIp===allowedIp}))return!0}if(source.allowedServices&&source.allowedServices.length>0){if(source.allowedServices.includes(serviceId))return!0}}return!1},pickRequestHost=(request,hostHeader,hostHeaderTrusted)=>{if(hostHeader&&hostHeaderTrusted){let forwarded=request.headers.get(hostHeader)?.split(",")[0]?.trim();if(forwarded)return forwarded}return request.headers.get("host")||new URL(request.url).host||""};var init_helpers=()=>{};import{pgSchema}from"drizzle-orm/pg-core";function createProvisionedSchemas(deps){let cache=new Map;return(schemaName)=>{let tenant=deps.tenantOf(schemaName);if(!tenant||!PROVISIONED_STATUSES.has(tenant.status))return;let cached=cache.get(schemaName);if(cached)return cached;let schema=pgSchema(schemaName),built={tables:deps.createTables(schema),relations:deps.createRelations?deps.createRelations(schema):{}};return cache.set(schemaName,built),built}}function hostTablesResolver(mainSchema,mainTables,source){return(schemaName)=>{if(schemaName===mainSchema)return mainTables;return source()?.getProvisionedSchema(schemaName)?.tables}}function hostRelationsResolver(mainSchema,mainRelations,source){return(schemaName)=>{if(schemaName===mainSchema)return mainRelations;return source()?.getProvisionedSchema(schemaName)?.relations??{}}}var PROVISIONED_STATUSES;var init_provisionedSchemas=__esm(()=>{PROVISIONED_STATUSES=new Set(["provisioning","active","suspended","archived"])});async function withDeadline(promise,timeoutMs,message){promise.catch(()=>{});let timer,deadline=new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(Error(message)),timeoutMs)});try{return await Promise.race([promise,deadline])}finally{if(timer)clearTimeout(timer)}}var exports_schemaReconcile={};__export(exports_schemaReconcile,{undeclaredTables:()=>undeclaredTables,setDefaultStatement:()=>setDefaultStatement,renderDefaultLiteral:()=>renderDefaultLiteral,reconcileMissingColumns:()=>reconcileMissingColumns,readActualSchemaDetailed:()=>readActualSchemaDetailed,readActualSchema:()=>readActualSchema,planRepair:()=>planRepair,findDrift:()=>findDrift,expectedFromTables:()=>expectedFromTables,describeRepair:()=>describeRepair,createMissingTables:()=>createMissingTables,addColumnStatement:()=>addColumnStatement});import{getTableColumns as getTableColumns6,sql as sql16}from"drizzle-orm";function findDrift(expected,actual,actualDefaults){let missingTables=[],missingColumns=[],columnsMissingDefault=[];for(let table of expected){let have=actual[table.name];if(!have){missingTables.push(table.name);continue}let haveDefault=actualDefaults?.[table.name];for(let column of table.columns){if(!have.has(column.name)){missingColumns.push({table:table.name,column});continue}if(haveDefault&&column.hasDefault&&column.defaultLiteral!==void 0&&!haveDefault.has(column.name))columnsMissingDefault.push({table:table.name,column})}}return{missingTables,missingColumns,columnsMissingDefault}}function addColumnStatement(schema,table,column){if(column.notNull&&!column.hasDefault)return null;return[`alter table "${schema}"."${table}"`,`add column if not exists "${column.name}" ${column.sqlType}`].join(" ")}function setDefaultStatement(schema,table,column){if(column.defaultLiteral===void 0)return null;return`alter table "${schema}"."${table}" alter column "${column.name}" set default ${column.defaultLiteral}`}function planRepair(schema,drift){let statements=[],unsafe=[];for(let{table,column}of drift.missingColumns){let statement=addColumnStatement(schema,table,column);if(statement)statements.push(statement);else unsafe.push({table,column:column.name,why:"declared NOT NULL with no default, and the table already has rows to fill"})}for(let{table,column}of drift.columnsMissingDefault){let statement=setDefaultStatement(schema,table,column);if(statement)statements.push(statement)}return{statements,unsafe,missingTables:drift.missingTables,createdTables:[],undeclaredTables:[]}}function undeclaredTables(expected,actual){let declared=new Set(expected.map((t)=>t.name));return Object.keys(actual).filter((name)=>!declared.has(name)).sort()}function isAlreadyExists(error){if(typeof error==="object"&&error!==null&&"code"in error){let code=error.code;if(typeof code==="string"&&ALREADY_EXISTS.has(code))return!0}return/already exists/i.test(errorMessage(error))}async function createMissingTables(options){let{run,tables,missing,schemaObject,logger:logger2,timeoutMs=60000}=options;if(missing.length===0)return{applied:0,errors:[]};let wanted=new Set(missing),imports={};for(let[key2,table]of Object.entries(tables)){if(!table||typeof table!=="object")continue;let name=tableNameOf(table);if(name&&wanted.has(name))imports[key2]=table}if(schemaObject)imports.__nucleusSchema=schemaObject;let statements;try{let{generateDrizzleJson,generateMigration}=await import("drizzle-kit/api"),realExit=process.exit;try{process.exit=(code)=>{throw Error(`drizzle-kit called process.exit(${code??0}) while generating table DDL`)},statements=await withDeadline(generateMigration(generateDrizzleJson({}),generateDrizzleJson(imports)),timeoutMs,`generating CREATE TABLE statements did not finish within ${timeoutMs}ms`)}finally{process.exit=realExit}}catch(error){let message=error instanceof Error?error.message:String(error);return logger2.error(`[Schema] CREATE TABLE statements could not be generated: ${message}`),{applied:0,errors:[message]}}let applied=0,errors=[];for(let statement of statements)try{await run(statement),applied+=1}catch(error){if(isAlreadyExists(error))continue;let message=error instanceof Error?error.message:String(error);errors.push(message),logger2.error(`[Schema] could not apply generated DDL: ${statement} \u2014 ${message}`)}return{applied,errors}}function describeRepair(plan,applied){let lines=[];if(applied>0)lines.push(`[Schema] The push applied nothing, so ${applied} missing column(s) were added directly. `+"This is additive only \u2014 nothing was dropped or altered.");if(plan.createdTables.length>0)lines.push(`[Schema] ${plan.createdTables.length} table(s) the push did not create were created directly: ${plan.createdTables.join(", ")}. Verified present in the database afterwards, not assumed from the statements that ran.`);if(plan.missingTables.length>0){if(lines.push(`[Schema] ${plan.missingTables.length} table(s) the code expects still do not exist: ${plan.missingTables.join(", ")}. Every read of these will fail. The additive repair tried `+"and could not create them \u2014 this needs a human."),plan.undeclaredTables.length>0)lines.push(`[Schema] The push is ambiguous because the database has ${plan.undeclaredTables.length} table(s) the model does not declare: ${plan.undeclaredTables.join(", ")}. drizzle-kit cannot tell a new table from a rename of one of these, and cannot ask without a TTY. Drop the stale one, or declare it, and the push stops aborting.`)}for(let item of plan.unsafe)lines.push(`[Schema] "${item.table}"."${item.column}" could not be added: ${item.why}. Give the column a default, or add it by hand with a backfill.`);return lines}function expectedFromTables(tables){let out=[];for(let value of Object.values(tables)){let table=asTable(value);if(!table)continue;let columns;try{columns=getTableColumns6(table)}catch{continue}if(!columns)continue;let list3=Object.values(columns),name=tableNameOf(table);if(!name||list3.length===0)continue;out.push({name,columns:list3.map((column)=>({name:column.name,sqlType:typeof column.getSQLType==="function"?column.getSQLType():"text",notNull:column.notNull===!0,hasDefault:column.hasDefault===!0,defaultLiteral:renderDefaultLiteral(column.default)}))})}return out}function renderDefaultLiteral(value){if(typeof value==="string")return`'${value.replace(/'/g,"''")}'`;if(typeof value==="number")return Number.isFinite(value)?String(value):void 0;if(typeof value==="boolean")return value?"true":"false";return}function tableNameOf(table){for(let key2 of Object.getOwnPropertySymbols(table))if(String(key2).includes("Name")&&!String(key2).includes("Schema")){let value=Reflect.get(table,key2);if(typeof value==="string"&&value.length>0)return value}return null}async function readActualSchema(execute,schema){return(await readActualSchemaDetailed(execute,schema)).columns}async function readActualSchemaDetailed(execute,schema){let result=await execute(`select table_name, column_name, column_default from information_schema.columns where table_schema = '${schema.replace(/'/g,"''")}'`),rows=Array.isArray(result)?result:result.rows??[],columns={},withDefault={};for(let source of rows){let row=rowOf(source),tableName=asText(row.table_name),columnName=asText(row.column_name);if(!tableName||!columnName)continue;if(columns[tableName]??=new Set,columns[tableName]?.add(columnName),withDefault[tableName]??=new Set,row.column_default!==null&&row.column_default!==void 0)withDefault[tableName]?.add(columnName)}return{columns,withDefault}}async function reconcileMissingColumns(options){let{db,schema,tables,logger:logger2,schemaObject}=options,run=(statement)=>db.execute(sql16.raw(statement));try{let expected=expectedFromTables(tables);if(expected.length===0)return null;let{columns:actual,withDefault}=await readActualSchemaDetailed(run,schema),drift=findDrift(expected,actual,withDefault),plan=planRepair(schema,drift);if(plan.undeclaredTables=undeclaredTables(expected,actual),drift.missingTables.length>0){await createMissingTables({run,tables,missing:drift.missingTables,schemaObject,logger:logger2});let after=await readActualSchema(run,schema);plan.createdTables=drift.missingTables.filter((name)=>after[name]),plan.missingTables=drift.missingTables.filter((name)=>!after[name])}let applied=0;for(let statement of plan.statements)try{await run(statement),applied+=1}catch(error){logger2.error(`[Schema] could not add a missing column: ${statement} \u2014 ${error instanceof Error?error.message:String(error)}`)}for(let line of describeRepair(plan,applied))if(plan.missingTables.length>0||plan.unsafe.length>0)logger2.error(line);else logger2.info(line);return{applied,plan}}catch(error){return logger2.error(`[Schema] the additive repair could not run: ${error instanceof Error?error.message:String(error)}`),null}}var ALREADY_EXISTS;var init_schemaReconcile=__esm(()=>{ALREADY_EXISTS=new Set(["42P06","42P07","42710","42723","23505"])});var ambiguousColumnTables=(expected,actual)=>{let found=[];for(let table of expected){let have=actual[table.name];if(!have)continue;let declared=new Set(table.columns.map((column)=>column.name)),added=table.columns.filter((column)=>!have.has(column.name)).map((c)=>c.name),extra=[...have].filter((name)=>!declared.has(name));if(added.length>0&&extra.length>0)found.push({table:table.name,added,extra})}return found};var trapDepth=0,realExit=null,withExitTrapped=async(work)=>{if(trapDepth===0)realExit=process.exit,process.exit=(code)=>{throw Error(`drizzle-kit called process.exit(${code??0}) during the schema push`)};trapDepth+=1;try{return await work()}finally{if(trapDepth-=1,trapDepth===0&&realExit)process.exit=realExit,realExit=null}};import{drizzle as drizzle3}from"drizzle-orm/node-postgres";import{Pool as Pool2}from"pg";async function withPushDb(db,schemaName,logger2,work,openPool=(config)=>new Pool2(config)){let config=pushPoolConfig(db);if(!config)return logger2.warn(`[Schema] ${schemaName}: the connection settings of the database handle cannot be read; the push uses the host pool and its connection timeout.`),work(db,!1);let pool=openPool(config);pool.on("error",(error)=>{logger2.warn(`[Schema] ${schemaName}: push pool connection error \u2014 ${reasonOf(error)}`)});try{return await work(drizzle3(pool),!0)}finally{await pool.end().catch((error)=>{logger2.warn(`[Schema] ${schemaName}: push pool did not close cleanly \u2014 ${reasonOf(error)}`)})}}var PUSH_POOL_MAX=4,pushPoolConfig=(db)=>{let client=Reflect.get(db,"$client");if(!(client instanceof Pool2))return null;let{options}=client;if(!options.connectionString&&!options.host&&!options.database)return null;return{...options,connectionTimeoutMillis:0,max:PUSH_POOL_MAX}};var init_pushPool=__esm(()=>{init_schema()});import{sql as sql17}from"drizzle-orm";import{PgDialect}from"drizzle-orm/pg-core";function keyOrderedIntrospection(db){let dialect=new PgDialect;return Object.create(db,{execute:{value:async(query)=>{let result=await db.execute(query),text3=dialect.sqlToQuery(query).sql,target=TABLE_OF_QUERY.exec(text3);if(!target||!text3.includes("constraint_column_usage"))return result;let keys=await uniqueKeyOrder(db,unquote(target[2]??""),unquote(target[1]??""));return{...result,rows:reordered(rowsOf2(result),keys)}}}})}var TABLE_OF_QUERY,unquote=(value)=>value.replace(/''/g,"'"),rowsOf2=(result)=>("rows"in result)&&Array.isArray(result.rows)?result.rows:[],uniqueKeyOrder=async(db,schemaName,tableName)=>{let result=await db.execute(sql17`select c.conname as name, a.attname as col
|
|
132
|
+
`,hashIdentity=(identity)=>createHash2("sha256").update(identity.trim().toLowerCase()).digest("base64url").slice(0,16),RateLimiterBackendError,DEFAULT_AUTH_LOGIN,DEFAULT_AUTH_REGISTER,DEFAULT_AUTH_PASSWORD_RESET,DEFAULT_AUTH_PASSWORD_RESET_CONFIRM,DEFAULT_AUTH_MAGIC_LINK,DEFAULT_CONFIG4;var init_RateLimiter=__esm(()=>{RateLimiterBackendError=class RateLimiterBackendError extends Error{constructor(message){super(message);this.name="RateLimiterBackendError"}};DEFAULT_AUTH_LOGIN={window:"15m",max:5,perAddressMax:100,blockDuration:"30m"},DEFAULT_AUTH_REGISTER={window:"1h",max:3,perAddressMax:30,blockDuration:"1h"},DEFAULT_AUTH_PASSWORD_RESET={window:"1h",max:3,perAddressMax:30,blockDuration:"1h"},DEFAULT_AUTH_PASSWORD_RESET_CONFIRM={window:"1h",max:10,perAddressMax:30,blockDuration:"15m"},DEFAULT_AUTH_MAGIC_LINK={window:"1h",max:5,perAddressMax:30,blockDuration:"1h"},DEFAULT_CONFIG4={enabled:!0,strategy:"sliding-window",keyPrefix:"rl:",authRoutes:{window:"1m",max:10,login:DEFAULT_AUTH_LOGIN,register:DEFAULT_AUTH_REGISTER,passwordReset:DEFAULT_AUTH_PASSWORD_RESET,passwordResetConfirm:DEFAULT_AUTH_PASSWORD_RESET_CONFIRM,magicLink:DEFAULT_AUTH_MAGIC_LINK},publicRoutes:{window:"1m",max:3000},privateRoutes:{window:"1m",max:3000},byIp:!0,byUserId:!0,byEndpoint:!1,skipSuccessfulRequests:!1,headers:{remaining:"X-RateLimit-Remaining",reset:"X-RateLimit-Reset",limit:"X-RateLimit-Limit"},whitelist:[],blacklist:[]}});function discoverSlots(source){let config=isPlainObject(source)?source:{},slots=new Map,add2=(slot)=>{let id=`${slot.scope}.${slot.key}`;if(!slots.has(id))slots.set(id,slot)},valueAt=(scope,key2)=>{let node=config;for(let segment of scope.split(".")){if(!isPlainObject(node))return;node=node[segment]}if(!isPlainObject(node))return;let value=node[key2];if(typeof value==="string")return value;if(Array.isArray(value)&&value.every((entry)=>typeof entry==="string"))return value.length>0?value.join(","):void 0;return};for(let descriptor of SECRET_SLOT_DESCRIPTORS)for(let scope of expandPath(config,descriptor.path,descriptor.always===!0)){let leaf=scope.split(".").pop()??descriptor.group,group=descriptor.path.endsWith("*")?`${descriptor.group}:${leaf}`:descriptor.group;for(let declared of descriptor.keys)add2({scope,key:declared.key,kind:declared.kind??kindFor(declared.key),label:declared.label,group,required:declared.required??!1,requiredWhen:declared.requiredWhen,hint:declared.hint,secret:declared.secret??descriptor.secret??!0,configValue:valueAt(scope,declared.key)})}let walk=(node,path,depth)=>{if(depth>6)return;for(let[key2,value]of Object.entries(node)){if(SKIP_SECTIONS.has(key2))continue;let childPath=path?`${path}.${key2}`:key2;if(isPlainObject(value)){walk(value,childPath,depth+1);continue}if(typeof value!=="string"&&value!==void 0&&value!==null)continue;if(!CREDENTIAL_KEY_PATTERN.test(key2))continue;if(NOT_A_CREDENTIAL.has(key2.toLowerCase()))continue;if(BOOT_ONLY_PATHS.has(`${path}.${key2}`))continue;let owner=path.split(".").pop(),label=owner&&owner.toLowerCase()!==key2.toLowerCase()?`${humanize(owner)} \u2014 ${humanize(key2)}`:humanize(key2);add2({scope:path,key:key2,kind:kindFor(key2),label,group:path.split(".")[0]??"other",required:!1,secret:!0,configValue:typeof value==="string"?value:void 0})}};return walk(config,"",0),[...slots.values()].sort((a,b)=>a.group.localeCompare(b.group)||a.scope.localeCompare(b.scope)||a.key.localeCompare(b.key))}var CREDENTIAL_KEY_PATTERN,NOT_A_CREDENTIAL,BOOT_ONLY_PATHS,SKIP_SECTIONS,kindFor=(key2)=>{let k=key2.toLowerCase();if(k.includes("json"))return"json";if(k.includes("connection"))return"connection_string";if(k.includes("privatekey")||k.includes("private_key"))return"pem";if(k.includes("clientid")||k.includes("client_id"))return"text";return"password"},humanize=(key2)=>key2.replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/\b\w/g,(c)=>c.toUpperCase()),SECRET_SLOT_DESCRIPTORS,isPlainObject=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value),expandPath=(config,path,always=!1)=>{let segments=path.split("."),scopes2=[{path:"",node:config}];for(let segment of segments){let next=[];for(let current of scopes2){if(!isPlainObject(current.node))continue;if(segment==="*")for(let[childKey,childValue]of Object.entries(current.node))next.push({path:current.path?`${current.path}.${childKey}`:childKey,node:childValue});else if(segment in current.node)next.push({path:current.path?`${current.path}.${segment}`:segment,node:current.node[segment]});else if(always)next.push({path:current.path?`${current.path}.${segment}`:segment,node:{}})}scopes2=next}return scopes2.filter((s)=>isPlainObject(s.node)).map((s)=>s.path)},looksLikeEnvName=(value)=>!!value&&/^[A-Z][A-Z0-9_]{2,}$/.test(value);var init_registry=__esm(()=>{CREDENTIAL_KEY_PATTERN=/(secret|password|passwd|apikey|api_key|accesskey|access_key|privatekey|private_key|token|credential|connection_string|connectionstring|clientid|client_id|encryptionkey|encryption_key|servicekey|service_key|json_file_path|jsonfilepath)$/i,NOT_A_CREDENTIAL=new Set(["preventapikeymanagement","allowapplicationkeys","maxkeysperuser","tokenurl","accesstoken","refreshtoken","sessiontoken"]),BOOT_ONLY_PATHS=new Set(["authorization.godminPassword","authorization.godminEmail","authentication.accessToken.secret","authentication.refreshToken.secret","authentication.sessionToken.secret","backup.encryptionKey","notification.channels.telegram.botToken","notification.channels.webhook.headers","domains.cloudflare.apiToken"]),SKIP_SECTIONS=new Set(["entities","systemTables","system_tables","tables","columns","indexes","routes","cors","swagger","secrets"]),SECRET_SLOT_DESCRIPTORS=[{path:"authentication.oauth.providers.*",group:"oauth",label:"OAuth / SSO",keys:[{key:"clientId",kind:"text",label:"Client ID",required:!0},{key:"clientSecret",kind:"password",label:"Client Secret",required:!0},{key:"tenantId",kind:"text",label:"Tenant ID"},{key:"redirectUri",kind:"text",secret:!1,required:!0,label:"Reply URL (Redirect URI)",hint:"The return address registered with the provider. It must be written identically on the provider side too (e.g. Entra > Authentication > Redirect URIs)."}]},{always:!0,path:"email.gmail",group:"email",label:"Gmail (service account)",keys:[{key:"service_account_json",kind:"json",label:"Service Account JSON",required:!0,requiredWhen:"enabled"}]},{always:!0,path:"email.azure",group:"email",label:"Azure Communication Services",keys:[{key:"connection_string",kind:"connection_string",label:"Connection String",required:!0,requiredWhen:"enabled"}]},{always:!0,path:"email.smtp",group:"email",label:"SMTP (Microsoft 365, Exchange, corporate mail)",keys:[{key:"enabled",kind:"boolean",secret:!1,label:"Send through this provider",hint:"The provider that is switched on carries the mail. If the panel cannot read this flag, the card stays \u201CNot set\u201D even when the details are filled in."},{key:"host",kind:"text",secret:!1,label:"Server",required:!0,requiredWhen:"enabled",hint:"smtp.office365.com for Microsoft 365"},{key:"port",kind:"text",secret:!1,label:"Port",hint:"Left empty this is 587 (STARTTLS). 465 means implicit TLS."},{key:"user",kind:"text",secret:!1,label:"Mailbox",required:!0,requiredWhen:"enabled",hint:"The address the password belongs to. It is also the sender address."},{key:"password",kind:"password",label:"Password / app password",required:!0,requiredWhen:"enabled",hint:"If the account has multi-factor authentication, the app password Microsoft generated. In Exchange Online, SMTP AUTH is off per tenant by default and a correct password is refused too \u2014 ask IT to turn it on for that mailbox."},{key:"sender_address",kind:"text",secret:!1,label:"Sender address (optional)",hint:"Left empty, the mailbox itself is used. If you enter a different address, Exchange requires that mailbox to have been granted \u201CSend As\u201D for it; without that the send is refused."},{key:"from_name",kind:"text",secret:!1,label:"Display name",hint:"The name the recipient reads in their inbox, e.g. the name of the portal."}]},{always:!0,path:"service",group:"service",label:"The server\u2019s own key",keys:[{key:"api_key",kind:"password",label:"Service API key",hint:"Some work the server has to do in its OWN name \u2014 counting how many people answered a survey, for instance. That cannot be done with an employee\u2019s permissions, and should not be. Generate the key in the admin panel and paste it here; it carries its owner\u2019s roles, not godmin\u2019s. Left empty, this work is skipped silently."}]},{always:!0,path:"storage.smb",group:"storage",label:"SMB / CIFS share",keys:[{key:"username",kind:"text",label:"Username",required:!0},{key:"password",kind:"password",label:"Password",required:!0}]},{secret:!1,always:!0,path:"storage",group:"storage",label:"File store",keys:[{key:"provider",kind:"text",label:"Storage kind",hint:"local (the server\u2019s own disk) or smb (a corporate file server). The change takes effect immediately."}]},{secret:!1,always:!0,path:"storage.smb",group:"storage",label:"SMB / CIFS share",keys:[{key:"url",kind:"text",label:"Share address",hint:"Paste it exactly as the customer sent it: smb://server/share \u2014 the server and the share name are read from this."},{key:"domain",kind:"text",label:"Domain",hint:"The domain part when the user is written as DOMAIN\\user. Leave empty if it is not needed."},{key:"base_path",kind:"text",label:"Folder inside the share",hint:"The subfolder uploads are gathered in. Empty means the root of the share."}]},{path:"payment.providers.*",group:"payment",label:"Payment provider",keys:[{key:"apiKey",kind:"password",label:"API Key",required:!0},{key:"secretKey",kind:"password",label:"Secret Key",required:!0},{key:"webhookSecret",kind:"password",label:"Webhook Secret"}]},{path:"captcha",group:"captcha",label:"Captcha",keys:[{key:"secretKey",kind:"password",label:"Secret Key"}]},{secret:!1,path:"authentication",group:"portal",label:"Portal address",keys:[{key:"trustedAppOrigins",kind:"list",label:"Trusted origins",required:!0,hint:"The address(es) the portal is installed at. Password-reset and SSO return links are built from these. Wildcard: *.company.com"}]},{secret:!1,always:!0,path:"email",group:"email",label:"Email provider",keys:[{key:"provider",kind:"text",label:"Provider to use",hint:"azure or gmail. Left empty, whichever provider is switched on is used."}]},{secret:!1,always:!0,path:"email.azure",group:"email",label:"Azure Communication Services",keys:[{key:"enabled",kind:"boolean",label:"Azure email enabled",hint:"Entering the connection string is not enough on its own \u2014 sending is turned on by this switch."},{key:"sender_address",kind:"text",label:"Sender address"},{key:"from_name",kind:"text",label:"Sender name",hint:"The name the recipient sees in their inbox in place of the address. Empty means the address shows."}]},{secret:!1,always:!0,path:"email.gmail",group:"email",label:"Gmail (service account)",keys:[{key:"enabled",kind:"boolean",label:"Gmail email enabled"},{key:"from_email",kind:"text",label:"Sender address"},{key:"from_name",kind:"text",label:"Sender name",hint:"The name the recipient sees in their inbox in place of the address. Empty means the address shows."}]}]});import{and as and14,eq as eq18}from"drizzle-orm";class SecretsStore{db;resolveTable;masterKey;constructor(deps){this.db=deps.db,this.resolveTable=deps.resolveTable,this.masterKey=deps.masterKey}table(schemaName){return this.resolveTable(SECRETS_TABLE,schemaName)}async loadAll(schemaName){let values=new Map,failed2=[],table=this.table(schemaName);if(!table)return{values,failed:failed2,tableMissing:!0};let rows;try{rows=(await this.db.select().from(table).where(eq18(col2(table,"isActive"),!0))).map(secretRowOf)}catch(error){if(isMissingTableError(error))return{values,failed:failed2,tableMissing:!0};throw error}for(let row of rows)try{values.set(cacheKeyOf(row.scope,row.key),decryptSecret(row.valueEnc,this.masterKey))}catch{failed2.push(`${row.scope}.${row.key}`)}return{values,failed:failed2}}async list(schemaName){let table=this.table(schemaName);if(!table)return[];try{return(await this.db.select().from(table)).map(secretRowOf).filter((r)=>r.isActive!==!1).map(rowToMeta)}catch(error){if(isMissingTableError(error))return[];throw error}}async get(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return null;let row=(await this.db.select().from(table).where(and14(eq18(col2(table,"scope"),scope),eq18(col2(table,"key"),key2))).limit(1))[0];return row?secretRowOf(row):null}async set(params,schemaName){let table=this.table(schemaName);if(!table)return null;let existing=await this.get(params.scope,params.key,schemaName),valueEnc=encryptSecret(params.value,this.masterKey),preview=previewOf(params.value),now2=new Date;if(existing)await this.db.update(table).set({valueEnc,previousEnc:existing.valueEnc,preview,kind:params.kind??existing.kind??"text",description:params.description??existing.description,version:(existing.version??1)+1,rotatedAt:now2,isActive:!0,updatedAt:now2,updatedBy:params.actorId??null}).where(eq18(col2(table,"id"),existing.id));else await this.db.insert(table).values({scope:params.scope,key:params.key,valueEnc,preview,kind:params.kind??"text",description:params.description??null,version:1,isActive:!0,createdBy:params.actorId??null,updatedBy:params.actorId??null});let saved=await this.get(params.scope,params.key,schemaName);return saved?rowToMeta(saved):null}async rollback(scope,key2,actorId,schemaName){let table=this.table(schemaName);if(!table)return null;let existing=await this.get(scope,key2,schemaName);if(!existing?.previousEnc)return null;let plaintext=decryptSecret(existing.previousEnc,this.masterKey),now2=new Date;await this.db.update(table).set({valueEnc:existing.previousEnc,previousEnc:existing.valueEnc,preview:previewOf(plaintext),version:(existing.version??1)+1,rotatedAt:now2,updatedAt:now2,updatedBy:actorId??null}).where(eq18(col2(table,"id"),existing.id));let saved=await this.get(scope,key2,schemaName);return saved?rowToMeta(saved):null}async remove(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return!1;let existing=await this.get(scope,key2,schemaName);if(!existing)return!1;return await this.db.delete(table).where(eq18(col2(table,"id"),existing.id)),!0}async touch(scope,key2,schemaName){let table=this.table(schemaName);if(!table)return;await this.db.update(table).set({lastUsedAt:new Date}).where(and14(eq18(col2(table,"scope"),scope),eq18(col2(table,"key"),key2)))}async reencryptAll(newMasterKey,schemaName){let table=this.table(schemaName);if(!table)return{migrated:0,failed:[]};let rows=(await this.db.select().from(table)).map(secretRowOf),failed2=[],planned=[];for(let row of rows)try{let plaintext=decryptSecret(row.valueEnc,this.masterKey),previous=row.previousEnc?encryptSecret(decryptSecret(row.previousEnc,this.masterKey),newMasterKey):null;planned.push({id:row.id,valueEnc:encryptSecret(plaintext,newMasterKey),previousEnc:previous})}catch{failed2.push(`${row.scope}.${row.key}`)}if(failed2.length>0)return{migrated:0,failed:failed2};return await this.db.transaction(async(tx)=>{for(let row of planned)await tx.update(table).set({valueEnc:row.valueEnc,previousEnc:row.previousEnc}).where(eq18(col2(table,"id"),row.id))}),this.masterKey=newMasterKey,{migrated:planned.length,failed:failed2}}}var SECRETS_TABLE="nucleusSecrets",col2,SECRET_KINDS,isSecretKind=(value)=>Object.hasOwn(SECRET_KINDS,value),secretRowOf=(source)=>{let row=rowOf(source);return{id:asText(row.id)??"",scope:asText(row.scope)??"",key:asText(row.key)??"",valueEnc:asText(row.valueEnc)??"",previousEnc:asText(row.previousEnc)??null,preview:asText(row.preview)??null,kind:asText(row.kind)??null,description:asText(row.description)??null,version:asNumber(row.version)??1,rotatedAt:asDate(row.rotatedAt)??null,lastUsedAt:asDate(row.lastUsedAt)??null,updatedAt:asDate(row.updatedAt)??null,updatedBy:asText(row.updatedBy)??null,isActive:asBoolean(row.isActive)??null}},toIso=(value)=>value?new Date(value).toISOString():null,UNDEFINED_TABLE="42P01",isMissingTableError=(error)=>{let seen=new Set,current=typeof error==="object"&&error!==null?error:void 0;while(current&&!seen.has(current)){if(seen.add(current),fieldOf(current,"code")===UNDEFINED_TABLE)return!0;let message=fieldOf(current,"message");if(typeof message==="string"&&/relation .* does not exist/i.test(message))return!0;let cause=fieldOf(current,"cause");current=typeof cause==="object"&&cause!==null?cause:void 0}return!1},rowToMeta=(row)=>({id:row.id,scope:row.scope,key:row.key,kind:row.kind!==null&&isSecretKind(row.kind)?row.kind:"text",preview:row.preview??"",description:row.description,version:row.version??1,canRollback:!!row.previousEnc,rotatedAt:toIso(row.rotatedAt),lastUsedAt:toIso(row.lastUsedAt),updatedAt:toIso(row.updatedAt),updatedBy:row.updatedBy}),cacheKeyOf=(scope,key2)=>`${scope}.${key2}`;var init_store3=__esm(()=>{init_crypto();col2=columnOf,SECRET_KINDS={text:!0,password:!0,json:!0,connection_string:!0,pem:!0,boolean:!0,list:!0}});class SecretsService{store;logger;getRedis;refreshIntervalMs;schemaName;cache=new Map;timer=null;localRevision=0;loaded=!1;tableMissing=!1;warnedTableMissing=!1;constructor(deps){this.store=deps.store,this.logger=deps.logger,this.getRedis=deps.getRedis,this.refreshIntervalMs=deps.refreshIntervalMs??DEFAULT_REFRESH_MS,this.schemaName=deps.schemaName}async start(){if(await this.refresh(),this.timer)return;let timer=setInterval(()=>{this.refreshIfStale()},this.refreshIntervalMs);timer.unref?.(),this.timer=timer}stop(){if(this.timer)clearInterval(this.timer);this.timer=null}isReady(){return this.loaded}size(){return this.cache.size}isTableMissing(){return this.tableMissing}async refresh(){try{let{values,failed:failed2,tableMissing}=await this.store.loadAll(this.schemaName);if(tableMissing){if(this.tableMissing=!0,!this.warnedTableMissing)this.warnedTableMissing=!0,this.logger.warn("[Secrets] nucleus_secrets does not exist yet \u2014 env and literal values resolve normally; "+"the store activates automatically once the schema sync creates it");return}if(this.tableMissing)this.tableMissing=!1,this.warnedTableMissing=!1,this.logger.info("[Secrets] nucleus_secrets is now available \u2014 credential store active");if(this.cache=values,this.loaded=!0,failed2.length>0)this.logger.error("[Secrets] Credentials failed to decrypt and were skipped",{slots:failed2,hint:"master key changed without re-encrypting \u2014 POST /secrets/reencrypt with the old key"})}catch(error){this.logger.warn("[Secrets] Refresh failed, keeping cached values",{error:error instanceof Error?error.message:String(error)})}}async refreshIfStale(){let redis=this.getRedis?.();if(!redis)return this.refresh();try{let result=await redis.read(REVISION_KEY),remote=Number(result.data??0);if(Number.isFinite(remote)&&remote===this.localRevision&&this.loaded)return;await this.refresh(),this.localRevision=Number.isFinite(remote)?remote:this.localRevision}catch{await this.refresh()}}async bumpRevision(){let redis=this.getRedis?.();if(!redis)return;try{let next=Date.now();this.localRevision=next,await redis.create(REVISION_KEY,next)}catch{}}get(scope,key2){return this.cache.get(cacheKeyOf(scope,key2))}has(scope,key2){return this.cache.has(cacheKeyOf(scope,key2))}resolve(scope,key2,configValue){let fromDb=this.cache.get(cacheKeyOf(scope,key2));if(fromDb)return{value:fromDb,source:"db"};if(configValue){let fromEnv=process.env[configValue];if(fromEnv)return{value:fromEnv,source:"env"};if(looksLikeEnvName(configValue))return{value:void 0,source:"missing"};return{value:configValue,source:"literal"}}return{value:void 0,source:"missing"}}value(scope,key2,configValue){return this.resolve(scope,key2,configValue).value}listValue(scope,key2,configValue){let fallback=Array.isArray(configValue)?configValue.join(","):configValue,raw=this.value(scope,key2,fallback);if(!raw)return Array.isArray(configValue)?configValue:[];return raw.split(/[,;\n\r]+/).map((entry)=>entry.trim()).filter(Boolean)}flag(scope,key2,configValue){let raw=this.get(scope,key2);if(raw===void 0)return configValue===!0;return raw==="true"||raw==="1"}liveConfig(scope,node,keys){let live={...node};for(let key2 of keys){let declared=fieldOf(node,key2),configValue=typeof declared==="string"?declared:void 0;Object.defineProperty(live,key2,{get:()=>this.resolve(scope,key2,configValue).value,enumerable:!0,configurable:!0})}return live}async describe(config,slots){let discovered=slots??discoverSlots(config),stored=await this.store.list(this.schemaName),byId=new Map(stored.map((s)=>[cacheKeyOf(s.scope,s.key),s]));return discovered.map((slot)=>{let id=cacheKeyOf(slot.scope,slot.key),record=byId.get(id),{value,source}=this.resolve(slot.scope,slot.key,slot.configValue),envName=looksLikeEnvName(slot.configValue)?slot.configValue:void 0,gate=slot.requiredWhen?this.flag(slot.scope,slot.requiredWhen,configFlagAt(config,slot.scope,slot.requiredWhen)):!0;return{...slot,required:slot.required&&gate,configValue:envName,source,value:slot.secret?void 0:value,preview:slot.secret?source==="db"&&record?record.preview:value?previewOf(value):"":value??"",envName,version:record?.version,rotatedAt:record?.rotatedAt??null,canRollback:record?.canRollback??!1}})}async list(){return this.store.list(this.schemaName)}async set(params){let saved=await this.store.set(params,this.schemaName);return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential stored",{scope:params.scope,key:params.key,version:saved?.version,actor:params.actorId}),saved}async rollback(scope,key2,actorId){let saved=await this.store.rollback(scope,key2,actorId,this.schemaName);if(!saved)return null;return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential rolled back",{scope,key:key2,actor:actorId}),saved}async remove(scope,key2,actorId){if(!await this.store.remove(scope,key2,this.schemaName))return!1;return await this.refresh(),await this.bumpRevision(),this.logger.info("[Secrets] Credential removed",{scope,key:key2,actor:actorId}),!0}async reencryptAll(newMasterKey){let result=await this.store.reencryptAll(newMasterKey,this.schemaName);return await this.refresh(),await this.bumpRevision(),result}}var REVISION_KEY="nucleus:secrets:revision",DEFAULT_REFRESH_MS=30000,configFlagAt=(config,scope,key2)=>{let node=config;for(let segment of scope.split(".")){if(typeof node!=="object"||node===null)return;node=fieldOf(node,segment)}if(typeof node!=="object"||node===null)return;let value=fieldOf(node,key2);if(typeof value==="boolean")return value;if(typeof value==="string")return value==="true"||value==="1";return};var init_SecretsService=__esm(()=>{init_crypto();init_registry();init_store3()});var resolveMasterKey=(configured)=>{if(configured){let fromEnv=process.env[configured];if(fromEnv)return fromEnv;if(!/^[A-Z][A-Z0-9_]{2,}$/.test(configured))return configured}return process.env.NUCLEUS_SECRETS_KEY||void 0};var init_Secrets=__esm(()=>{init_crypto();init_registry();init_SecretsService();init_store3()});var exports_schema={};__export(exports_schema,{validateIdentifier:()=>validateIdentifier,reasonOf:()=>reasonOf,isAlreadyPresent:()=>isAlreadyPresent,isAdditiveStatement:()=>isAdditiveStatement,ensureSchemaExists:()=>ensureSchemaExists,dropsSchemaObject:()=>dropsSchemaObject,applySchemaPush:()=>applySchemaPush});import{sql as sql15}from"drizzle-orm";function reasonOf(error){if(!(error instanceof Error))return String(error);let chain=errorChain(error),parts=[];for(let link of chain){let detail=fieldOf(link,"detail"),hint=fieldOf(link,"hint"),code=fieldOf(link,"code"),message=link.message.startsWith("Failed query:")&&chain.length>1?"":link.message;parts.push(message,detail?`detail: ${String(detail)}`:"",hint?`hint: ${String(hint)}`:"",code?`code: ${String(code)}`:"")}return parts.filter(Boolean).join(" \u2014 ")}function errorChain(error){let chain=[],current=error;while(current&&!chain.includes(current)&&chain.length<5)chain.push(current),current=current.cause instanceof Error?current.cause:void 0;return chain}function isAlreadyPresent(error){if(!(error instanceof Error))return!1;return errorChain(error).some((link)=>{let code=fieldOf(link,"code");return typeof code==="string"&&ALREADY_PRESENT.has(code)})}var validateIdentifier=(name)=>{if(!name||name.length>63)throw Error(`Invalid identifier: must be 1-63 characters, got ${name.length}`);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name))throw Error(`Invalid identifier: "${name}" contains unsafe characters`);return name},ensureSchemaExists=async(db,schemaName)=>{let safeName=validateIdentifier(schemaName),found=await db.execute(sql15`select 1 from pg_catalog.pg_namespace where nspname = ${safeName} limit 1`);if(rowCountOf(found)>0)return;await db.execute(sql15.raw(`CREATE SCHEMA IF NOT EXISTS "${safeName}"`))},rowCountOf=(result)=>{if(Array.isArray(result))return result.length;return"rows"in result&&Array.isArray(result.rows)?result.rows.length:0},ADDITIVE_PREFIXES,ALREADY_PRESENT,isAdditiveStatement=(statement)=>{let normalized=statement.trim().toUpperCase();if(/^ALTER TABLE .+ ADD COLUMN/.test(normalized))return!0;if(/^ALTER TABLE .+ ALTER COLUMN .+ SET DEFAULT /.test(normalized))return!0;if(/^ALTER TABLE .+ ADD CONSTRAINT /.test(normalized))return!0;if(/^ALTER TABLE .+ ALTER COLUMN .+ DROP NOT NULL$/.test(normalized))return!0;return ADDITIVE_PREFIXES.some((prefix)=>normalized.startsWith(prefix))},dropsSchemaObject=(statement)=>{let normalized=statement.trim().toUpperCase();return/^DROP INDEX /.test(normalized)||/^ALTER TABLE .+ DROP CONSTRAINT /.test(normalized)||/^DROP SEQUENCE /.test(normalized)},withoutKeptDrops=(push,opts)=>{let keep=opts.keep??dropsSchemaObject,kept=push.statementsToExecute.filter(keep);if(kept.length===0)return push;opts.logger.warn(`[Schema] Kept ${kept.length} index/constraint/sequence object(s) in "${opts.schemaName}" ${opts.reason??"that the table model does not declare (database.keepUndeclaredObjects). Declare them in the model, or drop them by hand if they are really gone."}`,{statements:kept});let{execute}=opts;if(!execute)return opts.logger.error(`[Schema] The schema push for "${opts.schemaName}" was not applied: keeping undeclared objects needs a statement executor to run the rest of it.`),null;let rest=push.statementsToExecute.filter((statement)=>!keep(statement));return{...push,statementsToExecute:rest,apply:async()=>{for(let statement of rest)await execute(statement)}}},applySchemaPush=async(planned,opts)=>{let{schemaName,allowDataLoss,logger:logger2,execute}=opts,owned=opts.keepObject?withoutKeptDrops(planned,{schemaName,logger:logger2,execute,keep:opts.keepObject,reason:"owned by a migration of the ledger (database.migrations)."}):planned,push=owned&&opts.keepUndeclaredObjects===!0&&!allowDataLoss?withoutKeptDrops(owned,opts):owned;if(!push)return!1;if(push.hasDataLoss&&!allowDataLoss){let additive=push.statementsToExecute.filter(isAdditiveStatement),blocked=push.statementsToExecute.filter((s)=>!isAdditiveStatement(s));if(logger2.error(`[Schema] Destructive changes detected for schema "${schemaName}" but database.allowDataLoss is not enabled \u2014 ${blocked.length} statement(s) skipped. Set database.allowDataLoss: true to apply them.`,{warnings:push.warnings,statements:blocked}),additive.length===0||!execute)return!1;let applied=0;for(let statement of additive)try{await execute(statement),applied++}catch(error){logger2.warn(`[Schema] ${schemaName}: ${statement} \u2014 ${reasonOf(error)}`)}return logger2.info(`[Schema] Applied ${applied}/${additive.length} additive statement(s) for "${schemaName}" despite the destructive changes being held back`),applied>0}if(push.hasDataLoss)logger2.warn(`[Schema] Applying destructive changes to schema "${schemaName}" (database.allowDataLoss=true)`,{warnings:push.warnings});try{return await push.apply(),!0}catch(error){let message=error instanceof Error?error.message:String(error);if(!execute)return logger2.error(`[Schema] Could not apply schema changes to "${schemaName}": ${message}. The database does not match this build, so queries against the missing columns will fail.`,{warnings:push.warnings}),!1;logger2.error(`[Schema] The schema push for "${schemaName}" failed as a batch (${message}) \u2014 retrying its ${push.statementsToExecute.length} statement(s) one at a time so one bad statement does not hold back the rest.`);let applied=0,alreadyPresent=0,failures=[];for(let statement of push.statementsToExecute)try{await execute(statement),applied++}catch(statementError){if(isAlreadyPresent(statementError)){alreadyPresent++;continue}failures.push(statement),logger2.error(`[Schema] ${schemaName}: ${statement} \u2014 ${reasonOf(statementError)}`)}if(alreadyPresent>0)logger2.info(`[Schema] ${alreadyPresent} statement(s) for "${schemaName}" found their object already in place (applied before the batch stopped).`);if(failures.length>0)logger2.error(`[Schema] ${failures.length} of ${push.statementsToExecute.length} statement(s) could not be applied to "${schemaName}". Any query touching what they would have created will fail until they are.`);return applied>0||alreadyPresent>0}};var init_schema=__esm(()=>{ADDITIVE_PREFIXES=["CREATE TABLE IF NOT EXISTS","CREATE TABLE","CREATE SCHEMA IF NOT EXISTS","CREATE SCHEMA","CREATE INDEX IF NOT EXISTS","CREATE INDEX","CREATE UNIQUE INDEX IF NOT EXISTS","CREATE UNIQUE INDEX","CREATE TYPE","DO $$"];ALREADY_PRESENT=new Set(["42P07","42P06","42710","42701","42723"])});var rowToTenantRecord=(source)=>{let row=rowOf(source);return{id:String(row.id||""),subdomain:String(row.subdomain||""),schemaName:String(row.schemaName||row.schema_name||""),companyId:String(row.companyId||row.company_id||""),companyName:row.companyName!=null?String(row.companyName):row.company_name!=null?String(row.company_name):null,godAdminEmail:String(row.godAdminEmail||row.god_admin_email||""),status:parseStatus(row.status),plan:row.plan!=null?String(row.plan):null,domain:row.domain!=null?String(row.domain):null,settings:parseJsonbToConfig(row.settings),trustedSources:parseTrustedSources(row.trustedSources||row.trusted_sources),maxUsers:row.maxUsers!=null?Number(row.maxUsers):row.max_users!=null?Number(row.max_users):null,provisionedAt:row.provisionedAt!=null?String(row.provisionedAt):row.provisioned_at!=null?String(row.provisioned_at):null,suspendedAt:row.suspendedAt!=null?String(row.suspendedAt):row.suspended_at!=null?String(row.suspended_at):null,suspendedReason:row.suspendedReason!=null?String(row.suspendedReason):row.suspended_reason!=null?String(row.suspended_reason):null}},rowToFeatureRecord=(source,parseConfig)=>{let row=rowOf(source);return{id:String(row.id||""),tenantId:String(row.tenantId||row.tenant_id||""),featureName:String(row.featureName||row.feature_name||""),enabled:Boolean(row.enabled),featureConfig:parseConfig(row.config)}},parseStatus=(value)=>{let valid=["provisioning","active","suspended","archived"],str2=String(value||"provisioning");return valid.find((status)=>status===str2)??"provisioning"},parseJsonbToConfig=(value)=>{if(!value||typeof value!=="object")return{};let result={};for(let[k,v]of Object.entries(rowOf(value)))if(typeof v==="string"||typeof v==="number"||typeof v==="boolean")result[k]=v;return result},parseTrustedSources=(value)=>{if(!Array.isArray(value))return[];return value.map((item)=>{let entry=typeof item==="object"&&item!==null?rowOf(item):{};return{allowHeaderAuth:entry.allowHeaderAuth===!0||entry.allow_header_auth===!0,allowedIps:textEntries(entry.allowedIps||entry.allowed_ips),allowedServices:textEntries(entry.allowedServices||entry.allowed_services)}})},textEntries=(value)=>Array.isArray(value)?value.filter((entry)=>typeof entry==="string"):void 0,normalizeHost=(host)=>{return((host||"").split(":")[0]||"").toLowerCase().replace(/\.$/,"")},extractSubdomain=(host)=>{let hostWithoutPort=host.split(":")[0]||"";if(hostWithoutPort==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(hostWithoutPort))return null;let parts=hostWithoutPort.split(".");if(parts.length<3)return null;let subdomain=parts[0]||"";if(!subdomain||subdomain==="www")return null;return subdomain},toIPv4Octets=(address)=>{let bare=address.startsWith("::ffff:")?address.slice(7):address;if(bare.includes(":"))return null;let parts=bare.split(".");if(parts.length!==4)return null;let[a,b,c,d]=parts.map((part)=>/^\d{1,3}$/.test(part)?Number(part):Number.NaN);if(a===void 0||b===void 0||c===void 0||d===void 0)return null;let octets=[a,b,c,d];return octets.every((o)=>Number.isInteger(o)&&o>=0&&o<=255)?octets:null},isIpInCidr=(ip,cidr)=>{let[cidrIp,prefixStr]=cidr.split("/");if(!cidrIp||!prefixStr)return!1;let prefix=Number.parseInt(prefixStr,10);if(Number.isNaN(prefix)||prefix<0||prefix>32)return!1;let ipParts=toIPv4Octets(ip),cidrParts=toIPv4Octets(cidrIp);if(!ipParts||!cidrParts)return!1;let toNumber=([a,b,c,d])=>(a<<24|b<<16|c<<8|d)>>>0,ipNum=toNumber(ipParts),cidrNum=toNumber(cidrParts),mask=prefix===0?0:~((1<<32-prefix)-1)>>>0;return(ipNum&mask)===(cidrNum&mask)},isTrustedSource=(tenant,request,authMode,fallbackSources,vettedClientIp)=>{let ownSources=tenant.trustedSources,trustedSources=Array.isArray(ownSources)&&ownSources.length>0?ownSources:fallbackSources;if(!trustedSources||!Array.isArray(trustedSources)||trustedSources.length===0)return!1;let clientIp=vettedClientIp?.trim()||"",serviceId=request.headers.get("x-service-id")||"";for(let source of trustedSources){if(!source.allowHeaderAuth)continue;if(source.allowedIps&&source.allowedIps.length>0){if(source.allowedIps.some((allowedIp)=>{if(allowedIp.includes("/"))return isIpInCidr(clientIp,allowedIp);return clientIp===allowedIp}))return!0}if(source.allowedServices&&source.allowedServices.length>0){if(source.allowedServices.includes(serviceId))return!0}}return!1},pickRequestHost=(request,hostHeader,hostHeaderTrusted)=>{if(hostHeader&&hostHeaderTrusted){let forwarded=request.headers.get(hostHeader)?.split(",")[0]?.trim();if(forwarded)return forwarded}return request.headers.get("host")||new URL(request.url).host||""};var init_helpers=()=>{};import{pgSchema}from"drizzle-orm/pg-core";function createProvisionedSchemas(deps){let cache=new Map;return(schemaName)=>{let tenant=deps.tenantOf(schemaName);if(!tenant||!PROVISIONED_STATUSES.has(tenant.status))return;let cached=cache.get(schemaName);if(cached)return cached;let schema=pgSchema(schemaName),built={tables:deps.createTables(schema),relations:deps.createRelations?deps.createRelations(schema):{}};return cache.set(schemaName,built),built}}function hostTablesResolver(mainSchema,mainTables,source){return(schemaName)=>{if(schemaName===mainSchema)return mainTables;return source()?.getProvisionedSchema(schemaName)?.tables}}function hostRelationsResolver(mainSchema,mainRelations,source){return(schemaName)=>{if(schemaName===mainSchema)return mainRelations;return source()?.getProvisionedSchema(schemaName)?.relations??{}}}var PROVISIONED_STATUSES;var init_provisionedSchemas=__esm(()=>{PROVISIONED_STATUSES=new Set(["provisioning","active","suspended","archived"])});async function withDeadline(promise,timeoutMs,message){promise.catch(()=>{});let timer,deadline=new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(Error(message)),timeoutMs)});try{return await Promise.race([promise,deadline])}finally{if(timer)clearTimeout(timer)}}var exports_schemaReconcile={};__export(exports_schemaReconcile,{undeclaredTables:()=>undeclaredTables,setDefaultStatement:()=>setDefaultStatement,renderDefaultLiteral:()=>renderDefaultLiteral,reconcileMissingColumns:()=>reconcileMissingColumns,readActualSchemaDetailed:()=>readActualSchemaDetailed,readActualSchema:()=>readActualSchema,planRepair:()=>planRepair,findDrift:()=>findDrift,expectedFromTables:()=>expectedFromTables,describeRepair:()=>describeRepair,createMissingTables:()=>createMissingTables,addColumnStatement:()=>addColumnStatement});import{getTableColumns as getTableColumns6,sql as sql16}from"drizzle-orm";function findDrift(expected,actual,actualDefaults){let missingTables=[],missingColumns=[],columnsMissingDefault=[];for(let table of expected){let have=actual[table.name];if(!have){missingTables.push(table.name);continue}let haveDefault=actualDefaults?.[table.name];for(let column of table.columns){if(!have.has(column.name)){missingColumns.push({table:table.name,column});continue}if(haveDefault&&column.hasDefault&&column.defaultLiteral!==void 0&&!haveDefault.has(column.name))columnsMissingDefault.push({table:table.name,column})}}return{missingTables,missingColumns,columnsMissingDefault}}function addColumnStatement(schema,table,column){if(column.notNull&&!column.hasDefault)return null;return[`alter table "${schema}"."${table}"`,`add column if not exists "${column.name}" ${column.sqlType}`].join(" ")}function setDefaultStatement(schema,table,column){if(column.defaultLiteral===void 0)return null;return`alter table "${schema}"."${table}" alter column "${column.name}" set default ${column.defaultLiteral}`}function planRepair(schema,drift){let statements=[],unsafe=[];for(let{table,column}of drift.missingColumns){let statement=addColumnStatement(schema,table,column);if(statement)statements.push(statement);else unsafe.push({table,column:column.name,why:"declared NOT NULL with no default, and the table already has rows to fill"})}for(let{table,column}of drift.columnsMissingDefault){let statement=setDefaultStatement(schema,table,column);if(statement)statements.push(statement)}return{statements,unsafe,missingTables:drift.missingTables,createdTables:[],undeclaredTables:[]}}function undeclaredTables(expected,actual){let declared=new Set(expected.map((t)=>t.name));return Object.keys(actual).filter((name)=>!declared.has(name)).sort()}function isAlreadyExists(error){if(typeof error==="object"&&error!==null&&"code"in error){let code=error.code;if(typeof code==="string"&&ALREADY_EXISTS.has(code))return!0}return/already exists/i.test(errorMessage(error))}async function createMissingTables(options){let{run,tables,missing,schemaObject,logger:logger2,timeoutMs=60000}=options;if(missing.length===0)return{applied:0,errors:[]};let wanted=new Set(missing),imports={};for(let[key2,table]of Object.entries(tables)){if(!table||typeof table!=="object")continue;let name=tableNameOf(table);if(name&&wanted.has(name))imports[key2]=table}if(schemaObject)imports.__nucleusSchema=schemaObject;let statements;try{let{generateDrizzleJson,generateMigration}=await import("drizzle-kit/api"),realExit=process.exit;try{process.exit=(code)=>{throw Error(`drizzle-kit called process.exit(${code??0}) while generating table DDL`)},statements=await withDeadline(generateMigration(generateDrizzleJson({}),generateDrizzleJson(imports)),timeoutMs,`generating CREATE TABLE statements did not finish within ${timeoutMs}ms`)}finally{process.exit=realExit}}catch(error){let message=error instanceof Error?error.message:String(error);return logger2.error(`[Schema] CREATE TABLE statements could not be generated: ${message}`),{applied:0,errors:[message]}}let applied=0,errors=[];for(let statement of statements)try{await run(statement),applied+=1}catch(error){if(isAlreadyExists(error))continue;let message=error instanceof Error?error.message:String(error);errors.push(message),logger2.error(`[Schema] could not apply generated DDL: ${statement} \u2014 ${message}`)}return{applied,errors}}function describeRepair(plan,applied){let lines=[];if(applied>0)lines.push(`[Schema] The push applied nothing, so ${applied} missing column(s) were added directly. `+"This is additive only \u2014 nothing was dropped or altered.");if(plan.createdTables.length>0)lines.push(`[Schema] ${plan.createdTables.length} table(s) the push did not create were created directly: ${plan.createdTables.join(", ")}. Verified present in the database afterwards, not assumed from the statements that ran.`);if(plan.missingTables.length>0){if(lines.push(`[Schema] ${plan.missingTables.length} table(s) the code expects still do not exist: ${plan.missingTables.join(", ")}. Every read of these will fail. The additive repair tried `+"and could not create them \u2014 this needs a human."),plan.undeclaredTables.length>0)lines.push(`[Schema] The push is ambiguous because the database has ${plan.undeclaredTables.length} table(s) the model does not declare: ${plan.undeclaredTables.join(", ")}. drizzle-kit cannot tell a new table from a rename of one of these, and cannot ask without a TTY. Drop the stale one, or declare it, and the push stops aborting.`)}for(let item of plan.unsafe)lines.push(`[Schema] "${item.table}"."${item.column}" could not be added: ${item.why}. Give the column a default, or add it by hand with a backfill.`);return lines}function expectedFromTables(tables){let out=[];for(let value of Object.values(tables)){let table=asTable(value);if(!table)continue;let columns;try{columns=getTableColumns6(table)}catch{continue}if(!columns)continue;let list3=Object.values(columns),name=tableNameOf(table);if(!name||list3.length===0)continue;out.push({name,columns:list3.map((column)=>({name:column.name,sqlType:typeof column.getSQLType==="function"?column.getSQLType():"text",notNull:column.notNull===!0,hasDefault:column.hasDefault===!0,defaultLiteral:renderDefaultLiteral(column.default)}))})}return out}function renderDefaultLiteral(value){if(typeof value==="string")return`'${value.replace(/'/g,"''")}'`;if(typeof value==="number")return Number.isFinite(value)?String(value):void 0;if(typeof value==="boolean")return value?"true":"false";return}function tableNameOf(table){for(let key2 of Object.getOwnPropertySymbols(table))if(String(key2).includes("Name")&&!String(key2).includes("Schema")){let value=Reflect.get(table,key2);if(typeof value==="string"&&value.length>0)return value}return null}async function readActualSchema(execute,schema){return(await readActualSchemaDetailed(execute,schema)).columns}async function readActualSchemaDetailed(execute,schema){let result=await execute(`select table_name, column_name, column_default from information_schema.columns where table_schema = '${schema.replace(/'/g,"''")}'`),rows=Array.isArray(result)?result:result.rows??[],columns={},withDefault={};for(let source of rows){let row=rowOf(source),tableName=asText(row.table_name),columnName=asText(row.column_name);if(!tableName||!columnName)continue;if(columns[tableName]??=new Set,columns[tableName]?.add(columnName),withDefault[tableName]??=new Set,row.column_default!==null&&row.column_default!==void 0)withDefault[tableName]?.add(columnName)}return{columns,withDefault}}async function reconcileMissingColumns(options){let{db,schema,tables,logger:logger2,schemaObject}=options,run=(statement)=>db.execute(sql16.raw(statement));try{let expected=expectedFromTables(tables);if(expected.length===0)return null;let{columns:actual,withDefault}=await readActualSchemaDetailed(run,schema),drift=findDrift(expected,actual,withDefault),plan=planRepair(schema,drift);if(plan.undeclaredTables=undeclaredTables(expected,actual),drift.missingTables.length>0){await createMissingTables({run,tables,missing:drift.missingTables,schemaObject,logger:logger2});let after=await readActualSchema(run,schema);plan.createdTables=drift.missingTables.filter((name)=>after[name]),plan.missingTables=drift.missingTables.filter((name)=>!after[name])}let applied=0;for(let statement of plan.statements)try{await run(statement),applied+=1}catch(error){logger2.error(`[Schema] could not add a missing column: ${statement} \u2014 ${error instanceof Error?error.message:String(error)}`)}for(let line of describeRepair(plan,applied))if(plan.missingTables.length>0||plan.unsafe.length>0)logger2.error(line);else logger2.info(line);return{applied,plan}}catch(error){return logger2.error(`[Schema] the additive repair could not run: ${error instanceof Error?error.message:String(error)}`),null}}var ALREADY_EXISTS;var init_schemaReconcile=__esm(()=>{ALREADY_EXISTS=new Set(["42P06","42P07","42710","42723","23505"])});var ambiguousColumnTables=(expected,actual)=>{let found=[];for(let table of expected){let have=actual[table.name];if(!have)continue;let declared=new Set(table.columns.map((column)=>column.name)),added=table.columns.filter((column)=>!have.has(column.name)).map((c)=>c.name),extra=[...have].filter((name)=>!declared.has(name));if(added.length>0&&extra.length>0)found.push({table:table.name,added,extra})}return found};var trapDepth=0,realExit=null,withExitTrapped=async(work)=>{if(trapDepth===0)realExit=process.exit,process.exit=(code)=>{throw Error(`drizzle-kit called process.exit(${code??0}) during the schema push`)};trapDepth+=1;try{return await work()}finally{if(trapDepth-=1,trapDepth===0&&realExit)process.exit=realExit,realExit=null}};import{drizzle as drizzle3}from"drizzle-orm/node-postgres";import{Pool as Pool2}from"pg";async function withPushDb(db,schemaName,logger2,work,openPool=(config)=>new Pool2(config)){let config=pushPoolConfig(db);if(!config)return logger2.warn(`[Schema] ${schemaName}: the connection settings of the database handle cannot be read; the push uses the host pool and its connection timeout.`),work(db,!1);let pool=openPool(config);pool.on("error",(error)=>{logger2.warn(`[Schema] ${schemaName}: push pool connection error \u2014 ${reasonOf(error)}`)});try{return await work(drizzle3(pool),!0)}finally{await pool.end().catch((error)=>{logger2.warn(`[Schema] ${schemaName}: push pool did not close cleanly \u2014 ${reasonOf(error)}`)})}}var PUSH_POOL_MAX=4,pushPoolConfig=(db)=>{let client=Reflect.get(db,"$client");if(!(client instanceof Pool2))return null;let{options}=client;if(!options.connectionString&&!options.host&&!options.database)return null;return{...options,connectionTimeoutMillis:0,max:PUSH_POOL_MAX}};var init_pushPool=__esm(()=>{init_schema()});import{sql as sql17}from"drizzle-orm";import{PgDialect}from"drizzle-orm/pg-core";function keyOrderedIntrospection(db){let dialect=new PgDialect;return Object.create(db,{execute:{value:async(query)=>{let result=await db.execute(query),text3=dialect.sqlToQuery(query).sql,target=TABLE_OF_QUERY.exec(text3);if(!target||!text3.includes("constraint_column_usage"))return result;let keys=await uniqueKeyOrder(db,unquote(target[2]??""),unquote(target[1]??""));return{...result,rows:reordered(rowsOf2(result),keys)}}}})}var TABLE_OF_QUERY,unquote=(value)=>value.replace(/''/g,"'"),rowsOf2=(result)=>("rows"in result)&&Array.isArray(result.rows)?result.rows:[],uniqueKeyOrder=async(db,schemaName,tableName)=>{let result=await db.execute(sql17`select c.conname as name, a.attname as col
|
|
133
133
|
from pg_catalog.pg_constraint c
|
|
134
134
|
join pg_catalog.pg_class t on t.oid = c.conrelid
|
|
135
135
|
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
|
@@ -59,6 +59,7 @@ export type ParentMessage = Static<typeof ParentMessageSchema>;
|
|
|
59
59
|
export declare const FrameMessageSchema: import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TObject<{
|
|
60
60
|
type: import("@sinclair/typebox").TLiteral<"ready">;
|
|
61
61
|
recordingId: import("@sinclair/typebox").TString;
|
|
62
|
+
preparing: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TBoolean>;
|
|
62
63
|
channel: import("@sinclair/typebox").TLiteral<"nucleus.replay">;
|
|
63
64
|
version: import("@sinclair/typebox").TLiteral<1>;
|
|
64
65
|
nonce: import("@sinclair/typebox").TString;
|
|
@@ -104,6 +105,14 @@ export declare const FrameMessageSchema: import("@sinclair/typebox").TUnion<[imp
|
|
|
104
105
|
channel: import("@sinclair/typebox").TLiteral<"nucleus.replay">;
|
|
105
106
|
version: import("@sinclair/typebox").TLiteral<1>;
|
|
106
107
|
nonce: import("@sinclair/typebox").TString;
|
|
108
|
+
}>, import("@sinclair/typebox").TObject<{
|
|
109
|
+
type: import("@sinclair/typebox").TLiteral<"skipped">;
|
|
110
|
+
stepId: import("@sinclair/typebox").TString;
|
|
111
|
+
actionIndex: import("@sinclair/typebox").TInteger;
|
|
112
|
+
reason: import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TLiteral<"target_timeout">, import("@sinclair/typebox").TLiteral<"target_unsupported">, import("@sinclair/typebox").TLiteral<"option_not_found">, import("@sinclair/typebox").TLiteral<"navigate_failed">, import("@sinclair/typebox").TLiteral<"action_error">, import("@sinclair/typebox").TLiteral<"step_unknown">]>;
|
|
113
|
+
channel: import("@sinclair/typebox").TLiteral<"nucleus.replay">;
|
|
114
|
+
version: import("@sinclair/typebox").TLiteral<1>;
|
|
115
|
+
nonce: import("@sinclair/typebox").TString;
|
|
107
116
|
}>, import("@sinclair/typebox").TObject<{
|
|
108
117
|
type: import("@sinclair/typebox").TLiteral<"unanswered">;
|
|
109
118
|
key: import("@sinclair/typebox").TString;
|
|
@@ -78,10 +78,11 @@ const strict = {
|
|
|
78
78
|
}, strict)
|
|
79
79
|
]);
|
|
80
80
|
/** What the frame sends to the embedding page. */ export const FrameMessageSchema = Type.Union([
|
|
81
|
-
Type.Object({
|
|
81
|
+
/** `preparing` means the frame is still rebuilding the state before its start chapter: it heard the hello, play waits. */ Type.Object({
|
|
82
82
|
...envelope,
|
|
83
83
|
type: Type.Literal('ready'),
|
|
84
|
-
recordingId: id
|
|
84
|
+
recordingId: id,
|
|
85
|
+
preparing: Type.Optional(Type.Boolean())
|
|
85
86
|
}, strict),
|
|
86
87
|
Type.Object({
|
|
87
88
|
...envelope,
|
|
@@ -117,6 +118,18 @@ const strict = {
|
|
|
117
118
|
at: ms,
|
|
118
119
|
playing: Type.Boolean()
|
|
119
120
|
}, strict),
|
|
121
|
+
/**
|
|
122
|
+
* An action the tape played on without (`skipFailedSteps`): the target never appeared, a choice was missing or the
|
|
123
|
+
* action threw. `actionIndex` is -1 when a prelude dropped the whole step. The player counts them.
|
|
124
|
+
*/ Type.Object({
|
|
125
|
+
...envelope,
|
|
126
|
+
type: Type.Literal('skipped'),
|
|
127
|
+
stepId: id,
|
|
128
|
+
actionIndex: Type.Integer({
|
|
129
|
+
minimum: -1
|
|
130
|
+
}),
|
|
131
|
+
reason: FailureReasonSchema
|
|
132
|
+
}, strict),
|
|
120
133
|
/** A call no recorded answer covered (`replay_unanswered`): the audit fails on any. */ Type.Object({
|
|
121
134
|
...envelope,
|
|
122
135
|
type: Type.Literal('unanswered'),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nucleus-core-ts",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.260",
|
|
4
4
|
"description": "Production-ready, enterprise-grade TypeScript framework for building multi-tenant APIs",
|
|
5
5
|
"author": "Hidayet Can Özcan <hidayetcan@gmail.com>",
|
|
6
6
|
"license": "SEE LICENSE IN LICENSE",
|