@aiquants/vault-host 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AI Quants / fehde-k
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,249 @@
1
- # Temporary Holding Version
1
+ # @aiquants/vault-host
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The whole of a vault application, assembled from the vault database's connection and the environment: the vault
4
+ ([`@aiquants/vault-core`](../vault-core/README.md) over [`@aiquants/vault-drizzle`](../vault-drizzle/README.md)), its
5
+ screens ([`@aiquants/vault-react-router`](../vault-react-router/README.md)), the Google sign-in
6
+ ([`@aiquants/auth-react-router`](../auth-react-router/README.md)), the permission checks and their admin screen
7
+ ([`@aiquants/authz-react-router`](../authz-react-router/README.md)), and the user and group admin screen with the links to
8
+ the Google Workspace groups. An application keeps only its settings and one-line route modules.
9
+
10
+ - **One sign-in rule, three gates**: a person signs in only when the Google Workspace domain Google names for the account
11
+ (`hd`) is the vault's **and** the address is in the ledger of the vault's sign-in groups. The same predicate runs at
12
+ the auth server's gate, inside the sign-up's transaction and on every request's session check, so a person dropped
13
+ from the groups loses the session. The address's own domain is never matched.
14
+ - **One identity resolution, two guards**: the admin screens' guard and the vault's authorizer resolve the signed-in
15
+ person from the session's OpenID subject, read the person's groups, prove the tenant membership by the directory's
16
+ policy, and refuse a scoped grant. The vault asks every question of one call at once, and the host answers them with
17
+ one read of the person's groups and one read of the grants, however many compartments the call asks about.
18
+ - **Nothing before `start()`**: creating the host reads and checks the environment and every option, and builds the
19
+ pool without opening it; `start()` opens it, confirms the connection can take its two locks (the authz write
20
+ boundaries' and the vault's), checks the seeded admin resource and registers the vault's permission resources.
21
+ - **The ceremony apart**: the key ceremony runs as the ceremony principal through `@aiquants/vault-host/cli`; the server
22
+ never holds the ceremony lock and never reads the ceremony principal.
23
+
24
+ Three entries: `./server` (Node, `createVaultHost`), `./client` (the browser: the shell, the sign-in page and the three
25
+ pages; no Node code), `./cli` (Node, `runVaultHostCeremony`; no React code).
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ pnpm add @aiquants/vault-host @aiquants/vault-core @aiquants/vault-drizzle @aiquants/vault-react-router \
31
+ @aiquants/auth-core @aiquants/auth-react-router @aiquants/auth-directory-core @aiquants/auth-directory-drizzle \
32
+ @aiquants/authz-core @aiquants/authz-drizzle @aiquants/authz-react-router @aiquants/console-ui @aiquants/mssql \
33
+ drizzle-orm mssql react react-router
34
+ # peers: @aiquants/vault-core ^0.7.0, @aiquants/vault-drizzle ^0.5.0, @aiquants/vault-react-router ^0.4.0,
35
+ # @aiquants/auth-core ^0.9.6, @aiquants/auth-react-router ^0.54.0, @aiquants/auth-directory-core ^0.6.0,
36
+ # @aiquants/auth-directory-drizzle ^0.23.0, @aiquants/authz-core ^0.7.1, @aiquants/authz-drizzle ^4.0.0,
37
+ # @aiquants/authz-react-router ^0.36.0, @aiquants/console-ui ^0.12.1, @aiquants/mssql ^0.5.0,
38
+ # drizzle-orm >=1.0.0-beta.4 <2.0.0, mssql ^11.0.1, react ^19.2.7, react-router ^7.0.0 || ^8.0.0
39
+ ```
40
+
41
+ Every dependency is a peer, so the application holds one copy of each. Load console-ui's stylesheet once (its README,
42
+ "Loading the stylesheet"); this package ships no CSS. The server and the ceremony entries need Node 24 or later.
43
+
44
+ ## Quick start
45
+
46
+ Create the host once per process, in a server module:
47
+
48
+ ```ts
49
+ // app/vault-host.server.ts
50
+ import { createVaultHost, nodeMssqlVaultHostConnection } from "@aiquants/vault-host/server"
51
+ import { compartmentOf, secretIdRule } from "~/vault/placement.server"
52
+ import { logger } from "~/logger.server"
53
+
54
+ export const vaultHost = createVaultHost({
55
+ env: process.env,
56
+ placement: { secretIdRule, compartmentOf, listWhileSealed: true },
57
+ paths: { vault: "/vault", signIn: "/auth/login", signInCallback: "/auth/google/callback", signOut: "/auth/logout", authzAdmin: "/authz", userAdmin: "/users" },
58
+ schemas: { vault: "vault", authz: "dbo_authz", users: "dbo_fastapi", parameters: "dbo" },
59
+ locale: "ja",
60
+ authzAdminResource: { key: "authz_admin", name: "権限の管理" },
61
+ logger,
62
+ connect: nodeMssqlVaultHostConnection,
63
+ })
64
+ ```
65
+
66
+ Every option is required and has no default. `logger` has `info`, `warn` and `error`, each taking a machine code and the
67
+ vault's log details (never a value). `authzAdminResource` is the resource that guards both admin screens, as the
68
+ database seeds it; its key must not be under `VAULT_RESOURCE_PREFIX`.
69
+
70
+ Start the host before the server takes requests, and dispose of it after the server stopped taking them:
71
+
72
+ ```ts
73
+ // server.mjs
74
+ await vaultHost.start()
75
+ const server = app.listen(port)
76
+ process.once("SIGTERM", () => server.close(() => void vaultHost.dispose()))
77
+ ```
78
+
79
+ Mount the routes (the value routes first, so their static segments outrank the screen route's splat) and give each route
80
+ module the host's handlers and the page:
81
+
82
+ ```ts
83
+ // app/routes.ts
84
+ export default [
85
+ route("auth/login", "routes/sign-in.tsx"),
86
+ route("auth/google/callback", "routes/sign-in-callback.ts"),
87
+ route("auth/logout", "routes/sign-out.ts"),
88
+ route("vault/-/api/*", "routes/vault-api.ts"),
89
+ route("vault/*", "routes/vault.tsx"),
90
+ route("authz/*", "routes/authz.tsx"),
91
+ route("users/*", "routes/users.tsx"),
92
+ ] satisfies RouteConfig
93
+ ```
94
+
95
+ ```tsx
96
+ // app/root.tsx
97
+ import { VaultHostShell } from "@aiquants/vault-host/client"
98
+ import { Outlet } from "react-router"
99
+ import { vaultHost } from "~/vault-host.server"
100
+
101
+ export const loader = vaultHost.routes.root.loader
102
+ export default function Root() {
103
+ return (
104
+ <VaultHostShell>
105
+ <Outlet />
106
+ </VaultHostShell>
107
+ )
108
+ }
109
+ ```
110
+
111
+ ```tsx
112
+ // app/routes/vault.tsx (the others are alike)
113
+ import { VaultHostVaultPage } from "@aiquants/vault-host/client"
114
+ import { vaultHost } from "~/vault-host.server"
115
+
116
+ export const loader = vaultHost.routes.vault.loader
117
+ export const action = vaultHost.routes.vault.action
118
+ export const headers = vaultHost.routes.vault.headers
119
+ export default VaultHostVaultPage
120
+ ```
121
+
122
+ | Route module | Handlers | Page |
123
+ | --- | --- | --- |
124
+ | `root.tsx` | `routes.root.loader` | `VaultHostShell` around the `<Outlet />` |
125
+ | `sign-in.tsx` | `routes.signIn.loader`, `routes.signIn.action` | `VaultHostSignInPage` |
126
+ | `sign-in-callback.ts` | `routes.signInCallback.loader` | — |
127
+ | `sign-out.ts` | `routes.signOut.loader` | — |
128
+ | `vault-api.ts` | `routes.vaultApi.action` | — |
129
+ | `vault.tsx` | `routes.vault.loader`, `routes.vault.action`, `routes.vault.headers` | `VaultHostVaultPage` |
130
+ | `authz.tsx` | `routes.authzAdmin.loader`, `routes.authzAdmin.action` | `VaultHostAuthzAdminPage` |
131
+ | `users.tsx` | `routes.userAdmin.loader`, `routes.userAdmin.action` | `VaultHostUserAdminPage` |
132
+
133
+ The pages read the root route's data (route ID `root`, `VAULT_HOST_ROOT_ROUTE_ID`), so `app/root.tsx` must export the
134
+ host's root loader. A page loader sends a reader without a session to the sign-in page with the page to return to; the
135
+ value routes and the writes answer the 401 of an access failure instead, which the screens draw.
136
+
137
+ Run the key ceremony with the ceremony principal:
138
+
139
+ ```ts
140
+ // scripts/vault-admin.mts
141
+ import { createTtyTerminal } from "@aiquants/vault-core"
142
+ import { nodeMssqlVaultHostConnection, runVaultHostCeremony } from "@aiquants/vault-host/cli"
143
+ import { compartmentOf, secretIdRule } from "../app/vault/placement.server"
144
+
145
+ const terminal = createTtyTerminal({ input: process.stdin, output: process.stdout, errorOutput: process.stderr, environment: process.env })
146
+ process.exitCode = await runVaultHostCeremony({ argv: process.argv.slice(2), env: process.env, placement: { secretIdRule, compartmentOf }, vaultSchema: "vault", locale: "ja", terminal, connect: nodeMssqlVaultHostConnection })
147
+ ```
148
+
149
+ ## Sign-in
150
+
151
+ `VAULT_SIGN_IN_DOMAIN` names the Workspace domain. A sign-in passes only when both hold:
152
+
153
+ - Google named that domain for the account (`hd`, compared case-folded and whole: `sub.example.com` and
154
+ `example.com.evil.test` do not match `example.com`; an account Google names no domain for, such as a Gmail one,
155
+ never passes).
156
+ - The address is in the ledger of an active sign-in group (`TDAllowlistGroup`, kept by the group sync).
157
+
158
+ The domain is checked first, so the ledger is not even read for an account outside it. The address and domain allowlist
159
+ entries (`TMAllowlist`) take no part: the user admin screen lists the sign-in groups only and refuses to add or remove an
160
+ address or domain entry with an operator-facing sentence.
161
+
162
+ With `AUTH_GOOGLE_DIRECTORY_ENABLED=false` the ledger allows nobody, so nobody signs in; the key ceremony still runs.
163
+
164
+ A user is created at the first sign-in (and on the user admin screen) with the address as the user name and the display
165
+ ID, the profile's name as the display name, and no password. A deactivated user or OpenID subject keeps nobody signed
166
+ in. A person without a display name cannot act on the vault (its audit records the name); set it on the user admin
167
+ screen.
168
+
169
+ ## Environment
170
+
171
+ Every key is required and has no default; `createVaultHost` (and `runVaultHostCeremony`) throws `VaultHostConfigError`
172
+ naming every missing or malformed key at once, never a value.
173
+
174
+ | Key | Rule | Read by |
175
+ | --- | --- | --- |
176
+ | `VAULT_DB_SERVER`, `VAULT_DB_NAME` | text | server, ceremony |
177
+ | `VAULT_DB_PORT` | integer from 1 | server, ceremony |
178
+ | `VAULT_DB_ENCRYPT`, `VAULT_DB_TRUST_SERVER_CERTIFICATE` | `true` or `false` | server, ceremony |
179
+ | `VAULT_DB_USER`, `VAULT_DB_PASSWORD` | the runtime principal | server |
180
+ | `VAULT_CEREMONY_DB_USER`, `VAULT_CEREMONY_DB_PASSWORD` | the ceremony principal | ceremony |
181
+ | `VAULT_LOCK_PRINCIPAL` | the database role the vault's locks belong to, whose members are exactly the runtime and the ceremony principals (`lockPrincipal` of `@aiquants/vault-drizzle`, which refuses `public`); the server and the ceremony must name the same role, or their locks miss each other | server, ceremony |
182
+ | `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` | the vault's own OAuth client | server |
183
+ | `GOOGLE_OAUTH_REDIRECT_URL` | an `https` URL | server |
184
+ | `VAULT_SESSION_SECRET` | the session cookie's secret | server |
185
+ | `VAULT_SIGN_IN_DOMAIN` | the Workspace domain | server |
186
+ | `AUTHZ_TENANT_ID`, `AUTHZ_APP_KEY`, `VAULT_RESOURCE_PREFIX` | the permission tenant, application key and resource prefix | server |
187
+ | `AUTHZ_LOCK_PRINCIPAL` | the database role the authz write boundaries' lock belongs to (`lockPrincipal` of `@aiquants/authz-drizzle`, which refuses `public`), passed to the admin store and the lockout guard alike | server |
188
+ | `AUTH_SIGNUP_LOCK_PRINCIPAL` | the database role the sign-up's two locks belong to (`lockPrincipal` of `@aiquants/auth-directory-drizzle`'s `createOpenidSignup`, which refuses `public`), whose members are the principals that sign people up (the runtime one) | server |
189
+ | `AUTH_GOOGLE_DIRECTORY_ENABLED` | `true` or `false` | server |
190
+ | `VAULT_CLIENT_ADDRESS_HEADER`, `VAULT_REQUEST_ID_HEADER` | HTTP header names the trusted proxy writes | server |
191
+ | `VAULT_LOCK_TIMEOUT_MS`, `VAULT_CEREMONY_LOCK_TIMEOUT_MS` | integer from 0 | server, ceremony |
192
+ | `VAULT_TX_RETRY_ATTEMPTS`, `VAULT_MAX_BODY_BYTES` | integer from 1 | server, ceremony |
193
+ | `VAULT_MAX_ATTACHMENT_COUNT` | integer from 0 | server, ceremony |
194
+ | `VAULT_UNSEAL_PROGRESS_TTL_SECONDS`, `VAULT_UNSEAL_FAILURE_LIMIT`, `VAULT_UNSEAL_LOCKOUT_SECONDS`, `VAULT_MAX_REQUEST_BYTES`, `VAULT_AUDIT_PAGE_SIZE`, `VAULT_REVEAL_HIDE_SECONDS` | integer from 1 (the vault and its screens check their own ranges) | server |
195
+ | `VAULT_EXPORT_TIME_ZONE` | the IANA time zone the screens write instants and date export files in | server |
196
+
197
+ A request whose client address header is missing or blank stops (the vault records no address the proxy did not write);
198
+ a missing request ID header gives no request ID.
199
+
200
+ ## Database
201
+
202
+ The schema names are the host's (`schemas`); the tables and columns are fixed: the users and their OpenID subjects
203
+ (`TDUsers`, `TDOpenid` in `schemas.users`, the columns every vault database shares), the authorization and directory
204
+ tables of `@aiquants/authz-drizzle` and `@aiquants/auth-directory-drizzle` and the sign-out generations
205
+ (`TDSessionGeneration`) in `schemas.authz`, the system parameters (`tm_system_parameter` in `schemas.parameters`), and the
206
+ vault's own tables in `schemas.vault`, which must differ from the others.
207
+
208
+ The writes that read rows back (the user and group administration's inserts into `TDUsers`, `TMGroup` and
209
+ `TDGroupMember`) go through `outputInto` of `@aiquants/mssql/drizzle`: `OUTPUT ... INTO` a table variable and a
210
+ `select` of it in one batch. The sign-out generations are `@aiquants/auth-directory-drizzle`'s
211
+ `createSessionGenerationStore` on `defineSessionGenerationSchema(schemas.authz)`, whose update and insert read their
212
+ rows back through a table variable too. SQL Server refuses an `OUTPUT` without `INTO` when the table has an enabled
213
+ trigger for that action (error 334), so the host may put a trigger for any action on any of these tables.
214
+
215
+ Seed before the first `start()`:
216
+
217
+ - the three lock roles, `AUTHZ_LOCK_PRINCIPAL`, `VAULT_LOCK_PRINCIPAL` and `AUTH_SIGNUP_LOCK_PRINCIPAL`, with the runtime
218
+ principal a member of each (and the ceremony principal of the vault's): `start()` checks them in that order with
219
+ `assertLockPrincipalMember` of `@aiquants/mssql/drizzle`, the one implementation of the check, and stops at the first
220
+ role whose locks cannot be taken, with its refusal naming the setting, the role, the database user and the login,
221
+ before it reads anything else;
222
+
223
+ - the admin resource (`authzAdminResource.key`, application `AUTHZ_APP_KEY`, tenant `AUTHZ_TENANT_ID`) and a role
224
+ granted every action on it; `start()` throws when the resource is missing, and reads nothing else of authz (no role,
225
+ grant or user);
226
+ - the directory's overdue threshold, `tm_system_parameter` category `directory`, key `AUTH_DIRECTORY_STALENESS_SECONDS`
227
+ (`DIRECTORY_STALENESS_PARAMETER`), a positive integer for the tenant or `SYSTEM`; the user admin screen's status
228
+ stops when it is missing.
229
+
230
+ The first administrator's assignment comes after `start()`: signing in needs no grant (only the Workspace domain and
231
+ the sign-in groups), and the first sign-in writes the person's user row, which the assignment names. So the order is
232
+ seed the resource and the role, `start()`, the first administrator signs in once, then assign them the role.
233
+
234
+ `start()` creates the vault's permission resources that are missing (`<prefix>.seal`, `<prefix>.audit`,
235
+ `<prefix>.compartments`, and `<prefix>.<code>.items`, `.values`, `.export` of every compartment); a compartment added on
236
+ the screens registers its own.
237
+
238
+ ## Language
239
+
240
+ `locale` (`"ja"` or `"en"`) picks every catalog: the vault's screens, the permission admin (`jaAuthzAdminLabels` with the
241
+ admin resource's name), the user admin, the last-administrator refusal (`jaLockoutMessage`), the auth server's texts, the
242
+ access-failure notices, the names of the registered resources and the host's own texts.
243
+
244
+ ## Development
245
+
246
+ ```bash
247
+ pnpm run build
248
+ pnpm run test
249
+ ```
@@ -0,0 +1 @@
1
+ import{a as o}from"./chunk-YSXGDEY5.mjs";var u=class extends Error{static{o(this,"VaultHostConfigError")}keys;constructor(t){super(`[@aiquants/vault-host] the environment is incomplete: ${t.map(r=>`${r.key} (${r.rule})`).join(", ")}`),this.name="VaultHostConfigError",this.keys=t.map(r=>r.key)}},l={authz:"AUTHZ_LOCK_PRINCIPAL",vault:"VAULT_LOCK_PRINCIPAL",signup:"AUTH_SIGNUP_LOCK_PRINCIPAL"},y=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u,p=/^(?:0|[1-9]\d*)$/u,d=o(e=>{let t=[],r=o(s=>{let n=e[s];return typeof n!="string"||n.trim()===""?(t.push({key:s,rule:"required"}),null):n},"raw");return{problems:t,text:o(s=>r(s)??"","text"),integer:o((s,n)=>{let a=r(s);if(a===null)return 0;let i=p.test(a)?Number(a):Number.NaN;return!Number.isSafeInteger(i)||i<n?(t.push({key:s,rule:`an integer from ${n}`}),0):i},"integer"),flag:o(s=>{let n=r(s);return n===null?!1:n!=="true"&&n!=="false"?(t.push({key:s,rule:"true or false"}),!1):n==="true"},"flag"),httpsUrl:o(s=>{let n=r(s);return n===null?"":!URL.canParse(n)||new URL(n).protocol!=="https:"?(t.push({key:s,rule:"an https URL"}),""):n},"httpsUrl"),header:o(s=>{let n=r(s);return n===null?"":y.test(n)?n.toLowerCase():(t.push({key:s,rule:"an HTTP header name"}),"")},"header")}},"readerOf"),c=o(e=>{if(e.length>0)throw new u(e)},"throwProblems"),m=o(e=>({server:e.text("VAULT_DB_SERVER"),port:e.integer("VAULT_DB_PORT",1),database:e.text("VAULT_DB_NAME"),encrypt:e.flag("VAULT_DB_ENCRYPT"),trustServerCertificate:e.flag("VAULT_DB_TRUST_SERVER_CERTIFICATE")}),"databaseOf"),_=o(e=>{let t=d(e),r={database:m(t),runtime:{user:t.text("VAULT_DB_USER"),password:t.text("VAULT_DB_PASSWORD")},lockPrincipal:t.text(l.vault),google:{clientId:t.text("GOOGLE_CLIENT_ID"),clientSecret:t.text("GOOGLE_CLIENT_SECRET"),redirectUrl:t.httpsUrl("GOOGLE_OAUTH_REDIRECT_URL")},sessionSecret:t.text("VAULT_SESSION_SECRET"),signInDomain:t.text("VAULT_SIGN_IN_DOMAIN"),authz:{tenantId:t.text("AUTHZ_TENANT_ID"),appKey:t.text("AUTHZ_APP_KEY"),resourcePrefix:t.text("VAULT_RESOURCE_PREFIX"),lockPrincipal:t.text(l.authz)},signupLockPrincipal:t.text(l.signup),directoryEnabled:t.flag("AUTH_GOOGLE_DIRECTORY_ENABLED"),headers:{clientAddress:t.header("VAULT_CLIENT_ADDRESS_HEADER"),requestId:t.header("VAULT_REQUEST_ID_HEADER")},numbers:{lockTimeoutMs:t.integer("VAULT_LOCK_TIMEOUT_MS",0),ceremonyLockTimeoutMs:t.integer("VAULT_CEREMONY_LOCK_TIMEOUT_MS",0),transactionRetryAttempts:t.integer("VAULT_TX_RETRY_ATTEMPTS",1),unsealProgressTtlSeconds:t.integer("VAULT_UNSEAL_PROGRESS_TTL_SECONDS",1),unsealFailureLimit:t.integer("VAULT_UNSEAL_FAILURE_LIMIT",1),unsealLockoutSeconds:t.integer("VAULT_UNSEAL_LOCKOUT_SECONDS",1),maxBodyBytes:t.integer("VAULT_MAX_BODY_BYTES",1),maxAttachmentCount:t.integer("VAULT_MAX_ATTACHMENT_COUNT",0),maxRequestBytes:t.integer("VAULT_MAX_REQUEST_BYTES",1),auditPageSize:t.integer("VAULT_AUDIT_PAGE_SIZE",1),revealHideSeconds:t.integer("VAULT_REVEAL_HIDE_SECONDS",1),exportTimeZone:t.text("VAULT_EXPORT_TIME_ZONE")}};return c(t.problems),r},"readVaultHostServerEnv"),V=o(e=>{let t=d(e),r={database:m(t),ceremony:{user:t.text("VAULT_CEREMONY_DB_USER"),password:t.text("VAULT_CEREMONY_DB_PASSWORD")},lockPrincipal:t.text(l.vault),numbers:{lockTimeoutMs:t.integer("VAULT_LOCK_TIMEOUT_MS",0),ceremonyLockTimeoutMs:t.integer("VAULT_CEREMONY_LOCK_TIMEOUT_MS",0),transactionRetryAttempts:t.integer("VAULT_TX_RETRY_ATTEMPTS",1),maxBodyBytes:t.integer("VAULT_MAX_BODY_BYTES",1),maxAttachmentCount:t.integer("VAULT_MAX_ATTACHMENT_COUNT",0)}};return c(t.problems),r},"readVaultHostCeremonyEnv");import{mssqlSessionConnection as g}from"@aiquants/vault-drizzle/node-mssql";import{drizzle as f}from"drizzle-orm/node-mssql";import E from"mssql";var U=o(e=>{let t=new E.ConnectionPool(e);return{db:f({client:t}),open:o(async()=>{await t.connect()},"open"),close:o(()=>t.close(),"close"),openSession:o(()=>g(e),"openSession")}},"nodeMssqlVaultHostConnection");var x=o((e,t,r)=>({server:e.server,port:e.port,database:e.database,user:t.user,password:t.password,options:{encrypt:e.encrypt,trustServerCertificate:e.trustServerCertificate,appName:r}}),"mssqlConfigOf");import{GOOGLE_PROVIDER as T}from"@aiquants/auth-core";import{registerVaultAuthzResources as A}from"@aiquants/vault-core/authz";var D=o(e=>async(t,r)=>{await A({store:e.store,tenantId:e.tenantId,appKey:e.appKey,resourcePrefix:e.resourcePrefix,compartments:t,nameOf:e.nameOf,actor:r})},"vaultResourceRegistrarOf"),q=o(()=>new Date,"systemClock"),N=o(async()=>{throw new Error("[@aiquants/vault-host] the server never holds the ceremony lock; run the key ceremony with runVaultHostCeremony")},"refuseCeremonySession"),w=o(e=>({onAdded:o((t,r)=>e([t],r.actor.id),"onAdded")}),"compartmentsPortOf"),k=o((e,t)=>({attempts:e,onRetry:o(({attempt:r})=>{t.warn("vault-host-vault-retried",{operation:"vault-transaction",compartment:null,secretId:null,version:null,reason:`${r}/${e-1}`,cause:null})},"onRetry")}),"vaultTransactionRetryOf"),M=o(e=>{let{catalog:t,resource:r,logger:s}=e;return{store:e.store,fieldLimits:e.fieldLimits,...e.labels===void 0?{}:{labels:e.labels},guards:{requireAccess:o(async(n,{action:a})=>{await e.requireUser(n),await e.requirePermission(n,{resourceKey:r.key,action:a})},"requireAccess"),onDenied:o(({intent:n,actions:a})=>{s.info("vault-host-user-admin-denied",{operation:n,compartment:null,secretId:null,version:null,reason:a.join(","),cause:null})},"onDenied")},resolveActor:o(async n=>{let a=await e.sessionUserOf(n),[i]=a===void 0?[]:a.emails;if(i===void 0)throw new Error("[@aiquants/vault-host] a user admin write reached the store without a signed-in address");return i.value},"resolveActor"),...t===null?{}:{directoryCatalog:{listGroups:o(()=>t.read(e.tenantId,T),"listGroups")}},getMyPermissions:o(n=>e.getMyPermissions(n,{resourceKeys:[r.key]}),"getMyPermissions"),resourceLabels:{[r.key]:r.name}}},"userAdminConfigOf"),K=o(e=>async({request:t})=>{let r=await e.sessionUserOf(t),[s]=r===void 0?[]:r.emails;return{signedIn:r===void 0?null:{displayName:r.displayName,email:s===void 0?null:s.value},readerStamp:await e.readerStampOf(r),locale:e.locale,timeZone:e.timeZone,paths:e.paths}},"rootLoaderOf"),B=o(e=>async({request:t})=>{let r=e.refusalOf(t);throw r!==void 0?(e.logger.warn("vault-host-sign-out-refused",{operation:"sign-out",compartment:null,secretId:null,version:null,reason:r,cause:null}),e.refusalResponse()):await e.signOut(t)},"signOutLoaderOf"),z=o(e=>async()=>{if(await e.open(),await e.checkLocks(),!(await e.listResources(e.tenantId)).some(r=>r.appKey===e.appKey&&r.resourceKey===e.adminResourceKey))throw new Error(`[@aiquants/vault-host] the admin resource ${e.adminResourceKey} is not registered for the application ${e.appKey} of the tenant ${e.tenantId}; seed it first`);await e.register(await e.listCompartments(),e.actor)},"startOf"),G=o((e,t)=>async r=>(await e(r.request),t(r)),"signedInLoaderOf"),Y=o(e=>async()=>{for(let t of e.roles)await e.check(t.lockPrincipal,t.settingName)},"lockRoleChecksOf"),$=o(e=>async()=>{e.disposeVault(),await e.close()},"disposeOf");export{x as a,u as b,l as c,_ as d,V as e,D as f,q as g,N as h,w as i,k as j,M as k,K as l,B as m,z as n,G as o,Y as p,$ as q,U as r};
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var c=Object.defineProperty;var d=(a,b)=>c(a,"name",{value:b,configurable:!0});exports.a = d;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var t=Object.freeze(["en","ja"]),e= exports.b ="root";exports.a = t; exports.b = e;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunkEI7MMDWYjs = require('./chunk-EI7MMDWY.js');var u=class extends Error{static{_chunkEI7MMDWYjs.a.call(void 0, this,"VaultHostConfigError")}constructor(t){super(`[@aiquants/vault-host] the environment is incomplete: ${t.map(r=>`${r.key} (${r.rule})`).join(", ")}`),this.name="VaultHostConfigError",this.keys=t.map(r=>r.key)}},l= exports.c ={authz:"AUTHZ_LOCK_PRINCIPAL",vault:"VAULT_LOCK_PRINCIPAL",signup:"AUTH_SIGNUP_LOCK_PRINCIPAL"},y=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u,p=/^(?:0|[1-9]\d*)$/u,d=_chunkEI7MMDWYjs.a.call(void 0, e=>{let t=[],r=_chunkEI7MMDWYjs.a.call(void 0, s=>{let n=e[s];return typeof n!="string"||n.trim()===""?(t.push({key:s,rule:"required"}),null):n},"raw");return{problems:t,text:_chunkEI7MMDWYjs.a.call(void 0, s=>_nullishCoalesce(r(s), () => ("")),"text"),integer:_chunkEI7MMDWYjs.a.call(void 0, (s,n)=>{let a=r(s);if(a===null)return 0;let i=p.test(a)?Number(a):Number.NaN;return!Number.isSafeInteger(i)||i<n?(t.push({key:s,rule:`an integer from ${n}`}),0):i},"integer"),flag:_chunkEI7MMDWYjs.a.call(void 0, s=>{let n=r(s);return n===null?!1:n!=="true"&&n!=="false"?(t.push({key:s,rule:"true or false"}),!1):n==="true"},"flag"),httpsUrl:_chunkEI7MMDWYjs.a.call(void 0, s=>{let n=r(s);return n===null?"":!URL.canParse(n)||new URL(n).protocol!=="https:"?(t.push({key:s,rule:"an https URL"}),""):n},"httpsUrl"),header:_chunkEI7MMDWYjs.a.call(void 0, s=>{let n=r(s);return n===null?"":y.test(n)?n.toLowerCase():(t.push({key:s,rule:"an HTTP header name"}),"")},"header")}},"readerOf"),c=_chunkEI7MMDWYjs.a.call(void 0, e=>{if(e.length>0)throw new u(e)},"throwProblems"),m=_chunkEI7MMDWYjs.a.call(void 0, e=>({server:e.text("VAULT_DB_SERVER"),port:e.integer("VAULT_DB_PORT",1),database:e.text("VAULT_DB_NAME"),encrypt:e.flag("VAULT_DB_ENCRYPT"),trustServerCertificate:e.flag("VAULT_DB_TRUST_SERVER_CERTIFICATE")}),"databaseOf"),_= exports.d =_chunkEI7MMDWYjs.a.call(void 0, e=>{let t=d(e),r={database:m(t),runtime:{user:t.text("VAULT_DB_USER"),password:t.text("VAULT_DB_PASSWORD")},lockPrincipal:t.text(l.vault),google:{clientId:t.text("GOOGLE_CLIENT_ID"),clientSecret:t.text("GOOGLE_CLIENT_SECRET"),redirectUrl:t.httpsUrl("GOOGLE_OAUTH_REDIRECT_URL")},sessionSecret:t.text("VAULT_SESSION_SECRET"),signInDomain:t.text("VAULT_SIGN_IN_DOMAIN"),authz:{tenantId:t.text("AUTHZ_TENANT_ID"),appKey:t.text("AUTHZ_APP_KEY"),resourcePrefix:t.text("VAULT_RESOURCE_PREFIX"),lockPrincipal:t.text(l.authz)},signupLockPrincipal:t.text(l.signup),directoryEnabled:t.flag("AUTH_GOOGLE_DIRECTORY_ENABLED"),headers:{clientAddress:t.header("VAULT_CLIENT_ADDRESS_HEADER"),requestId:t.header("VAULT_REQUEST_ID_HEADER")},numbers:{lockTimeoutMs:t.integer("VAULT_LOCK_TIMEOUT_MS",0),ceremonyLockTimeoutMs:t.integer("VAULT_CEREMONY_LOCK_TIMEOUT_MS",0),transactionRetryAttempts:t.integer("VAULT_TX_RETRY_ATTEMPTS",1),unsealProgressTtlSeconds:t.integer("VAULT_UNSEAL_PROGRESS_TTL_SECONDS",1),unsealFailureLimit:t.integer("VAULT_UNSEAL_FAILURE_LIMIT",1),unsealLockoutSeconds:t.integer("VAULT_UNSEAL_LOCKOUT_SECONDS",1),maxBodyBytes:t.integer("VAULT_MAX_BODY_BYTES",1),maxAttachmentCount:t.integer("VAULT_MAX_ATTACHMENT_COUNT",0),maxRequestBytes:t.integer("VAULT_MAX_REQUEST_BYTES",1),auditPageSize:t.integer("VAULT_AUDIT_PAGE_SIZE",1),revealHideSeconds:t.integer("VAULT_REVEAL_HIDE_SECONDS",1),exportTimeZone:t.text("VAULT_EXPORT_TIME_ZONE")}};return c(t.problems),r},"readVaultHostServerEnv"),V= exports.e =_chunkEI7MMDWYjs.a.call(void 0, e=>{let t=d(e),r={database:m(t),ceremony:{user:t.text("VAULT_CEREMONY_DB_USER"),password:t.text("VAULT_CEREMONY_DB_PASSWORD")},lockPrincipal:t.text(l.vault),numbers:{lockTimeoutMs:t.integer("VAULT_LOCK_TIMEOUT_MS",0),ceremonyLockTimeoutMs:t.integer("VAULT_CEREMONY_LOCK_TIMEOUT_MS",0),transactionRetryAttempts:t.integer("VAULT_TX_RETRY_ATTEMPTS",1),maxBodyBytes:t.integer("VAULT_MAX_BODY_BYTES",1),maxAttachmentCount:t.integer("VAULT_MAX_ATTACHMENT_COUNT",0)}};return c(t.problems),r},"readVaultHostCeremonyEnv");var _nodemssql = require('@aiquants/vault-drizzle/node-mssql');var _nodemssql3 = require('drizzle-orm/node-mssql');var _mssql = require('mssql'); var _mssql2 = _interopRequireDefault(_mssql);var U=_chunkEI7MMDWYjs.a.call(void 0, e=>{let t=new _mssql2.default.ConnectionPool(e);return{db:_nodemssql3.drizzle.call(void 0, {client:t}),open:_chunkEI7MMDWYjs.a.call(void 0, async()=>{await t.connect()},"open"),close:_chunkEI7MMDWYjs.a.call(void 0, ()=>t.close(),"close"),openSession:_chunkEI7MMDWYjs.a.call(void 0, ()=>_nodemssql.mssqlSessionConnection.call(void 0, e),"openSession")}},"nodeMssqlVaultHostConnection");var x=_chunkEI7MMDWYjs.a.call(void 0, (e,t,r)=>({server:e.server,port:e.port,database:e.database,user:t.user,password:t.password,options:{encrypt:e.encrypt,trustServerCertificate:e.trustServerCertificate,appName:r}}),"mssqlConfigOf");var _authcore = require('@aiquants/auth-core');var _authz = require('@aiquants/vault-core/authz');var D=_chunkEI7MMDWYjs.a.call(void 0, e=>async(t,r)=>{await _authz.registerVaultAuthzResources.call(void 0, {store:e.store,tenantId:e.tenantId,appKey:e.appKey,resourcePrefix:e.resourcePrefix,compartments:t,nameOf:e.nameOf,actor:r})},"vaultResourceRegistrarOf"),q= exports.g =_chunkEI7MMDWYjs.a.call(void 0, ()=>new Date,"systemClock"),N= exports.h =_chunkEI7MMDWYjs.a.call(void 0, async()=>{throw new Error("[@aiquants/vault-host] the server never holds the ceremony lock; run the key ceremony with runVaultHostCeremony")},"refuseCeremonySession"),w= exports.i =_chunkEI7MMDWYjs.a.call(void 0, e=>({onAdded:_chunkEI7MMDWYjs.a.call(void 0, (t,r)=>e([t],r.actor.id),"onAdded")}),"compartmentsPortOf"),k= exports.j =_chunkEI7MMDWYjs.a.call(void 0, (e,t)=>({attempts:e,onRetry:_chunkEI7MMDWYjs.a.call(void 0, ({attempt:r})=>{t.warn("vault-host-vault-retried",{operation:"vault-transaction",compartment:null,secretId:null,version:null,reason:`${r}/${e-1}`,cause:null})},"onRetry")}),"vaultTransactionRetryOf"),M= exports.k =_chunkEI7MMDWYjs.a.call(void 0, e=>{let{catalog:t,resource:r,logger:s}=e;return{store:e.store,fieldLimits:e.fieldLimits,...e.labels===void 0?{}:{labels:e.labels},guards:{requireAccess:_chunkEI7MMDWYjs.a.call(void 0, async(n,{action:a})=>{await e.requireUser(n),await e.requirePermission(n,{resourceKey:r.key,action:a})},"requireAccess"),onDenied:_chunkEI7MMDWYjs.a.call(void 0, ({intent:n,actions:a})=>{s.info("vault-host-user-admin-denied",{operation:n,compartment:null,secretId:null,version:null,reason:a.join(","),cause:null})},"onDenied")},resolveActor:_chunkEI7MMDWYjs.a.call(void 0, async n=>{let a=await e.sessionUserOf(n),[i]=a===void 0?[]:a.emails;if(i===void 0)throw new Error("[@aiquants/vault-host] a user admin write reached the store without a signed-in address");return i.value},"resolveActor"),...t===null?{}:{directoryCatalog:{listGroups:_chunkEI7MMDWYjs.a.call(void 0, ()=>t.read(e.tenantId,_authcore.GOOGLE_PROVIDER),"listGroups")}},getMyPermissions:_chunkEI7MMDWYjs.a.call(void 0, n=>e.getMyPermissions(n,{resourceKeys:[r.key]}),"getMyPermissions"),resourceLabels:{[r.key]:r.name}}},"userAdminConfigOf"),K= exports.l =_chunkEI7MMDWYjs.a.call(void 0, e=>async({request:t})=>{let r=await e.sessionUserOf(t),[s]=r===void 0?[]:r.emails;return{signedIn:r===void 0?null:{displayName:r.displayName,email:s===void 0?null:s.value},readerStamp:await e.readerStampOf(r),locale:e.locale,timeZone:e.timeZone,paths:e.paths}},"rootLoaderOf"),B= exports.m =_chunkEI7MMDWYjs.a.call(void 0, e=>async({request:t})=>{let r=e.refusalOf(t);throw r!==void 0?(e.logger.warn("vault-host-sign-out-refused",{operation:"sign-out",compartment:null,secretId:null,version:null,reason:r,cause:null}),e.refusalResponse()):await e.signOut(t)},"signOutLoaderOf"),z= exports.n =_chunkEI7MMDWYjs.a.call(void 0, e=>async()=>{if(await e.open(),await e.checkLocks(),!(await e.listResources(e.tenantId)).some(r=>r.appKey===e.appKey&&r.resourceKey===e.adminResourceKey))throw new Error(`[@aiquants/vault-host] the admin resource ${e.adminResourceKey} is not registered for the application ${e.appKey} of the tenant ${e.tenantId}; seed it first`);await e.register(await e.listCompartments(),e.actor)},"startOf"),G= exports.o =_chunkEI7MMDWYjs.a.call(void 0, (e,t)=>async r=>(await e(r.request),t(r)),"signedInLoaderOf"),Y= exports.p =_chunkEI7MMDWYjs.a.call(void 0, e=>async()=>{for(let t of e.roles)await e.check(t.lockPrincipal,t.settingName)},"lockRoleChecksOf"),$= exports.q =_chunkEI7MMDWYjs.a.call(void 0, e=>async()=>{e.disposeVault(),await e.close()},"disposeOf");exports.a = x; exports.b = u; exports.c = l; exports.d = _; exports.e = V; exports.f = D; exports.g = q; exports.h = N; exports.i = w; exports.j = k; exports.k = M; exports.l = K; exports.m = B; exports.n = z; exports.o = G; exports.p = Y; exports.q = $; exports.r = U;
@@ -0,0 +1 @@
1
+ var t=Object.freeze(["en","ja"]),e="root";export{t as a,e as b};
@@ -0,0 +1 @@
1
+ var c=Object.defineProperty;var d=(a,b)=>c(a,"name",{value:b,configurable:!0});export{d as a};
package/dist/cli.d.mts ADDED
@@ -0,0 +1,20 @@
1
+ import { VaultPlacementRule, VaultCliLocale, VaultTerminal } from "@aiquants/vault-core";
2
+ import { V as VaultHostEnvironment, a as VaultHostConnect } from "./connect-ZEgTyJ3x.mjs";
3
+ export { n as nodeMssqlVaultHostConnection } from "./connect-ZEgTyJ3x.mjs";
4
+ import "@aiquants/vault-drizzle";
5
+ import "mssql";
6
+ declare const VAULT_HOST_CEREMONY_APP_NAME = "aiquants-vault-host-ceremony";
7
+ type RunVaultHostCeremonyOptions = {
8
+ readonly argv: readonly string[];
9
+ readonly env: VaultHostEnvironment;
10
+ readonly placement: {
11
+ readonly secretIdRule: (candidate: string) => boolean;
12
+ readonly compartmentOf: VaultPlacementRule;
13
+ };
14
+ readonly vaultSchema: string;
15
+ readonly locale: VaultCliLocale;
16
+ readonly terminal: VaultTerminal;
17
+ readonly connect: VaultHostConnect;
18
+ };
19
+ declare const runVaultHostCeremony: (options: RunVaultHostCeremonyOptions) => Promise<number>;
20
+ export { type RunVaultHostCeremonyOptions, VAULT_HOST_CEREMONY_APP_NAME, runVaultHostCeremony };
package/dist/cli.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ import { VaultPlacementRule, VaultCliLocale, VaultTerminal } from "@aiquants/vault-core";
2
+ import { V as VaultHostEnvironment, a as VaultHostConnect } from "./connect-ZEgTyJ3x.js";
3
+ export { n as nodeMssqlVaultHostConnection } from "./connect-ZEgTyJ3x.js";
4
+ import "@aiquants/vault-drizzle";
5
+ import "mssql";
6
+ declare const VAULT_HOST_CEREMONY_APP_NAME = "aiquants-vault-host-ceremony";
7
+ type RunVaultHostCeremonyOptions = {
8
+ readonly argv: readonly string[];
9
+ readonly env: VaultHostEnvironment;
10
+ readonly placement: {
11
+ readonly secretIdRule: (candidate: string) => boolean;
12
+ readonly compartmentOf: VaultPlacementRule;
13
+ };
14
+ readonly vaultSchema: string;
15
+ readonly locale: VaultCliLocale;
16
+ readonly terminal: VaultTerminal;
17
+ readonly connect: VaultHostConnect;
18
+ };
19
+ declare const runVaultHostCeremony: (options: RunVaultHostCeremonyOptions) => Promise<number>;
20
+ export { type RunVaultHostCeremonyOptions, VAULT_HOST_CEREMONY_APP_NAME, runVaultHostCeremony };
package/dist/cli.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkQJKY44QOjs = require('./chunk-QJKY44QO.js');var _chunkEI7MMDWYjs = require('./chunk-EI7MMDWY.js');var _vaultcore = require('@aiquants/vault-core');var _vaultdrizzle = require('@aiquants/vault-drizzle');var c="aiquants-vault-host-ceremony",C=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u,v= exports.runVaultHostCeremony =_chunkEI7MMDWYjs.a.call(void 0, async e=>{let a=_chunkQJKY44QOjs.e.call(void 0, e.env);if(typeof e.vaultSchema!="string"||!C.test(e.vaultSchema))throw new RangeError("[@aiquants/vault-host] vaultSchema must be a regular SQL Server identifier");let s=_chunkQJKY44QOjs.a.call(void 0, a.database,a.ceremony,c),n=e.connect(s);await n.open();try{let{numbers:t}=a,u=_vaultdrizzle.createDrizzleVaultStorage.call(void 0, {db:n.db,schema:_vaultdrizzle.defineVaultSchema.call(void 0, e.vaultSchema),lockTimeoutMs:t.lockTimeoutMs,ceremonyLockTimeoutMs:t.ceremonyLockTimeoutMs,lockPrincipal:a.lockPrincipal,transactionRetry:{attempts:t.transactionRetryAttempts},openSessionConnection:n.openSession});return await _vaultcore.runVaultAdminCli.call(void 0, {argv:e.argv,terminal:e.terminal,terminalName:_vaultcore.nodeTerminalName.call(void 0, ),storage:u,clock:_chunkQJKY44QOjs.g,secretIdRule:e.placement.secretIdRule,compartmentOf:e.placement.compartmentOf,limits:{maxBodyBytes:t.maxBodyBytes,maxAttachmentCount:t.maxAttachmentCount},files:_vaultcore.nodeVaultAdminFiles,locale:e.locale})}finally{await n.close()}},"runVaultHostCeremony");exports.VAULT_HOST_CEREMONY_APP_NAME = c; exports.nodeMssqlVaultHostConnection = _chunkQJKY44QOjs.r; exports.runVaultHostCeremony = v;
package/dist/cli.mjs ADDED
@@ -0,0 +1 @@
1
+ import{a as r,e as l,g as m,r as i}from"./chunk-7QP3MVGS.mjs";import{a as o}from"./chunk-YSXGDEY5.mjs";import{nodeTerminalName as y,nodeVaultAdminFiles as d,runVaultAdminCli as p}from"@aiquants/vault-core";import{createDrizzleVaultStorage as V,defineVaultSchema as f}from"@aiquants/vault-drizzle";var c="aiquants-vault-host-ceremony",C=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u,v=o(async e=>{let a=l(e.env);if(typeof e.vaultSchema!="string"||!C.test(e.vaultSchema))throw new RangeError("[@aiquants/vault-host] vaultSchema must be a regular SQL Server identifier");let s=r(a.database,a.ceremony,c),n=e.connect(s);await n.open();try{let{numbers:t}=a,u=V({db:n.db,schema:f(e.vaultSchema),lockTimeoutMs:t.lockTimeoutMs,ceremonyLockTimeoutMs:t.ceremonyLockTimeoutMs,lockPrincipal:a.lockPrincipal,transactionRetry:{attempts:t.transactionRetryAttempts},openSessionConnection:n.openSession});return await p({argv:e.argv,terminal:e.terminal,terminalName:y(),storage:u,clock:m,secretIdRule:e.placement.secretIdRule,compartmentOf:e.placement.compartmentOf,limits:{maxBodyBytes:t.maxBodyBytes,maxAttachmentCount:t.maxAttachmentCount},files:d,locale:e.locale})}finally{await n.close()}},"runVaultHostCeremony");export{c as VAULT_HOST_CEREMONY_APP_NAME,i as nodeMssqlVaultHostConnection,v as runVaultHostCeremony};
@@ -0,0 +1,37 @@
1
+ import { AccessFailurePresenter, StampWrite } from "@aiquants/auth-core";
2
+ import * as react from "react";
3
+ import { ReactNode } from "react";
4
+ import { V as VaultHostRootData } from "./contract-Ck9emmKB.mjs";
5
+ export { a as VAULT_HOST_ROOT_ROUTE_ID, b as VaultHostLocale, c as VaultHostPaths, d as VaultHostSignedInPerson } from "./contract-Ck9emmKB.mjs";
6
+ declare const useVaultHostAccessFailure: (testId: string) => AccessFailurePresenter<ReactNode>;
7
+ type VaultHostClientLabels = {
8
+ readonly formatLocale: string;
9
+ readonly nav: {
10
+ readonly label: string;
11
+ readonly vault: string;
12
+ readonly authzAdmin: string;
13
+ readonly userAdmin: string;
14
+ };
15
+ readonly signedInAs: string;
16
+ readonly signOut: string;
17
+ readonly signIn: {
18
+ readonly title: string;
19
+ readonly description: string;
20
+ readonly button: string;
21
+ };
22
+ };
23
+ declare const englishClientLabels: VaultHostClientLabels;
24
+ declare const japaneseClientLabels: VaultHostClientLabels;
25
+ declare const VaultHostVaultPage: () => react.JSX.Element;
26
+ declare const VaultHostAuthzAdminPage: () => react.JSX.Element;
27
+ declare const VaultHostUserAdminPage: () => react.JSX.Element;
28
+ declare const useVaultHostRoot: () => VaultHostRootData;
29
+ declare const useVaultHostLabels: () => VaultHostClientLabels;
30
+ declare const useVaultHostStampWrite: () => StampWrite;
31
+ type VaultHostShellProps = {
32
+ readonly children: ReactNode;
33
+ };
34
+ declare const VaultHostShell: ({ children }: VaultHostShellProps) => react.JSX.Element;
35
+ declare const GOOGLE_SIGN_IN_INTENT = "Sign In with Google";
36
+ declare const VaultHostSignInPage: () => react.JSX.Element;
37
+ export { GOOGLE_SIGN_IN_INTENT, VaultHostAuthzAdminPage, type VaultHostClientLabels, VaultHostRootData, VaultHostShell, type VaultHostShellProps, VaultHostSignInPage, VaultHostUserAdminPage, VaultHostVaultPage, englishClientLabels, japaneseClientLabels, useVaultHostAccessFailure, useVaultHostLabels, useVaultHostRoot, useVaultHostStampWrite };
@@ -0,0 +1,37 @@
1
+ import { AccessFailurePresenter, StampWrite } from "@aiquants/auth-core";
2
+ import * as react from "react";
3
+ import { ReactNode } from "react";
4
+ import { V as VaultHostRootData } from "./contract-Ck9emmKB.js";
5
+ export { a as VAULT_HOST_ROOT_ROUTE_ID, b as VaultHostLocale, c as VaultHostPaths, d as VaultHostSignedInPerson } from "./contract-Ck9emmKB.js";
6
+ declare const useVaultHostAccessFailure: (testId: string) => AccessFailurePresenter<ReactNode>;
7
+ type VaultHostClientLabels = {
8
+ readonly formatLocale: string;
9
+ readonly nav: {
10
+ readonly label: string;
11
+ readonly vault: string;
12
+ readonly authzAdmin: string;
13
+ readonly userAdmin: string;
14
+ };
15
+ readonly signedInAs: string;
16
+ readonly signOut: string;
17
+ readonly signIn: {
18
+ readonly title: string;
19
+ readonly description: string;
20
+ readonly button: string;
21
+ };
22
+ };
23
+ declare const englishClientLabels: VaultHostClientLabels;
24
+ declare const japaneseClientLabels: VaultHostClientLabels;
25
+ declare const VaultHostVaultPage: () => react.JSX.Element;
26
+ declare const VaultHostAuthzAdminPage: () => react.JSX.Element;
27
+ declare const VaultHostUserAdminPage: () => react.JSX.Element;
28
+ declare const useVaultHostRoot: () => VaultHostRootData;
29
+ declare const useVaultHostLabels: () => VaultHostClientLabels;
30
+ declare const useVaultHostStampWrite: () => StampWrite;
31
+ type VaultHostShellProps = {
32
+ readonly children: ReactNode;
33
+ };
34
+ declare const VaultHostShell: ({ children }: VaultHostShellProps) => react.JSX.Element;
35
+ declare const GOOGLE_SIGN_IN_INTENT = "Sign In with Google";
36
+ declare const VaultHostSignInPage: () => react.JSX.Element;
37
+ export { GOOGLE_SIGN_IN_INTENT, VaultHostAuthzAdminPage, type VaultHostClientLabels, VaultHostRootData, VaultHostShell, type VaultHostShellProps, VaultHostSignInPage, VaultHostUserAdminPage, VaultHostVaultPage, englishClientLabels, japaneseClientLabels, useVaultHostAccessFailure, useVaultHostLabels, useVaultHostRoot, useVaultHostStampWrite };
package/dist/client.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkJ2KNKMKOjs = require('./chunk-J2KNKMKO.js');var _chunkEI7MMDWYjs = require('./chunk-EI7MMDWY.js');var _authcore = require('@aiquants/auth-core');var _returnto = require('@aiquants/auth-react-router/return-to');var _consoleui = require('@aiquants/console-ui');var _react = require('react');var _reactrouter = require('react-router');var b=Object.freeze({formatLocale:"en-US",nav:Object.freeze({label:"Vault menu",vault:"Vault",authzAdmin:"Permissions",userAdmin:"Users and groups"}),signedInAs:"Signed in as {name}",signOut:"Sign out",signIn:Object.freeze({title:"Sign in to the vault",description:"Sign in with your organization's Google Workspace account. Only the members of the vault's sign-in groups can enter.",button:"Sign in with Google"})});var y=Object.freeze({formatLocale:"ja-JP",nav:Object.freeze({label:"\u4FDD\u7BA1\u5EAB\u306E\u30E1\u30CB\u30E5\u30FC",vault:"\u4FDD\u7BA1\u5EAB",authzAdmin:"\u6A29\u9650\u306E\u7BA1\u7406",userAdmin:"\u5229\u7528\u8005\u3068\u30B0\u30EB\u30FC\u30D7"}),signedInAs:"{name} \u3067\u30B5\u30A4\u30F3\u30A4\u30F3\u4E2D",signOut:"\u30B5\u30A4\u30F3\u30A2\u30A6\u30C8",signIn:Object.freeze({title:"\u4FDD\u7BA1\u5EAB\u306B\u30B5\u30A4\u30F3\u30A4\u30F3",description:"\u7D44\u7E54\u306E Google Workspace \u306E\u30A2\u30AB\u30A6\u30F3\u30C8\u3067\u30B5\u30A4\u30F3\u30A4\u30F3\u3057\u307E\u3059\u3002\u4FDD\u7BA1\u5EAB\u306E\u30B5\u30A4\u30F3\u30A4\u30F3\u3092\u8A31\u3059\u30B0\u30EB\u30FC\u30D7\u306E\u4EBA\u3060\u3051\u304C\u5165\u308C\u307E\u3059\u3002",button:"Google \u3067\u30B5\u30A4\u30F3\u30A4\u30F3"})});var n=_chunkEI7MMDWYjs.a.call(void 0, ()=>{let t=_reactrouter.useRouteLoaderData.call(void 0, _chunkJ2KNKMKOjs.b);if(t===void 0)throw new Error(`[@aiquants/vault-host] the root route (${_chunkJ2KNKMKOjs.b}) has no data; export the host's routes.root.loader from app/root.tsx`);return t},"useVaultHostRoot"),m= exports.useVaultHostLabels =_chunkEI7MMDWYjs.a.call(void 0, ()=>n().locale==="ja"?y:b,"useVaultHostLabels"),d= exports.useVaultHostStampWrite =_chunkEI7MMDWYjs.a.call(void 0, ()=>{let{readerStamp:t}=n();return _react.useCallback.call(void 0, a=>_authcore.stampReader.call(void 0, a,t),[t])},"useVaultHostStampWrite");var _jsxruntime = require('react/jsx-runtime');var i=_chunkEI7MMDWYjs.a.call(void 0, t=>{let{locale:a,paths:s}=n(),o=_reactrouter.useNavigate.call(void 0, ),{pathname:u,search:r}=_reactrouter.useLocation.call(void 0, );return _react.useMemo.call(void 0, ()=>{let V=_authcore.resolveAccessFailureLabels.call(void 0, a),g=_chunkEI7MMDWYjs.a.call(void 0, ()=>{o(_returnto.signInPathWithReturnTo.call(void 0, s.signIn,`${u}${r}`))},"signIn"),H={"sign-in":g,"sign-in-again":g,back:_chunkEI7MMDWYjs.a.call(void 0, ()=>{o(-1)},"back"),top:_chunkEI7MMDWYjs.a.call(void 0, ()=>{o(s.vault)},"top")};return F=>{let O=_authcore.accessFailureView.call(void 0, F,{signedIn:!0,keepsWork:!1},V);return _jsxruntime.jsx.call(void 0, _consoleui.AccessFailureNotice,{view:O,handlers:H,testId:t})}},[a,s,o,u,r,t])},"useVaultHostAccessFailure");var _admin = require('@aiquants/auth-react-router/admin');var _authzreactrouter = require('@aiquants/authz-react-router');var _client = require('@aiquants/vault-react-router/client');var j=_chunkEI7MMDWYjs.a.call(void 0, ()=>{let t=i("vault-host-vault-access-failure"),a=d();return _jsxruntime.jsx.call(void 0, _client.VaultAppView,{accessFailure:t,stampWrite:a})},"VaultHostVaultPage"),E= exports.VaultHostAuthzAdminPage =_chunkEI7MMDWYjs.a.call(void 0, ()=>{let t=i("vault-host-authz-admin-access-failure"),a=d();return _jsxruntime.jsx.call(void 0, _authzreactrouter.AuthzAdminAppView,{accessFailure:t,stampWrite:a})},"VaultHostAuthzAdminPage"),Z= exports.VaultHostUserAdminPage =_chunkEI7MMDWYjs.a.call(void 0, ()=>{let{paths:t}=n(),a=i("vault-host-user-admin-access-failure"),s=d();return _jsxruntime.jsx.call(void 0, _admin.AuthUserAdminAppView,{basePath:t.userAdmin,accessFailure:a,stampWrite:s})},"VaultHostUserAdminPage");var _core = require('@aiquants/console-ui/core');var M=_chunkEI7MMDWYjs.a.call(void 0, ({children:t})=>{let{signedIn:a,paths:s,locale:o,timeZone:u}=n(),r=m(),V=_reactrouter.useNavigate.call(void 0, ),g=i("vault-host-shell-access-failure"),p=_chunkEI7MMDWYjs.a.call(void 0, H=>()=>{V(H)},"go");return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, _consoleui.ConsoleUiRoot,{locale:o,formatLocale:r.formatLocale,timeZone:u,accessFailure:g,testId:"vault-host-shell",children:_jsxruntime.jsx.call(void 0, "header",{"data-testid":"vault-host-header",children:a===null?null:_jsxruntime.jsxs.call(void 0, _consoleui.Cluster,{gap:"space-4",testId:"vault-host-header-bar",children:[_jsxruntime.jsx.call(void 0, "nav",{"aria-label":r.nav.label,"data-testid":"vault-host-nav",children:_jsxruntime.jsxs.call(void 0, _consoleui.Cluster,{gap:"space-2",testId:"vault-host-nav-links",children:[_jsxruntime.jsx.call(void 0, _consoleui.Link,{onNavigate:p(s.vault),testId:"vault-host-nav-vault",children:r.nav.vault}),_jsxruntime.jsx.call(void 0, _consoleui.Link,{onNavigate:p(s.authzAdmin),testId:"vault-host-nav-authz-admin",children:r.nav.authzAdmin}),_jsxruntime.jsx.call(void 0, _consoleui.Link,{onNavigate:p(s.userAdmin),testId:"vault-host-nav-user-admin",children:r.nav.userAdmin})]})}),_jsxruntime.jsxs.call(void 0, _consoleui.Cluster,{gap:"space-2",testId:"vault-host-account",children:[_jsxruntime.jsx.call(void 0, _consoleui.Text,{fg:"fg-secondary",type:"body",testId:"vault-host-signed-in-as",children:_core.fillLabel.call(void 0, r.signedInAs,{name:a.displayName})}),_jsxruntime.jsx.call(void 0, _consoleui.Link,{onNavigate:p(s.signOut),testId:"vault-host-sign-out",children:r.signOut})]})]})})}),_jsxruntime.jsx.call(void 0, "main",{"data-testid":"vault-host-main",children:t})]})},"VaultHostShell");var S="Sign In with Google",nt= exports.VaultHostSignInPage =_chunkEI7MMDWYjs.a.call(void 0, ()=>{let{error:t}=_reactrouter.useLoaderData.call(void 0, ),{locale:a,timeZone:s}=n(),o=m(),u=i("vault-host-sign-in-access-failure");return _jsxruntime.jsx.call(void 0, _consoleui.ConsoleUiRoot,{locale:a,formatLocale:o.formatLocale,timeZone:s,accessFailure:u,testId:"vault-host-sign-in-root",children:_jsxruntime.jsxs.call(void 0, _consoleui.Stack,{gap:"space-4",testId:"vault-host-sign-in",children:[_jsxruntime.jsx.call(void 0, _consoleui.Heading,{level:1,type:"display",testId:"vault-host-sign-in-title",children:o.signIn.title}),_jsxruntime.jsx.call(void 0, _consoleui.Text,{fg:"fg-secondary",type:"body",as:"p",testId:"vault-host-sign-in-description",children:o.signIn.description}),t===null?null:_jsxruntime.jsx.call(void 0, _consoleui.Notice,{tone:"warning",testId:"vault-host-sign-in-error",children:t}),_jsxruntime.jsxs.call(void 0, _reactrouter.Form,{method:"post","data-testid":"vault-host-sign-in-form",children:[_jsxruntime.jsx.call(void 0, "input",{type:"hidden",name:"_action",value:S}),_jsxruntime.jsx.call(void 0, _consoleui.Button,{variant:"primary",type:"submit",testId:"vault-host-sign-in-submit",children:o.signIn.button})]})]})})},"VaultHostSignInPage");exports.GOOGLE_SIGN_IN_INTENT = S; exports.VAULT_HOST_ROOT_ROUTE_ID = _chunkJ2KNKMKOjs.b; exports.VaultHostAuthzAdminPage = E; exports.VaultHostShell = M; exports.VaultHostSignInPage = nt; exports.VaultHostUserAdminPage = Z; exports.VaultHostVaultPage = j; exports.englishClientLabels = b; exports.japaneseClientLabels = y; exports.useVaultHostAccessFailure = i; exports.useVaultHostLabels = m; exports.useVaultHostRoot = n; exports.useVaultHostStampWrite = d;
@@ -0,0 +1 @@
1
+ import{b as h}from"./chunk-T6OT6WLH.mjs";import{a as e}from"./chunk-YSXGDEY5.mjs";import{accessFailureView as N,resolveAccessFailureLabels as P}from"@aiquants/auth-core";import{signInPathWithReturnTo as z}from"@aiquants/auth-react-router/return-to";import{AccessFailureNotice as T}from"@aiquants/console-ui";import{useMemo as W}from"react";import{useLocation as _,useNavigate as k}from"react-router";import{stampReader as R}from"@aiquants/auth-core";import{useCallback as x}from"react";import{useRouteLoaderData as C}from"react-router";var b=Object.freeze({formatLocale:"en-US",nav:Object.freeze({label:"Vault menu",vault:"Vault",authzAdmin:"Permissions",userAdmin:"Users and groups"}),signedInAs:"Signed in as {name}",signOut:"Sign out",signIn:Object.freeze({title:"Sign in to the vault",description:"Sign in with your organization's Google Workspace account. Only the members of the vault's sign-in groups can enter.",button:"Sign in with Google"})});var y=Object.freeze({formatLocale:"ja-JP",nav:Object.freeze({label:"\u4FDD\u7BA1\u5EAB\u306E\u30E1\u30CB\u30E5\u30FC",vault:"\u4FDD\u7BA1\u5EAB",authzAdmin:"\u6A29\u9650\u306E\u7BA1\u7406",userAdmin:"\u5229\u7528\u8005\u3068\u30B0\u30EB\u30FC\u30D7"}),signedInAs:"{name} \u3067\u30B5\u30A4\u30F3\u30A4\u30F3\u4E2D",signOut:"\u30B5\u30A4\u30F3\u30A2\u30A6\u30C8",signIn:Object.freeze({title:"\u4FDD\u7BA1\u5EAB\u306B\u30B5\u30A4\u30F3\u30A4\u30F3",description:"\u7D44\u7E54\u306E Google Workspace \u306E\u30A2\u30AB\u30A6\u30F3\u30C8\u3067\u30B5\u30A4\u30F3\u30A4\u30F3\u3057\u307E\u3059\u3002\u4FDD\u7BA1\u5EAB\u306E\u30B5\u30A4\u30F3\u30A4\u30F3\u3092\u8A31\u3059\u30B0\u30EB\u30FC\u30D7\u306E\u4EBA\u3060\u3051\u304C\u5165\u308C\u307E\u3059\u3002",button:"Google \u3067\u30B5\u30A4\u30F3\u30A4\u30F3"})});var n=e(()=>{let t=C(h);if(t===void 0)throw new Error(`[@aiquants/vault-host] the root route (${h}) has no data; export the host's routes.root.loader from app/root.tsx`);return t},"useVaultHostRoot"),m=e(()=>n().locale==="ja"?y:b,"useVaultHostLabels"),d=e(()=>{let{readerStamp:t}=n();return x(a=>R(a,t),[t])},"useVaultHostStampWrite");import{jsx as U}from"react/jsx-runtime";var i=e(t=>{let{locale:a,paths:s}=n(),o=k(),{pathname:u,search:r}=_();return W(()=>{let V=P(a),g=e(()=>{o(z(s.signIn,`${u}${r}`))},"signIn"),H={"sign-in":g,"sign-in-again":g,back:e(()=>{o(-1)},"back"),top:e(()=>{o(s.vault)},"top")};return F=>{let O=N(F,{signedIn:!0,keepsWork:!1},V);return U(T,{view:O,handlers:H,testId:t})}},[a,s,o,u,r,t])},"useVaultHostAccessFailure");import{AuthUserAdminAppView as w}from"@aiquants/auth-react-router/admin";import{AuthzAdminAppView as G}from"@aiquants/authz-react-router";import{VaultAppView as D}from"@aiquants/vault-react-router/client";import{jsx as I}from"react/jsx-runtime";var j=e(()=>{let t=i("vault-host-vault-access-failure"),a=d();return I(D,{accessFailure:t,stampWrite:a})},"VaultHostVaultPage"),E=e(()=>{let t=i("vault-host-authz-admin-access-failure"),a=d();return I(G,{accessFailure:t,stampWrite:a})},"VaultHostAuthzAdminPage"),Z=e(()=>{let{paths:t}=n(),a=i("vault-host-user-admin-access-failure"),s=d();return I(w,{basePath:t.userAdmin,accessFailure:a,stampWrite:s})},"VaultHostUserAdminPage");import{Cluster as A,ConsoleUiRoot as $,Link as v,Text as B}from"@aiquants/console-ui";import{fillLabel as q}from"@aiquants/console-ui/core";import{useNavigate as J}from"react-router";import{Fragment as K,jsx as l,jsxs as f}from"react/jsx-runtime";var M=e(({children:t})=>{let{signedIn:a,paths:s,locale:o,timeZone:u}=n(),r=m(),V=J(),g=i("vault-host-shell-access-failure"),p=e(H=>()=>{V(H)},"go");return f(K,{children:[l($,{locale:o,formatLocale:r.formatLocale,timeZone:u,accessFailure:g,testId:"vault-host-shell",children:l("header",{"data-testid":"vault-host-header",children:a===null?null:f(A,{gap:"space-4",testId:"vault-host-header-bar",children:[l("nav",{"aria-label":r.nav.label,"data-testid":"vault-host-nav",children:f(A,{gap:"space-2",testId:"vault-host-nav-links",children:[l(v,{onNavigate:p(s.vault),testId:"vault-host-nav-vault",children:r.nav.vault}),l(v,{onNavigate:p(s.authzAdmin),testId:"vault-host-nav-authz-admin",children:r.nav.authzAdmin}),l(v,{onNavigate:p(s.userAdmin),testId:"vault-host-nav-user-admin",children:r.nav.userAdmin})]})}),f(A,{gap:"space-2",testId:"vault-host-account",children:[l(B,{fg:"fg-secondary",type:"body",testId:"vault-host-signed-in-as",children:q(r.signedInAs,{name:a.displayName})}),l(v,{onNavigate:p(s.signOut),testId:"vault-host-sign-out",children:r.signOut})]})]})})}),l("main",{"data-testid":"vault-host-main",children:t})]})},"VaultHostShell");import{Button as Q,ConsoleUiRoot as X,Heading as Y,Notice as tt,Stack as et,Text as at}from"@aiquants/console-ui";import{Form as st,useLoaderData as ot}from"react-router";import{jsx as c,jsxs as L}from"react/jsx-runtime";var S="Sign In with Google",nt=e(()=>{let{error:t}=ot(),{locale:a,timeZone:s}=n(),o=m(),u=i("vault-host-sign-in-access-failure");return c(X,{locale:a,formatLocale:o.formatLocale,timeZone:s,accessFailure:u,testId:"vault-host-sign-in-root",children:L(et,{gap:"space-4",testId:"vault-host-sign-in",children:[c(Y,{level:1,type:"display",testId:"vault-host-sign-in-title",children:o.signIn.title}),c(at,{fg:"fg-secondary",type:"body",as:"p",testId:"vault-host-sign-in-description",children:o.signIn.description}),t===null?null:c(tt,{tone:"warning",testId:"vault-host-sign-in-error",children:t}),L(st,{method:"post","data-testid":"vault-host-sign-in-form",children:[c("input",{type:"hidden",name:"_action",value:S}),c(Q,{variant:"primary",type:"submit",testId:"vault-host-sign-in-submit",children:o.signIn.button})]})]})})},"VaultHostSignInPage");export{S as GOOGLE_SIGN_IN_INTENT,h as VAULT_HOST_ROOT_ROUTE_ID,E as VaultHostAuthzAdminPage,M as VaultHostShell,nt as VaultHostSignInPage,Z as VaultHostUserAdminPage,j as VaultHostVaultPage,b as englishClientLabels,y as japaneseClientLabels,i as useVaultHostAccessFailure,m as useVaultHostLabels,n as useVaultHostRoot,d as useVaultHostStampWrite};
@@ -0,0 +1,20 @@
1
+ import { VaultDrizzleDatabase, VaultSessionConnection } from "@aiquants/vault-drizzle";
2
+ import { config } from "mssql";
3
+ type VaultHostEnvironment = Readonly<Record<string, string | undefined>>;
4
+ declare class VaultHostConfigError extends Error {
5
+ readonly keys: readonly string[];
6
+ constructor(problems: readonly {
7
+ readonly key: string;
8
+ readonly rule: string;
9
+ }[]);
10
+ }
11
+ type VaultHostDatabase = VaultDrizzleDatabase;
12
+ type VaultHostConnection = {
13
+ readonly db: VaultHostDatabase;
14
+ readonly open: () => Promise<void>;
15
+ readonly close: () => Promise<void>;
16
+ readonly openSession: () => Promise<VaultSessionConnection>;
17
+ };
18
+ type VaultHostConnect = (config: config) => VaultHostConnection;
19
+ declare const nodeMssqlVaultHostConnection: VaultHostConnect;
20
+ export { type VaultHostEnvironment as V, type VaultHostConnect as a, VaultHostConfigError as b, type VaultHostConnection as c, type VaultHostDatabase as d, nodeMssqlVaultHostConnection as n };
@@ -0,0 +1,20 @@
1
+ import { VaultDrizzleDatabase, VaultSessionConnection } from "@aiquants/vault-drizzle";
2
+ import { config } from "mssql";
3
+ type VaultHostEnvironment = Readonly<Record<string, string | undefined>>;
4
+ declare class VaultHostConfigError extends Error {
5
+ readonly keys: readonly string[];
6
+ constructor(problems: readonly {
7
+ readonly key: string;
8
+ readonly rule: string;
9
+ }[]);
10
+ }
11
+ type VaultHostDatabase = VaultDrizzleDatabase;
12
+ type VaultHostConnection = {
13
+ readonly db: VaultHostDatabase;
14
+ readonly open: () => Promise<void>;
15
+ readonly close: () => Promise<void>;
16
+ readonly openSession: () => Promise<VaultSessionConnection>;
17
+ };
18
+ type VaultHostConnect = (config: config) => VaultHostConnection;
19
+ declare const nodeMssqlVaultHostConnection: VaultHostConnect;
20
+ export { type VaultHostEnvironment as V, type VaultHostConnect as a, VaultHostConfigError as b, type VaultHostConnection as c, type VaultHostDatabase as d, nodeMssqlVaultHostConnection as n };
@@ -0,0 +1,23 @@
1
+ type VaultHostLocale = "en" | "ja";
2
+ declare const VAULT_HOST_LOCALES: readonly VaultHostLocale[];
3
+ type VaultHostPaths = {
4
+ readonly vault: string;
5
+ readonly signIn: string;
6
+ readonly signInCallback: string;
7
+ readonly signOut: string;
8
+ readonly authzAdmin: string;
9
+ readonly userAdmin: string;
10
+ };
11
+ type VaultHostSignedInPerson = {
12
+ readonly displayName: string;
13
+ readonly email: string | null;
14
+ };
15
+ type VaultHostRootData = {
16
+ readonly signedIn: VaultHostSignedInPerson | null;
17
+ readonly readerStamp: string;
18
+ readonly locale: VaultHostLocale;
19
+ readonly timeZone: string;
20
+ readonly paths: VaultHostPaths;
21
+ };
22
+ declare const VAULT_HOST_ROOT_ROUTE_ID = "root";
23
+ export { type VaultHostRootData as V, VAULT_HOST_ROOT_ROUTE_ID as a, type VaultHostLocale as b, type VaultHostPaths as c, type VaultHostSignedInPerson as d, VAULT_HOST_LOCALES as e };
@@ -0,0 +1,23 @@
1
+ type VaultHostLocale = "en" | "ja";
2
+ declare const VAULT_HOST_LOCALES: readonly VaultHostLocale[];
3
+ type VaultHostPaths = {
4
+ readonly vault: string;
5
+ readonly signIn: string;
6
+ readonly signInCallback: string;
7
+ readonly signOut: string;
8
+ readonly authzAdmin: string;
9
+ readonly userAdmin: string;
10
+ };
11
+ type VaultHostSignedInPerson = {
12
+ readonly displayName: string;
13
+ readonly email: string | null;
14
+ };
15
+ type VaultHostRootData = {
16
+ readonly signedIn: VaultHostSignedInPerson | null;
17
+ readonly readerStamp: string;
18
+ readonly locale: VaultHostLocale;
19
+ readonly timeZone: string;
20
+ readonly paths: VaultHostPaths;
21
+ };
22
+ declare const VAULT_HOST_ROOT_ROUTE_ID = "root";
23
+ export { type VaultHostRootData as V, VAULT_HOST_ROOT_ROUTE_ID as a, type VaultHostLocale as b, type VaultHostPaths as c, type VaultHostSignedInPerson as d, VAULT_HOST_LOCALES as e };
@@ -0,0 +1,89 @@
1
+ import { V as VaultHostEnvironment, a as VaultHostConnect } from "./connect-ZEgTyJ3x.mjs";
2
+ export { b as VaultHostConfigError, c as VaultHostConnection, d as VaultHostDatabase, n as nodeMssqlVaultHostConnection } from "./connect-ZEgTyJ3x.mjs";
3
+ import { createUserAdminApp } from "@aiquants/auth-react-router/admin";
4
+ import { AuthServer } from "@aiquants/auth-react-router/server";
5
+ import { createAuthzAdminApp } from "@aiquants/authz-react-router";
6
+ import { VaultLogger, VaultLogDetails, VaultPlacementRule, Vault } from "@aiquants/vault-core";
7
+ import { VaultApp, vaultRouteHeaders } from "@aiquants/vault-react-router/server";
8
+ import { LoaderFunctionArgs, ActionFunctionArgs } from "react-router";
9
+ import { c as VaultHostPaths, b as VaultHostLocale, V as VaultHostRootData } from "./contract-Ck9emmKB.mjs";
10
+ export { e as VAULT_HOST_LOCALES, a as VAULT_HOST_ROOT_ROUTE_ID, d as VaultHostSignedInPerson } from "./contract-Ck9emmKB.mjs";
11
+ import "@aiquants/vault-drizzle";
12
+ import "mssql";
13
+ type VaultHostLogger = VaultLogger & {
14
+ readonly info: (code: string, details: VaultLogDetails) => void;
15
+ };
16
+ type VaultHostSchemas = {
17
+ readonly vault: string;
18
+ readonly authz: string;
19
+ readonly users: string;
20
+ readonly parameters: string;
21
+ };
22
+ declare const VAULT_HOST_APP_NAME = "aiquants-vault-host";
23
+ type VaultHostPlacement = {
24
+ readonly secretIdRule: (candidate: string) => boolean;
25
+ readonly compartmentOf: VaultPlacementRule;
26
+ readonly listWhileSealed: boolean;
27
+ };
28
+ type CreateVaultHostOptions = {
29
+ readonly env: VaultHostEnvironment;
30
+ readonly placement: VaultHostPlacement;
31
+ readonly paths: VaultHostPaths;
32
+ readonly schemas: VaultHostSchemas;
33
+ readonly locale: VaultHostLocale;
34
+ readonly authzAdminResource: {
35
+ readonly key: string;
36
+ readonly name: string;
37
+ };
38
+ readonly logger: VaultHostLogger;
39
+ readonly connect: VaultHostConnect;
40
+ };
41
+ type VaultHostAuthzAdminApp = ReturnType<typeof createAuthzAdminApp>;
42
+ type VaultHostUserAdminApp = ReturnType<typeof createUserAdminApp>;
43
+ type VaultHostRoutes = {
44
+ readonly root: {
45
+ readonly loader: (args: {
46
+ readonly request: Request;
47
+ }) => Promise<VaultHostRootData>;
48
+ };
49
+ readonly vault: {
50
+ readonly loader: (args: LoaderFunctionArgs) => Promise<Awaited<ReturnType<VaultApp["ui"]["loader"]>>>;
51
+ readonly action: (args: ActionFunctionArgs) => ReturnType<VaultApp["ui"]["action"]>;
52
+ readonly headers: typeof vaultRouteHeaders;
53
+ };
54
+ readonly vaultApi: {
55
+ readonly action: (args: ActionFunctionArgs) => ReturnType<VaultApp["api"]["action"]>;
56
+ };
57
+ readonly signIn: {
58
+ readonly loader: (args: LoaderFunctionArgs) => ReturnType<AuthServer["loginLoader"]>;
59
+ readonly action: (args: ActionFunctionArgs) => ReturnType<AuthServer["loginAction"]>;
60
+ };
61
+ readonly signInCallback: {
62
+ readonly loader: (args: LoaderFunctionArgs) => ReturnType<AuthServer["googleCallbackLoader"]>;
63
+ };
64
+ readonly signOut: {
65
+ readonly loader: (args: {
66
+ readonly request: Request;
67
+ }) => Promise<never>;
68
+ };
69
+ readonly authzAdmin: Pick<VaultHostAuthzAdminApp, "loader" | "action">;
70
+ readonly userAdmin: Pick<VaultHostUserAdminApp, "loader" | "action">;
71
+ };
72
+ type VaultHost = {
73
+ readonly vault: Vault;
74
+ readonly vaultApp: VaultApp;
75
+ readonly auth: AuthServer;
76
+ readonly authzAdmin: VaultHostAuthzAdminApp;
77
+ readonly userAdmin: VaultHostUserAdminApp;
78
+ readonly routes: VaultHostRoutes;
79
+ readonly start: () => Promise<void>;
80
+ readonly dispose: () => Promise<void>;
81
+ readonly locale: VaultHostLocale;
82
+ readonly paths: VaultHostPaths;
83
+ };
84
+ declare const createVaultHost: (options: CreateVaultHostOptions) => VaultHost;
85
+ declare const DIRECTORY_STALENESS_PARAMETER: {
86
+ readonly category: "directory";
87
+ readonly key: "AUTH_DIRECTORY_STALENESS_SECONDS";
88
+ };
89
+ export { type CreateVaultHostOptions, DIRECTORY_STALENESS_PARAMETER, VAULT_HOST_APP_NAME, type VaultHost, VaultHostConnect, VaultHostEnvironment, VaultHostLocale, type VaultHostLogger, VaultHostPaths, type VaultHostPlacement, VaultHostRootData, type VaultHostRoutes, type VaultHostSchemas, createVaultHost };
@@ -0,0 +1,89 @@
1
+ import { V as VaultHostEnvironment, a as VaultHostConnect } from "./connect-ZEgTyJ3x.js";
2
+ export { b as VaultHostConfigError, c as VaultHostConnection, d as VaultHostDatabase, n as nodeMssqlVaultHostConnection } from "./connect-ZEgTyJ3x.js";
3
+ import { createUserAdminApp } from "@aiquants/auth-react-router/admin";
4
+ import { AuthServer } from "@aiquants/auth-react-router/server";
5
+ import { createAuthzAdminApp } from "@aiquants/authz-react-router";
6
+ import { VaultLogger, VaultLogDetails, VaultPlacementRule, Vault } from "@aiquants/vault-core";
7
+ import { VaultApp, vaultRouteHeaders } from "@aiquants/vault-react-router/server";
8
+ import { LoaderFunctionArgs, ActionFunctionArgs } from "react-router";
9
+ import { c as VaultHostPaths, b as VaultHostLocale, V as VaultHostRootData } from "./contract-Ck9emmKB.js";
10
+ export { e as VAULT_HOST_LOCALES, a as VAULT_HOST_ROOT_ROUTE_ID, d as VaultHostSignedInPerson } from "./contract-Ck9emmKB.js";
11
+ import "@aiquants/vault-drizzle";
12
+ import "mssql";
13
+ type VaultHostLogger = VaultLogger & {
14
+ readonly info: (code: string, details: VaultLogDetails) => void;
15
+ };
16
+ type VaultHostSchemas = {
17
+ readonly vault: string;
18
+ readonly authz: string;
19
+ readonly users: string;
20
+ readonly parameters: string;
21
+ };
22
+ declare const VAULT_HOST_APP_NAME = "aiquants-vault-host";
23
+ type VaultHostPlacement = {
24
+ readonly secretIdRule: (candidate: string) => boolean;
25
+ readonly compartmentOf: VaultPlacementRule;
26
+ readonly listWhileSealed: boolean;
27
+ };
28
+ type CreateVaultHostOptions = {
29
+ readonly env: VaultHostEnvironment;
30
+ readonly placement: VaultHostPlacement;
31
+ readonly paths: VaultHostPaths;
32
+ readonly schemas: VaultHostSchemas;
33
+ readonly locale: VaultHostLocale;
34
+ readonly authzAdminResource: {
35
+ readonly key: string;
36
+ readonly name: string;
37
+ };
38
+ readonly logger: VaultHostLogger;
39
+ readonly connect: VaultHostConnect;
40
+ };
41
+ type VaultHostAuthzAdminApp = ReturnType<typeof createAuthzAdminApp>;
42
+ type VaultHostUserAdminApp = ReturnType<typeof createUserAdminApp>;
43
+ type VaultHostRoutes = {
44
+ readonly root: {
45
+ readonly loader: (args: {
46
+ readonly request: Request;
47
+ }) => Promise<VaultHostRootData>;
48
+ };
49
+ readonly vault: {
50
+ readonly loader: (args: LoaderFunctionArgs) => Promise<Awaited<ReturnType<VaultApp["ui"]["loader"]>>>;
51
+ readonly action: (args: ActionFunctionArgs) => ReturnType<VaultApp["ui"]["action"]>;
52
+ readonly headers: typeof vaultRouteHeaders;
53
+ };
54
+ readonly vaultApi: {
55
+ readonly action: (args: ActionFunctionArgs) => ReturnType<VaultApp["api"]["action"]>;
56
+ };
57
+ readonly signIn: {
58
+ readonly loader: (args: LoaderFunctionArgs) => ReturnType<AuthServer["loginLoader"]>;
59
+ readonly action: (args: ActionFunctionArgs) => ReturnType<AuthServer["loginAction"]>;
60
+ };
61
+ readonly signInCallback: {
62
+ readonly loader: (args: LoaderFunctionArgs) => ReturnType<AuthServer["googleCallbackLoader"]>;
63
+ };
64
+ readonly signOut: {
65
+ readonly loader: (args: {
66
+ readonly request: Request;
67
+ }) => Promise<never>;
68
+ };
69
+ readonly authzAdmin: Pick<VaultHostAuthzAdminApp, "loader" | "action">;
70
+ readonly userAdmin: Pick<VaultHostUserAdminApp, "loader" | "action">;
71
+ };
72
+ type VaultHost = {
73
+ readonly vault: Vault;
74
+ readonly vaultApp: VaultApp;
75
+ readonly auth: AuthServer;
76
+ readonly authzAdmin: VaultHostAuthzAdminApp;
77
+ readonly userAdmin: VaultHostUserAdminApp;
78
+ readonly routes: VaultHostRoutes;
79
+ readonly start: () => Promise<void>;
80
+ readonly dispose: () => Promise<void>;
81
+ readonly locale: VaultHostLocale;
82
+ readonly paths: VaultHostPaths;
83
+ };
84
+ declare const createVaultHost: (options: CreateVaultHostOptions) => VaultHost;
85
+ declare const DIRECTORY_STALENESS_PARAMETER: {
86
+ readonly category: "directory";
87
+ readonly key: "AUTH_DIRECTORY_STALENESS_SECONDS";
88
+ };
89
+ export { type CreateVaultHostOptions, DIRECTORY_STALENESS_PARAMETER, VAULT_HOST_APP_NAME, type VaultHost, VaultHostConnect, VaultHostEnvironment, VaultHostLocale, type VaultHostLogger, VaultHostPaths, type VaultHostPlacement, VaultHostRootData, type VaultHostRoutes, type VaultHostSchemas, createVaultHost };
package/dist/server.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunkQJKY44QOjs = require('./chunk-QJKY44QO.js');var _chunkJ2KNKMKOjs = require('./chunk-J2KNKMKO.js');var _chunkEI7MMDWYjs = require('./chunk-EI7MMDWY.js');var _authdirectorydrizzle = require('@aiquants/auth-directory-drizzle');var _admin = require('@aiquants/auth-react-router/admin');var _server = require('@aiquants/auth-react-router/server');var _authzreactrouter = require('@aiquants/authz-react-router');var _drizzle = require('@aiquants/mssql/drizzle');var _vaultcore = require('@aiquants/vault-core');var _vaultdrizzle = require('@aiquants/vault-drizzle');var _server3 = require('@aiquants/vault-react-router/server');var _authdirectorycore = require('@aiquants/auth-directory-core');var _authzcore = require('@aiquants/authz-core');var _authzdrizzle = require('@aiquants/authz-drizzle');var _authz = require('@aiquants/vault-core/authz');var _drizzleorm = require('drizzle-orm');var _crypto = require('crypto');var _=_chunkEI7MMDWYjs.a.call(void 0, (e,t,n,a)=>({uuid:_crypto.randomUUID.call(void 0, ),username:e,displayId:e,displayName:t,isPasswordDisabled:!0,createdAt:n,createdBy:a,updatedAt:n,updatedBy:a}),"newUserValues"),K=_chunkEI7MMDWYjs.a.call(void 0, (e,t)=>async(n,a)=>{let[i]=await e.select({userId:t.users.id,displayName:t.users.displayName,userActive:t.users.isActive,subjectActive:t.openid.isActive}).from(t.openid).innerJoin(t.users,_drizzleorm.eq.call(void 0, t.users.id,t.openid.userId)).where(_drizzleorm.and.call(void 0, _drizzleorm.eq.call(void 0, t.openid.provider,n),_drizzleorm.eq.call(void 0, t.openid.openid,a)));return i===void 0?null:{userId:i.userId,displayName:i.displayName,active:i.userActive&&i.subjectActive}},"personLookupOf");var Ae=_chunkEI7MMDWYjs.a.call(void 0, (e,t,n)=>({many:_chunkEI7MMDWYjs.a.call(void 0, a=>_authzdrizzle.getEffectivePermissionsMany.call(void 0, e,t.authz,a),"many"),resourceKeys:_chunkEI7MMDWYjs.a.call(void 0, a=>_authzdrizzle.listResourceKeys.call(void 0, e,t.authz,n,a),"resourceKeys")}),"drizzlePermissionSourceOf"),he=_chunkEI7MMDWYjs.a.call(void 0, e=>{let t=new WeakMap;return n=>{let a=t.get(n);if(a!==void 0)return a;let i=e(n);return t.set(n,i),i}},"perRequest"),be=_chunkEI7MMDWYjs.a.call(void 0, e=>{let{db:t,tables:n,identity:a,appKey:i,logger:u}=e,{tenantId:c,directoryLinkStore:p}=a,y=Object.freeze([c]),A=K(t,n),d=n.authz.TDGroupMember,f=he(async l=>{let m=await e.sessionUserOf(l);if(m===void 0)return null;let o=await A(m.provider,m.id);return o===null||!o.active?null:{profile:m,userId:o.userId,displayName:o.displayName}}),R=_chunkEI7MMDWYjs.a.call(void 0, async l=>{let m=await f(l);return m===null?null:m.userId},"resolveUserId"),b=_chunkEI7MMDWYjs.a.call(void 0, async l=>(await t.select({groupId:d.groupId}).from(d).where(_drizzleorm.eq.call(void 0, d.userId,l))).map(o=>o.groupId),"groupIdsOfUser"),k=he(async l=>{let m=await R(l);return m===null?[]:b(m)}),O=new WeakMap,E=_chunkEI7MMDWYjs.a.call(void 0, async(l,m)=>{let o=await f(l),s=await p.loadTenantMembershipPolicy(c),g=_chunkEI7MMDWYjs.a.call(void 0, (Y,Z)=>_authdirectorycore.evaluateTenantMembership.call(void 0, {requestedTenantId:m,servedTenantIds:y,userId:o===null?null:o.userId,policy:s,localGroupIds:Y,ledgerGroupIds:Z}),"evaluate");if(o===null||s.kind==="no-proof-required")return g([],[]).isMember;let[h]=o.profile.emails,[T,N]=await Promise.all([k(l),p.listLedgerGroupIds(c,{provider:o.profile.provider,externalUserId:o.profile.id,email:h===void 0?null:h.value})]),G=g(T,N);return G.isMember||u.info("vault-host-tenant-membership-denied",{operation:"authorize",compartment:null,secretId:null,version:null,reason:G.reason,cause:null}),G.isMember},"isTenantMember"),S=_chunkEI7MMDWYjs.a.call(void 0, (l,m)=>{let o=O.get(l);o===void 0&&(o=new Map,O.set(l,o));let s=o.get(m);if(s!==void 0)return s;let g=E(l,m);return o.set(m,g),g},"assertTenantMembership"),V=_authzreactrouter.createAuthz.call(void 0, {appKey:i,resolveUserId:R,resolveTenantId:_chunkEI7MMDWYjs.a.call(void 0, ()=>c,"resolveTenantId"),assertTenantMembership:S,resolveGroupIds:_chunkEI7MMDWYjs.a.call(void 0, l=>k(l),"resolveGroupIds"),getEffectivePermissions:_chunkEI7MMDWYjs.a.call(void 0, l=>e.permissions.many(l),"getEffectivePermissions"),listResourceKeys:_chunkEI7MMDWYjs.a.call(void 0, (l,m)=>e.permissions.resourceKeys(m),"listResourceKeys")}),x=_authzcore.createRequirePermissions.call(void 0, {resolveTenantId:_chunkEI7MMDWYjs.a.call(void 0, ()=>c,"resolveTenantId"),resolveUserId:R,assertTenantMembership:_chunkEI7MMDWYjs.a.call(void 0, ({ctx:l,tenantId:m})=>S(l,m),"assertTenantMembership"),getEffectivePermissionsMany:_chunkEI7MMDWYjs.a.call(void 0, async l=>e.permissions.many({...l,groupIds:l.userId===null?[]:await b(Number(l.userId))}),"getEffectivePermissionsMany"),scopedGrants:"deny"}),H=new WeakMap,z=_authz.createAuthzVaultAuthorizer.call(void 0, {requirePermissions:_chunkEI7MMDWYjs.a.call(void 0, (l,m)=>x(l,m),"requirePermissions"),contextOf:_chunkEI7MMDWYjs.a.call(void 0, l=>{let m=H.get(l);if(m===void 0)throw new Error("[@aiquants/vault-host] the vault asked about a request context this host's resolveContext did not make");return m},"contextOf"),appKey:i,resourcePrefix:e.resourcePrefix});return{signedInOf:f,resolveUserId:R,requirePermission:V.requirePermission,getMyPermissions:V.getMyPermissions,vaultAuthorizer:z,rememberContext:_chunkEI7MMDWYjs.a.call(void 0, (l,m)=>(H.set(l,m),l),"rememberContext")}},"createVaultHostAuthz");var _authcore = require('@aiquants/auth-core');var we=_chunkEI7MMDWYjs.a.call(void 0, e=>async t=>{let n=await e.authz.signedInOf(t);if(n===null)throw _authcore.accessFailureResponse.call(void 0, "unauthenticated");let a=t.headers.get(e.clientAddressHeader);if(a===null||a.trim()==="")throw new Error(`[@aiquants/vault-host] the trusted proxy wrote no client address into ${e.clientAddressHeader}`);if(n.displayName===null||n.displayName.trim()==="")throw new Error(`[@aiquants/vault-host] user ${n.userId} has no display name; set it on the user admin screen`);let i={actor:{kind:"user",id:String(n.userId),displayName:n.displayName},origin:{kind:"request",address:a,userAgent:_server3.vaultUserAgentOf.call(void 0, t)},requestId:t.headers.get(e.requestIdHeader)};return e.authz.rememberContext(i,t)},"createVaultHostContextResolver");var _async_hooks = require('async_hooks');var C={category:"directory",key:"AUTH_DIRECTORY_STALENESS_SECONDS"},lt="SYSTEM",dt=_chunkEI7MMDWYjs.a.call(void 0, async(e,t,n)=>{let a=t.systemParameter,i=await e.select({tenantId:a.tenantId,value:a.value}).from(a).where(_drizzleorm.and.call(void 0, _drizzleorm.eq.call(void 0, a.category,C.category),_drizzleorm.eq.call(void 0, a.key,C.key))),u=i.find(y=>y.tenantId===n),c=u===void 0?i.find(y=>y.tenantId===lt):u,p=c!==void 0&&/^[1-9]\d*$/u.test(c.value)?Number(c.value):Number.NaN;if(!Number.isSafeInteger(p))throw new Error(`[@aiquants/vault-host] the system parameter ${C.category}/${C.key} must be a positive integer for the tenant or SYSTEM`);return p},"readDirectoryStalenessSeconds"),ct=_chunkEI7MMDWYjs.a.call(void 0, e=>({users:{table:e.users,id:e.users.id,email:e.users.email,isActive:e.users.isActive},subjects:{table:e.openid,provider:e.openid.provider,subject:e.openid.openid,userId:e.openid.userId,isActive:e.openid.isActive}}),"openidBindingOf"),pt=_chunkEI7MMDWYjs.a.call(void 0, e=>({onRetry:_chunkEI7MMDWYjs.a.call(void 0, ({attempt:t,attempts:n})=>{e.warn("vault-host-authz-retried",{operation:"authz-transaction",compartment:null,secretId:null,version:null,reason:`${t}/${n-1}`,cause:null})},"onRetry")}),"authzRetryOf"),mt=_chunkEI7MMDWYjs.a.call(void 0, (e,t)=>{let n=new _async_hooks.AsyncLocalStorage,a=_chunkEI7MMDWYjs.a.call(void 0, c=>(_nullishCoalesce(n.getStore(), () => (e))).withTransaction((p,y)=>c(p,y)),"withAuthzTransaction");return{withAuthzTransaction:a,withAmbientAuthzTransaction:_chunkEI7MMDWYjs.a.call(void 0, (c,p)=>n.run(c,p),"withAmbientAuthzTransaction"),assertLinkableAndWrite:_chunkEI7MMDWYjs.a.call(void 0, (c,p,y)=>a(async(A,d)=>{await _authdirectorydrizzle.assertGroupMayBeLinked.call(void 0, A,c,p,t),await y(d)}),"assertLinkableAndWrite")}},"authzTransactionsOf"),yt=_chunkEI7MMDWYjs.a.call(void 0, (e,t)=>n=>dt(e,t,n),"stalenessReaderOf"),Ve=_chunkEI7MMDWYjs.a.call(void 0, e=>{let{db:t,tables:n,tenantId:a,appKey:i,adminResourceKey:u}=e,c=e.lockoutMessage===void 0?{}:{lockoutMessage:e.lockoutMessage},p=ct(n),y=_authdirectorydrizzle.createOpenidMemberResolver.call(void 0, t,p,{}),A=_authzdrizzle.createAuthzAdminStore.call(void 0, t,n.authz,{userTable:n.users,userScope:{kind:"global"},userActiveColumn:n.users.isActive,adminAppKey:i,adminResourceKey:u,lockPrincipal:e.lockPrincipal,transactionRetry:pt(e.logger),...c}),d={adminAppKey:i,adminResourceKey:u,message:_authdirectorydrizzle.defaultExternalGroupGuardMessage},f=mt(A,d),R=_authdirectorydrizzle.createDirectoryLinkStore.call(void 0, t,n.directory,n.authz,{linkable:{assertLinkableAndWrite:f.assertLinkableAndWrite},resolveStalenessThresholdSec:yt(t,n),isEnabled:e.directoryEnabled,provider:_authcore.GOOGLE_PROVIDER,refusals:_authdirectorydrizzle.defaultDirectoryLinkRefusals,memberResolver:y}),b=_authdirectorydrizzle.withExternalGroupGuards.call(void 0, A,{...d,linkLookup:R}),k=_authzdrizzle.createAdminLockoutGuard.call(void 0, t,n.authz,{userTable:n.users,userScope:{kind:"global"},userActiveColumn:n.users.isActive,adminAppKey:i,adminResourceKey:u,lockPrincipal:e.lockPrincipal,...c}),O=e.directoryEnabled?_authdirectorydrizzle.createDirectoryCatalogReader.call(void 0, t,n.directory,{}):null;return{tenantId:a,binding:p,memberResolver:y,authzAdminStore:b,directoryLinkStore:R,adminLockoutGuard:k,withAuthzTransaction:f.withAuthzTransaction,withAmbientAuthzTransaction:f.withAmbientAuthzTransaction,directoryCatalog:O}},"createVaultHostIdentity");var X=_chunkEI7MMDWYjs.a.call(void 0, e=>({operation:"sign-in",compartment:null,secretId:null,version:null,reason:null,cause:e}),"detailsOf"),j=_chunkEI7MMDWYjs.a.call(void 0, e=>({info:_chunkEI7MMDWYjs.a.call(void 0, (...t)=>e.info("vault-host-sign-in",X(t)),"info"),warn:_chunkEI7MMDWYjs.a.call(void 0, (...t)=>e.warn("vault-host-sign-in",X(t)),"warn"),error:_chunkEI7MMDWYjs.a.call(void 0, (...t)=>e.error("vault-host-sign-in",X(t)),"error")}),"signInLoggerOf");var _mssqlcore = require('drizzle-orm/mssql-core');var At=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u,Se=_chunkEI7MMDWYjs.a.call(void 0, e=>{for(let t of["vault","authz","users","parameters"]){let n=typeof e=="object"&&e!==null?e[t]:void 0;if(typeof n!="string"||!At.test(n))throw new RangeError(`[@aiquants/vault-host] schemas.${t} must be a regular SQL Server identifier`)}if([e.authz,e.users,e.parameters].some(t=>t.toLowerCase()===e.vault.toLowerCase()))throw new RangeError("[@aiquants/vault-host] schemas.vault must differ from the identity schemas");return Object.freeze({vault:e.vault,authz:e.authz,users:e.users,parameters:e.parameters})},"checkedSchemas"),Re=_chunkEI7MMDWYjs.a.call(void 0, e=>{let t=_mssqlcore.mssqlSchema.call(void 0, e.users),n=t.table("TDUsers",{id:_mssqlcore.bigint.call(void 0, "id",{mode:"number"}).identity().notNull(),uuid:_mssqlcore.nvarchar.call(void 0, "uuid",{length:100}),username:_mssqlcore.nvarchar.call(void 0, "username",{length:100}).notNull(),email:_mssqlcore.nvarchar.call(void 0, "email",{length:100}),hashedPassword:_mssqlcore.nvarchar.call(void 0, "hashed_password",{length:200}),isPasswordDisabled:_mssqlcore.bit.call(void 0, "is_password_disabled").notNull(),isActive:_mssqlcore.bit.call(void 0, "is_active").notNull(),displayId:_mssqlcore.nvarchar.call(void 0, "display_id",{length:100}),displayName:_mssqlcore.nvarchar.call(void 0, "display_name",{length:100}),createdAt:_mssqlcore.datetime2.call(void 0, "created_at"),createdBy:_mssqlcore.nvarchar.call(void 0, "created_by",{length:50}),updatedAt:_mssqlcore.datetime2.call(void 0, "updated_at"),updatedBy:_mssqlcore.nvarchar.call(void 0, "updated_by",{length:50})},y=>[_mssqlcore.primaryKey.call(void 0, {columns:[y.id]})]),a=t.table("TDOpenid",{id:_mssqlcore.bigint.call(void 0, "id",{mode:"number"}).identity().notNull(),provider:_mssqlcore.nvarchar.call(void 0, "provider",{length:50}).notNull(),openid:_mssqlcore.nvarchar.call(void 0, "openid",{length:1e3}).notNull(),email:_mssqlcore.nvarchar.call(void 0, "email",{length:200}),name:_mssqlcore.nvarchar.call(void 0, "name",{length:200}),givenName:_mssqlcore.nvarchar.call(void 0, "given_name",{length:200}),familyName:_mssqlcore.nvarchar.call(void 0, "family_name",{length:200}),picture:_mssqlcore.nvarchar.call(void 0, "picture",{length:"max"}),locale:_mssqlcore.nvarchar.call(void 0, "locale",{length:200}),userId:_mssqlcore.bigint.call(void 0, "user_id",{mode:"number"}).notNull(),isActive:_mssqlcore.bit.call(void 0, "is_active").notNull(),createdAt:_mssqlcore.datetime.call(void 0, "created_at").notNull(),createdBy:_mssqlcore.nvarchar.call(void 0, "created_by",{length:50}).notNull(),updatedAt:_mssqlcore.datetime.call(void 0, "updated_at"),updatedBy:_mssqlcore.nvarchar.call(void 0, "updated_by",{length:50})},y=>[_mssqlcore.primaryKey.call(void 0, {columns:[y.id]})]),i=_authzdrizzle.defineAuthzSchema.call(void 0, e.authz,{userTable:n}),u=_authdirectorydrizzle.defineAuthDirectorySchema.call(void 0, e.authz,{groupTable:i.TMGroup,userTable:n}),c=_authdirectorydrizzle.defineSessionGenerationSchema.call(void 0, e.authz),p=_mssqlcore.mssqlSchema.call(void 0, e.parameters).table("tm_system_parameter",{id:_mssqlcore.bigint.call(void 0, "id",{mode:"number"}).identity().notNull(),tenantId:_mssqlcore.nvarchar.call(void 0, "tenant_id",{length:64}).notNull(),category:_mssqlcore.nvarchar.call(void 0, "param_category",{length:32}).notNull(),key:_mssqlcore.nvarchar.call(void 0, "param_key",{length:64}).notNull(),value:_mssqlcore.nvarchar.call(void 0, "param_value",{length:"max"}).notNull()},y=>[_mssqlcore.primaryKey.call(void 0, {columns:[y.id]})]);return{users:n,openid:a,authz:i,directory:u,sessionGeneration:c,systemParameter:p}},"defineVaultHostTables");var $="signup",Vt=_chunkEI7MMDWYjs.a.call(void 0, (e,t)=>{let n=_authcore.hostedDomainAllowlist.call(void 0, [e]);return async(a,i)=>!n(i)||typeof a!="string"||a.trim()===""?!1:t.isEmailAllowedByGroup(a)},"vaultSignInRuleOf"),It=_chunkEI7MMDWYjs.a.call(void 0, e=>({identify:e.identify,lockPrincipal:e.lockPrincipal,isEmailAllowed:_chunkEI7MMDWYjs.a.call(void 0, (t,n)=>e.mayEnter(t,n.hostedDomain),"isEmailAllowed"),newUser:_chunkEI7MMDWYjs.a.call(void 0, ({identity:t,profile:n,now:a})=>_(t.email,n.displayName,a,$),"newUser"),newSubject:_chunkEI7MMDWYjs.a.call(void 0, ({identity:t,profile:n,now:a})=>({email:t.email,name:n.displayName,givenName:n.name.givenName,familyName:n.name.familyName,createdAt:a,createdBy:$,updatedAt:a,updatedBy:$}),"newSubject"),promotion:{tables:e.tables.directory,authzTables:e.tables.authz,tenantId:e.tenantId,actor:$},transactionRetry:{onRetry:_chunkEI7MMDWYjs.a.call(void 0, ({attempt:t,attempts:n})=>{e.logger.warn("vault-host-sign-up-retried",{operation:"sign-up",compartment:null,secretId:null,version:null,reason:`${t}/${n-1}`,cause:null})},"onRetry")}}),"vaultHostSignupOptions"),Te=_chunkEI7MMDWYjs.a.call(void 0, e=>{let t=Vt(e.signInDomain,e.ledger),n=K(e.db,e.tables),a=_server.createGoogleTokenVerifier.call(void 0, {clientIds:[e.googleClientId],logger:j(e.logger)}),i=_authdirectorydrizzle.createOpenidSignup.call(void 0, e.db,e.binding,It({tables:e.tables,tenantId:e.tenantId,identify:a.identify,mayEnter:t,lockPrincipal:e.signupLockPrincipal,logger:e.logger}));return{mayEnter:t,isEmailAllowed:_chunkEI7MMDWYjs.a.call(void 0, (u,c)=>t(u,c.hostedDomain),"isEmailAllowed"),isUserActive:_chunkEI7MMDWYjs.a.call(void 0, async u=>{let[c]=u.emails;if(!await t(c===void 0?null:c.value,u.hostedDomain))return!1;let p=await n(u.provider,u.id);return p===null||p.active},"isUserActive"),backendAuth:{verify:a.verify,signup:i}}},"createVaultHostSignIn");var kt=Object.freeze({items:{name:"items",description:"See, create, change and remove the items of the compartment."},values:{name:"values",description:"Reveal and copy the values of the compartment's items."},export:{name:"export",description:"Export the compartment's items as a file."},seal:{name:"Vault seal",description:"Seal the vault and take part in unsealing it."},audit:{name:"Vault audit log",description:"Read the vault's audit log."},compartments:{name:"Vault compartments",description:"Add compartments and rename them."}}),Oe=Object.freeze({authMessages:Object.freeze({emailNotVerified:"Your email address is not verified.",googleFailed:"Signing in with Google failed.",consentDenied:"You did not allow the sign-in on Google's screen, so you are not signed in.",backendFailed:"The sign-in could not be completed on the server.",notAllowed:"You may not use this application.",backendUnreachable:"The sign-in service could not be reached. Try again later.",unexpected:"An unexpected error occurred while signing in.",returnToRefused:"The sign-in did not start, because the address to return to could not be accepted.",signOutRefused:"The sign-out request was not accepted. Sign out again with the sign-out button on the screen."}),refusals:Object.freeze({userNotFound:_chunkEI7MMDWYjs.a.call(void 0, e=>`User not found: ${e}`,"userNotFound"),groupNotFound:_chunkEI7MMDWYjs.a.call(void 0, e=>`Group not found: ${e}`,"groupNotFound"),upstreamOwned:_chunkEI7MMDWYjs.a.call(void 0, e=>`The members and the name of this group are owned by the upstream directory (${e}). Change them there.`,"upstreamOwned"),patternEntriesUnused:"The vault admits people by its sign-in groups and its Google Workspace domain only, so address and domain entries are not used. Add the person to a sign-in group instead."}),resourceNameOf:_chunkEI7MMDWYjs.a.call(void 0, (e,t)=>{let n=kt[e];return t===null?n:{name:`Vault ${t.name} (${t.code}): ${n.name}`,description:n.description}},"resourceNameOf")});var St=Object.freeze({items:{name:"\u9805\u76EE",description:"\u533A\u753B\u306E\u9805\u76EE\u3092\u898B\u308B\u30FB\u4F5C\u308B\u30FB\u76F4\u3059\u30FB\u6D88\u3059\u3002"},values:{name:"\u5024",description:"\u533A\u753B\u306E\u9805\u76EE\u306E\u5024\u3092\u898B\u305B\u308B\u30FB\u5199\u3059\u3002"},export:{name:"\u66F8\u304D\u51FA\u3057",description:"\u533A\u753B\u306E\u9805\u76EE\u3092\u30D5\u30A1\u30A4\u30EB\u306B\u66F8\u304D\u51FA\u3059\u3002"},seal:{name:"\u4FDD\u7BA1\u5EAB\u306E\u5C01",description:"\u4FDD\u7BA1\u5EAB\u3092\u5C01\u3058\u3001\u5C01\u3092\u89E3\u304F\u3053\u3068\u306B\u52A0\u308F\u308B\u3002"},audit:{name:"\u4FDD\u7BA1\u5EAB\u306E\u8A18\u9332",description:"\u4FDD\u7BA1\u5EAB\u306E\u64CD\u4F5C\u306E\u8A18\u9332\u3092\u8AAD\u3080\u3002"},compartments:{name:"\u4FDD\u7BA1\u5EAB\u306E\u533A\u753B",description:"\u533A\u753B\u3092\u8DB3\u3057\u3001\u533A\u753B\u306E\u540D\u3092\u66FF\u3048\u308B\u3002"}}),Le=Object.freeze({authMessages:_authcore.defaultAuthMessages,refusals:Object.freeze({userNotFound:_chunkEI7MMDWYjs.a.call(void 0, e=>`\u5229\u7528\u8005\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${e}`,"userNotFound"),groupNotFound:_chunkEI7MMDWYjs.a.call(void 0, e=>`\u30B0\u30EB\u30FC\u30D7\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${e}`,"groupNotFound"),upstreamOwned:_chunkEI7MMDWYjs.a.call(void 0, e=>`\u3053\u306E\u30B0\u30EB\u30FC\u30D7\u306E\u6240\u5C5E\u3068\u540D\u79F0\u306F\u4E0A\u6D41\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA (${e}) \u304C\u6240\u6709\u3057\u3066\u3044\u307E\u3059\u3002\u5909\u66F4\u306F\u4E0A\u6D41\u5074\u3067\u884C\u3063\u3066\u304F\u3060\u3055\u3044\u3002`,"upstreamOwned"),patternEntriesUnused:"\u4FDD\u7BA1\u5EAB\u306F\u3001\u30B5\u30A4\u30F3\u30A4\u30F3\u3092\u8A31\u3059\u30B0\u30EB\u30FC\u30D7\u3068 Google Workspace \u306E\u30C9\u30E1\u30A4\u30F3\u3060\u3051\u3067\u4EBA\u3092\u901A\u3059\u306E\u3067\u3001\u30A2\u30C9\u30EC\u30B9\u3068\u30C9\u30E1\u30A4\u30F3\u306E\u8A31\u3057\u306F\u4F7F\u3044\u307E\u305B\u3093\u3002\u305D\u306E\u4EBA\u3092\u30B5\u30A4\u30F3\u30A4\u30F3\u3092\u8A31\u3059\u30B0\u30EB\u30FC\u30D7\u306B\u5165\u308C\u3066\u304F\u3060\u3055\u3044\u3002"}),resourceNameOf:_chunkEI7MMDWYjs.a.call(void 0, (e,t)=>{let n=St[e];return t===null?n:{name:`\u4FDD\u7BA1\u5EAB ${t.name} (${t.code}) \u306E${n.name}`,description:n.description}},"resourceNameOf")});var ne=_chunkEI7MMDWYjs.a.call(void 0, e=>e,"guardTransactionOf"),L="user-admin",P=_chunkEI7MMDWYjs.a.call(void 0, (...e)=>Math.min(...e.map(t=>{if(typeof t.length!="number")throw new Error(`[@aiquants/vault-host] column ${t.name} declares no width`);return t.length})),"narrowestWidth"),xe=_chunkEI7MMDWYjs.a.call(void 0, e=>{let{users:t}=e,{TMGroup:n}=e.authz,{TMAllowlist:a,TDAllowlistGroup:i,TDGroupExternalLink:u}=e.directory;return{user:{displayName:P(t.displayName),email:P(t.email,t.username,t.displayId)},group:{groupKey:P(n.groupKey),name:P(n.name),description:P(n.description)},allowlist:{pattern:P(a.pattern),description:P(a.description)},allowlistGroup:{description:P(i.description)},link:{externalId:P(u.externalId),externalKey:P(u.externalKey)}}},"vaultHostFieldLimitsOf"),Rt=_chunkEI7MMDWYjs.a.call(void 0, ({linkId:e,groupId:t,tenantId:n,...a})=>a,"listedLinkOf"),Tt=_chunkEI7MMDWYjs.a.call(void 0, e=>new Error(`[@aiquants/vault-host] ${e} answered no inserted row`),"noInsertedRow"),W=_chunkEI7MMDWYjs.a.call(void 0, (e,t)=>{let[n]=e;if(n===void 0)throw Tt(t);let{id:a}=n;if(typeof a!="number"||!Number.isSafeInteger(a)||a<1)throw new Error(`[@aiquants/vault-host] ${t} read back an ID that is not a positive safe integer`);return a},"insertedIdOf"),Pe=_chunkEI7MMDWYjs.a.call(void 0, e=>{let{db:t,tables:n,tenantId:a,links:i,lockoutGuard:u,transactions:c,refusals:p,now:y}=e,{users:A}=n,{TMGroup:d,TDGroupMember:f,TDGroupRole:R}=n.authz,{TDGroupExternalLink:b}=n.directory,k=_drizzle.outputInto.call(void 0, {id:A.id}),O=_drizzle.outputInto.call(void 0, {id:d.id}),E=_drizzle.outputInto.call(void 0, {id:f.id}),S=_chunkEI7MMDWYjs.a.call(void 0, async()=>(await t.select({id:A.id,email:A.email,displayName:A.displayName,isActive:A.isActive}).from(A).orderBy(_drizzleorm.asc.call(void 0, A.email))).map(s=>({id:s.id,email:_nullishCoalesce(s.email, () => ("")),displayName:_nullishCoalesce(s.displayName, () => ("")),isActive:s.isActive})),"readUsers"),V=_chunkEI7MMDWYjs.a.call(void 0, async o=>{let s=(await S()).find(g=>g.id===o);if(s===void 0)throw new (0, _admin.UserAdminOperatorError)(p.userNotFound(o));return s},"readUser"),x=_chunkEI7MMDWYjs.a.call(void 0, o=>_drizzleorm.and.call(void 0, _drizzleorm.eq.call(void 0, d.id,o),_drizzleorm.eq.call(void 0, d.tenantId,a)),"groupInTenant"),H=_chunkEI7MMDWYjs.a.call(void 0, async()=>{let[o,s]=await Promise.all([t.select({id:d.id,groupKey:d.groupKey,name:d.name,description:d.description,isActive:d.isActive}).from(d).where(_drizzleorm.eq.call(void 0, d.tenantId,a)).orderBy(_drizzleorm.asc.call(void 0, d.name)),i.listLinks(a)]),g=new Map(s.map(h=>[h.groupId,h]));return o.map(h=>{let T=g.get(h.id);return{id:h.id,groupKey:h.groupKey,name:h.name,description:h.description===null||h.description===""?void 0:h.description,isActive:h.isActive,readOnly:T!==void 0,...T===void 0?{}:{externalLink:Rt(T)}}})},"readGroups"),z=_chunkEI7MMDWYjs.a.call(void 0, async o=>{let s=(await H()).find(g=>g.id===o);if(s===void 0)throw new (0, _admin.UserAdminOperatorError)(p.groupNotFound(o));return s},"readGroup"),l=_chunkEI7MMDWYjs.a.call(void 0, async o=>{let[s]=await t.select({id:d.id}).from(d).where(x(o));if(s===void 0)throw new (0, _admin.UserAdminOperatorError)(p.groupNotFound(o))},"assertGroupInTenant"),m=_chunkEI7MMDWYjs.a.call(void 0, async o=>{let[s]=await t.select({externalKey:b.externalKey}).from(b).where(_drizzleorm.and.call(void 0, _drizzleorm.eq.call(void 0, b.groupId,o),_drizzleorm.eq.call(void 0, b.tenantId,a)));if(s!==void 0)throw new (0, _admin.UserAdminOperatorError)(p.upstreamOwned(s.externalKey))},"assertGroupIsLocallyManaged");return{listUsers:S,createUser:_chunkEI7MMDWYjs.a.call(void 0, async o=>{let s=y(),g=await k.run(t,t.insert(A).output({id:k.field}).values({..._(o.email,o.displayName,s,L),email:o.email,isActive:!0}));return V(W(g,"TDUsers"))},"createUser"),updateUser:_chunkEI7MMDWYjs.a.call(void 0, async(o,s)=>(await t.update(A).set({email:s.email,displayName:s.displayName,updatedAt:y(),updatedBy:L}).where(_drizzleorm.eq.call(void 0, A.id,o)),V(o)),"updateUser"),toggleUserActive:_chunkEI7MMDWYjs.a.call(void 0, async(o,s)=>{let g={isActive:s,updatedAt:y(),updatedBy:L};return s?await t.update(A).set(g).where(_drizzleorm.eq.call(void 0, A.id,o)):await u.guardedWrite(a,{deactivateUserId:o},"deactivate-user",h=>ne(h).update(A).set(g).where(_drizzleorm.eq.call(void 0, A.id,o))),V(o)},"toggleUserActive"),listGroups:H,createGroup:_chunkEI7MMDWYjs.a.call(void 0, async o=>{let s=await O.run(t,t.insert(d).output({id:O.field}).values({tenantId:a,groupKey:o.groupKey,name:o.name,description:_nullishCoalesce(o.description, () => (null)),isActive:!0,createdAt:y(),createdBy:L}));return z(W(s,"TMGroup"))},"createGroup"),createLinkedGroup:_chunkEI7MMDWYjs.a.call(void 0, async o=>{let s=await c.withAuthzTransaction(async(g,h)=>{let T=h,N=await O.run(T,T.insert(d).output({id:O.field}).values({tenantId:a,groupKey:o.groupKey,name:o.name,description:_nullishCoalesce(o.description, () => (null)),isActive:!0,createdAt:y(),createdBy:L})),G=W(N,"TMGroup");return await c.withAmbientAuthzTransaction(g,()=>i.linkGroup(a,G,{provider:o.provider,externalId:o.externalId,externalKey:o.externalKey,membershipMode:o.membershipMode},L)),G});return z(s)},"createLinkedGroup"),updateGroup:_chunkEI7MMDWYjs.a.call(void 0, async(o,s)=>(await m(o),await t.update(d).set({name:s.name,description:_nullishCoalesce(s.description, () => (null)),updatedAt:y(),updatedBy:L}).where(x(o)),z(o)),"updateGroup"),deleteGroup:_chunkEI7MMDWYjs.a.call(void 0, async o=>{await m(o),await u.guardedWrite(a,{removeGroupId:o},"delete-group",async s=>{let g=ne(s),[h]=await g.select({id:d.id}).from(d).where(x(o));if(h===void 0)throw new (0, _admin.UserAdminOperatorError)(p.groupNotFound(o));await g.delete(R).where(_drizzleorm.eq.call(void 0, R.groupId,o)),await g.delete(f).where(_drizzleorm.eq.call(void 0, f.groupId,o)),await g.delete(d).where(x(o))})},"deleteGroup"),listGroupMembers:_chunkEI7MMDWYjs.a.call(void 0, async()=>(await t.select({id:f.id,groupId:f.groupId,userId:f.userId}).from(f).innerJoin(d,_drizzleorm.and.call(void 0, _drizzleorm.eq.call(void 0, d.id,f.groupId),_drizzleorm.eq.call(void 0, d.tenantId,a))).orderBy(_drizzleorm.asc.call(void 0, f.groupId),_drizzleorm.asc.call(void 0, f.userId))).map(s=>({id:s.id,groupId:s.groupId,userId:s.userId})),"listGroupMembers"),addGroupMember:_chunkEI7MMDWYjs.a.call(void 0, async(o,s)=>{await l(o),await m(o);let[g]=await t.select({id:f.id}).from(f).where(_drizzleorm.and.call(void 0, _drizzleorm.eq.call(void 0, f.groupId,o),_drizzleorm.eq.call(void 0, f.userId,s)));if(g!==void 0)return{id:g.id,groupId:o,userId:s};let h=await E.run(t,t.insert(f).output({id:E.field}).values({groupId:o,userId:s,createdAt:y(),createdBy:L}));return{id:W(h,"TDGroupMember"),groupId:o,userId:s}},"addGroupMember"),removeGroupMember:_chunkEI7MMDWYjs.a.call(void 0, async(o,s)=>{await l(o),await m(o),await u.guardedWrite(a,{removeGroupMembership:{groupId:o,userId:s}},"remove-group-member",g=>ne(g).delete(f).where(_drizzleorm.and.call(void 0, _drizzleorm.eq.call(void 0, f.groupId,o),_drizzleorm.eq.call(void 0, f.userId,s))))},"removeGroupMember"),listAllowlist:_chunkEI7MMDWYjs.a.call(void 0, ()=>i.listAllowlistGroups(a),"listAllowlist"),addAllowlistEntry:_chunkEI7MMDWYjs.a.call(void 0, async()=>{throw new (0, _admin.UserAdminOperatorError)(p.patternEntriesUnused)},"addAllowlistEntry"),removeAllowlistEntry:_chunkEI7MMDWYjs.a.call(void 0, async()=>{throw new (0, _admin.UserAdminOperatorError)(p.patternEntriesUnused)},"removeAllowlistEntry"),addAllowlistGroup:_chunkEI7MMDWYjs.a.call(void 0, (o,s)=>i.addAllowlistGroup(a,o,s,L),"addAllowlistGroup"),removeAllowlistGroup:_chunkEI7MMDWYjs.a.call(void 0, o=>i.removeAllowlistGroup(a,o),"removeAllowlistGroup"),linkDirectoryGroup:_chunkEI7MMDWYjs.a.call(void 0, (o,s)=>i.linkGroup(a,o,{provider:s.provider,externalId:s.externalId,externalKey:s.externalKey,membershipMode:s.membershipMode},L),"linkDirectoryGroup"),unlinkDirectoryGroup:_chunkEI7MMDWYjs.a.call(void 0, o=>i.unlinkGroup(a,o),"unlinkDirectoryGroup"),setDirectorySyncEnabled:_chunkEI7MMDWYjs.a.call(void 0, (o,s)=>i.setSyncEnabled(a,o,s,L),"setDirectorySyncEnabled"),requestDirectorySync:_chunkEI7MMDWYjs.a.call(void 0, (o,s)=>i.requestSync(a,o,s),"requestDirectorySync"),getDirectoryStatus:_chunkEI7MMDWYjs.a.call(void 0, ()=>i.getStatus(a),"getDirectoryStatus")}},"createVaultHostUserAdminStore");var ze="aiquants-vault-host",Ft="vault-host",Wt="sign-out",Yt=2048,Zt=/^(\/[A-Za-z0-9_~-][A-Za-z0-9._~-]*)+$/u,Jt=_chunkEI7MMDWYjs.a.call(void 0, e=>{let t=["vault","signIn","signInCallback","signOut","authzAdmin","userAdmin"];for(let n of t){let a=typeof e=="object"&&e!==null?e[n]:void 0;if(typeof a!="string"||!Zt.test(a)||a.split("/").some(i=>i==="."||i===".."))throw new RangeError(`[@aiquants/vault-host] paths.${n} must be an absolute route path without a trailing slash`)}if(new Set(t.map(n=>e[n])).size!==t.length)throw new RangeError("[@aiquants/vault-host] the six paths must all differ");return Object.freeze({vault:e.vault,signIn:e.signIn,signInCallback:e.signInCallback,signOut:e.signOut,authzAdmin:e.authzAdmin,userAdmin:e.userAdmin})},"checkedPaths"),Qt=_chunkEI7MMDWYjs.a.call(void 0, (e,t)=>{if(!_chunkJ2KNKMKOjs.a.includes(e.locale))throw new RangeError(`[@aiquants/vault-host] locale must be one of ${_chunkJ2KNKMKOjs.a.join(", ")}`);let{placement:n,logger:a,connect:i,authzAdminResource:u}=e;if(typeof n!="object"||n===null||typeof n.secretIdRule!="function"||typeof n.listWhileSealed!="boolean")throw new TypeError("[@aiquants/vault-host] placement needs secretIdRule (a function), compartmentOf and listWhileSealed (a boolean)");if(typeof a!="object"||a===null||[a.info,a.warn,a.error].some(y=>typeof y!="function"))throw new TypeError("[@aiquants/vault-host] logger needs info, warn and error functions");if(typeof i!="function")throw new TypeError("[@aiquants/vault-host] connect must be a function (nodeMssqlVaultHostConnection)");let c=typeof u=="object"&&u!==null?u.key:void 0,p=typeof u=="object"&&u!==null?u.name:void 0;if(typeof c!="string"||c.trim()===""||typeof p!="string"||p.trim()==="")throw new RangeError("[@aiquants/vault-host] authzAdminResource needs a non-blank key and name");if(c===t||c.startsWith(`${t}.`))throw new RangeError(`[@aiquants/vault-host] authzAdminResource.key must not be under the vault's resource prefix (${t})`)},"checkOptions"),Xt=_chunkEI7MMDWYjs.a.call(void 0, e=>{let t=new URL(e.url);return`${t.pathname}${t.search}`},"returnToOf"),er= exports.createVaultHost =_chunkEI7MMDWYjs.a.call(void 0, e=>{let t=_chunkQJKY44QOjs.d.call(void 0, e.env);Qt(e,t.authz.resourcePrefix);let n=Jt(e.paths),a=Se(e.schemas),{locale:i,logger:u,placement:c,authzAdminResource:p}=e,y=i==="ja",A=y?Le:Oe,{tenantId:d,appKey:f,resourcePrefix:R}=t.authz,{numbers:b}=t,k=Re(a),O=_chunkQJKY44QOjs.a.call(void 0, t.database,t.runtime,ze),E=e.connect(O),{db:S}=E,V=Ve({db:S,tables:k,tenantId:d,appKey:f,adminResourceKey:p.key,directoryEnabled:t.directoryEnabled,lockoutMessage:y?_authzreactrouter.jaLockoutMessage:void 0,lockPrincipal:t.authz.lockPrincipal,logger:u}),x=Te({db:S,tables:k,binding:V.binding,tenantId:d,ledger:V.directoryLinkStore,signInDomain:t.signInDomain,googleClientId:t.google.clientId,signupLockPrincipal:t.signupLockPrincipal,logger:u}),H=_server.createAuthServer.call(void 0, {google:{clientId:t.google.clientId,clientSecret:t.google.clientSecret,redirectURI:t.google.redirectUrl},session:{secrets:[t.sessionSecret],secure:!0},messages:A.authMessages,logger:j(u),isEmailAllowed:x.isEmailAllowed,isUserActive:x.isUserActive,sessionGeneration:{store:_authdirectorydrizzle.createSessionGenerationStore.call(void 0, S,k.sessionGeneration,{actor:Wt})},readerCheck:!0,backendAuth:x.backendAuth,loginPath:n.signIn,postLoginRedirect:n.vault,postLogoutRedirect:n.signIn,returnTo:{allowedPaths:[n.vault,n.authzAdmin,n.userAdmin],pages:{excludedPathPrefixes:[`${n.vault}/-/api/`,n.signIn,n.signInCallback,n.signOut],maxLength:Yt}}}),z=_chunkEI7MMDWYjs.a.call(void 0, v=>H.getSessionUser(v),"sessionUserOf"),l=be({db:S,tables:k,identity:V,permissions:Ae(S,k,f),appKey:f,resourcePrefix:R,sessionUserOf:z,logger:u}),m=we({authz:l,clientAddressHeader:t.headers.clientAddress,requestIdHeader:t.headers.requestId}),o=_vaultcore.createVault.call(void 0, {storage:_vaultdrizzle.createDrizzleVaultStorage.call(void 0, {db:S,schema:_vaultdrizzle.defineVaultSchema.call(void 0, a.vault),lockTimeoutMs:b.lockTimeoutMs,ceremonyLockTimeoutMs:b.ceremonyLockTimeoutMs,lockPrincipal:t.lockPrincipal,transactionRetry:_chunkQJKY44QOjs.j.call(void 0, b.transactionRetryAttempts,u),openSessionConnection:_chunkQJKY44QOjs.h}),authorizer:l.vaultAuthorizer,logger:u,clock:_chunkQJKY44QOjs.g,secretIdRule:c.secretIdRule,compartmentOf:c.compartmentOf,listWhileSealed:c.listWhileSealed,unseal:{progressTtlSeconds:b.unsealProgressTtlSeconds,failureLimit:b.unsealFailureLimit,lockoutSeconds:b.unsealLockoutSeconds},limits:{maxBodyBytes:b.maxBodyBytes,maxAttachmentCount:b.maxAttachmentCount,maxRequestBytes:b.maxRequestBytes},audit:{pageSize:b.auditPageSize}}),s=_chunkQJKY44QOjs.f.call(void 0, {store:V.authzAdminStore,tenantId:d,appKey:f,resourcePrefix:R,nameOf:A.resourceNameOf}),g=_server3.createVaultApp.call(void 0, {vault:o,basePath:n.vault,crossOrigin:_server3.createVaultNavigationPolicy.call(void 0, {mountPath:n.vault}),resolveContext:m,reveal:{hideSeconds:b.revealHideSeconds},logger:u,compartments:_chunkQJKY44QOjs.i.call(void 0, s),labels:{...y?_server3.jaVaultLabels:_server3.defaultVaultLabels,timeZone:b.exportTimeZone}}),h=_chunkEI7MMDWYjs.a.call(void 0, v=>H.requireUser(v,Xt(v)),"requireUser"),T=_authzreactrouter.createAuthzAdminApp.call(void 0, {store:V.authzAdminStore,basePath:n.authzAdmin,resourceKey:p.key,requireUser:h,requirePermission:l.requirePermission,labels:y?{..._authzreactrouter.jaAuthzAdminLabels,adminResourceName:p.name}:{adminResourceName:p.name}}),N=_admin.createUserAdminApp.call(void 0, _chunkQJKY44QOjs.k.call(void 0, {store:Pe({db:S,tables:k,tenantId:d,links:V.directoryLinkStore,lockoutGuard:V.adminLockoutGuard,transactions:V,refusals:A.refusals,now:_chunkQJKY44QOjs.g}),fieldLimits:xe(k),labels:y?_admin.jaUserAdminLabels:void 0,resource:p,requireUser:h,requirePermission:l.requirePermission,getMyPermissions:l.getMyPermissions,sessionUserOf:z,catalog:V.directoryCatalog,tenantId:d,logger:u})),G=_chunkQJKY44QOjs.l.call(void 0, {sessionUserOf:z,readerStampOf:H.readerStampOf,locale:i,timeZone:b.exportTimeZone,paths:n}),Y=_chunkQJKY44QOjs.n.call(void 0, {open:_chunkEI7MMDWYjs.a.call(void 0, ()=>E.open(),"open"),checkLocks:_chunkQJKY44QOjs.p.call(void 0, {check:_chunkEI7MMDWYjs.a.call(void 0, (v,Ne)=>_drizzle.assertLockPrincipalMember.call(void 0, S,v,Ne),"check"),roles:[{lockPrincipal:t.authz.lockPrincipal,settingName:_chunkQJKY44QOjs.c.authz},{lockPrincipal:t.lockPrincipal,settingName:_chunkQJKY44QOjs.c.vault},{lockPrincipal:t.signupLockPrincipal,settingName:_chunkQJKY44QOjs.c.signup}]}),listResources:_chunkEI7MMDWYjs.a.call(void 0, v=>V.authzAdminStore.listResources(v),"listResources"),listCompartments:_chunkEI7MMDWYjs.a.call(void 0, ()=>o.listCompartments(),"listCompartments"),register:s,tenantId:d,appKey:f,adminResourceKey:p.key,actor:Ft}),Z=_chunkQJKY44QOjs.q.call(void 0, {disposeVault:_chunkEI7MMDWYjs.a.call(void 0, ()=>o.dispose(),"disposeVault"),close:_chunkEI7MMDWYjs.a.call(void 0, ()=>E.close(),"close")}),Ee=_chunkQJKY44QOjs.m.call(void 0, {refusalOf:_server.signOutRefusal,refusalResponse:_chunkEI7MMDWYjs.a.call(void 0, ()=>_server.signOutRefusalResponse.call(void 0, H.messages),"refusalResponse"),signOut:_chunkEI7MMDWYjs.a.call(void 0, v=>H.logoutAndRedirect(v),"signOut"),logger:u}),Ge=Object.freeze({root:Object.freeze({loader:G}),vault:Object.freeze({loader:_chunkQJKY44QOjs.o.call(void 0, h,g.ui.loader),action:_chunkEI7MMDWYjs.a.call(void 0, v=>g.ui.action(v),"action"),headers:_server3.vaultRouteHeaders}),vaultApi:Object.freeze({action:_chunkEI7MMDWYjs.a.call(void 0, v=>g.api.action(v),"action")}),signIn:Object.freeze({loader:_chunkEI7MMDWYjs.a.call(void 0, ({request:v})=>H.loginLoader({request:v}),"loader"),action:_chunkEI7MMDWYjs.a.call(void 0, ({request:v})=>H.loginAction({request:v}),"action")}),signInCallback:Object.freeze({loader:_chunkEI7MMDWYjs.a.call(void 0, ({request:v})=>H.googleCallbackLoader({request:v}),"loader")}),signOut:Object.freeze({loader:Ee}),authzAdmin:Object.freeze({loader:T.loader,action:T.action}),userAdmin:Object.freeze({loader:N.loader,action:N.action})});return Object.freeze({vault:o,vaultApp:g,auth:H,authzAdmin:T,userAdmin:N,routes:Ge,start:Y,dispose:Z,locale:i,paths:n})},"createVaultHost");exports.DIRECTORY_STALENESS_PARAMETER = C; exports.VAULT_HOST_APP_NAME = ze; exports.VAULT_HOST_LOCALES = _chunkJ2KNKMKOjs.a; exports.VAULT_HOST_ROOT_ROUTE_ID = _chunkJ2KNKMKOjs.b; exports.VaultHostConfigError = _chunkQJKY44QOjs.b; exports.createVaultHost = er; exports.nodeMssqlVaultHostConnection = _chunkQJKY44QOjs.r;
@@ -0,0 +1 @@
1
+ import{a as oe,b as qe,c as D,d as ae,f as se,g as J,h as ie,i as ue,j as le,k as de,l as ce,m as pe,n as me,o as ye,p as ge,q as fe,r as Ce}from"./chunk-7QP3MVGS.mjs";import{a as U,b as Me}from"./chunk-T6OT6WLH.mjs";import{a as r}from"./chunk-YSXGDEY5.mjs";import{createSessionGenerationStore as Ot}from"@aiquants/auth-directory-drizzle";import{createUserAdminApp as Lt,jaUserAdminLabels as xt}from"@aiquants/auth-react-router/admin";import{createAuthServer as Pt,signOutRefusal as zt,signOutRefusalResponse as Et}from"@aiquants/auth-react-router/server";import{createAuthzAdminApp as Gt,jaAuthzAdminLabels as Nt,jaLockoutMessage as qt}from"@aiquants/authz-react-router";import{assertLockPrincipalMember as Ct}from"@aiquants/mssql/drizzle";import{createVault as Mt}from"@aiquants/vault-core";import{createDrizzleVaultStorage as Dt,defineVaultSchema as Ut}from"@aiquants/vault-drizzle";import{createVaultApp as _t,createVaultNavigationPolicy as Kt,defaultVaultLabels as jt,jaVaultLabels as Bt,vaultRouteHeaders as $t}from"@aiquants/vault-react-router/server";import{evaluateTenantMembership as _e}from"@aiquants/auth-directory-core";import{createRequirePermissions as Ke}from"@aiquants/authz-core";import{getEffectivePermissionsMany as je,listResourceKeys as Be}from"@aiquants/authz-drizzle";import{createAuthz as $e}from"@aiquants/authz-react-router";import{createAuthzVaultAuthorizer as Fe}from"@aiquants/vault-core/authz";import{eq as We}from"drizzle-orm";import{randomUUID as De}from"crypto";import{and as Ue,eq as Q}from"drizzle-orm";var _=r((e,t,n,a)=>({uuid:De(),username:e,displayId:e,displayName:t,isPasswordDisabled:!0,createdAt:n,createdBy:a,updatedAt:n,updatedBy:a}),"newUserValues"),K=r((e,t)=>async(n,a)=>{let[i]=await e.select({userId:t.users.id,displayName:t.users.displayName,userActive:t.users.isActive,subjectActive:t.openid.isActive}).from(t.openid).innerJoin(t.users,Q(t.users.id,t.openid.userId)).where(Ue(Q(t.openid.provider,n),Q(t.openid.openid,a)));return i===void 0?null:{userId:i.userId,displayName:i.displayName,active:i.userActive&&i.subjectActive}},"personLookupOf");var Ae=r((e,t,n)=>({many:r(a=>je(e,t.authz,a),"many"),resourceKeys:r(a=>Be(e,t.authz,n,a),"resourceKeys")}),"drizzlePermissionSourceOf"),he=r(e=>{let t=new WeakMap;return n=>{let a=t.get(n);if(a!==void 0)return a;let i=e(n);return t.set(n,i),i}},"perRequest"),be=r(e=>{let{db:t,tables:n,identity:a,appKey:i,logger:u}=e,{tenantId:c,directoryLinkStore:p}=a,y=Object.freeze([c]),A=K(t,n),d=n.authz.TDGroupMember,f=he(async l=>{let m=await e.sessionUserOf(l);if(m===void 0)return null;let o=await A(m.provider,m.id);return o===null||!o.active?null:{profile:m,userId:o.userId,displayName:o.displayName}}),R=r(async l=>{let m=await f(l);return m===null?null:m.userId},"resolveUserId"),b=r(async l=>(await t.select({groupId:d.groupId}).from(d).where(We(d.userId,l))).map(o=>o.groupId),"groupIdsOfUser"),k=he(async l=>{let m=await R(l);return m===null?[]:b(m)}),O=new WeakMap,E=r(async(l,m)=>{let o=await f(l),s=await p.loadTenantMembershipPolicy(c),g=r((Y,Z)=>_e({requestedTenantId:m,servedTenantIds:y,userId:o===null?null:o.userId,policy:s,localGroupIds:Y,ledgerGroupIds:Z}),"evaluate");if(o===null||s.kind==="no-proof-required")return g([],[]).isMember;let[h]=o.profile.emails,[T,N]=await Promise.all([k(l),p.listLedgerGroupIds(c,{provider:o.profile.provider,externalUserId:o.profile.id,email:h===void 0?null:h.value})]),G=g(T,N);return G.isMember||u.info("vault-host-tenant-membership-denied",{operation:"authorize",compartment:null,secretId:null,version:null,reason:G.reason,cause:null}),G.isMember},"isTenantMember"),S=r((l,m)=>{let o=O.get(l);o===void 0&&(o=new Map,O.set(l,o));let s=o.get(m);if(s!==void 0)return s;let g=E(l,m);return o.set(m,g),g},"assertTenantMembership"),V=$e({appKey:i,resolveUserId:R,resolveTenantId:r(()=>c,"resolveTenantId"),assertTenantMembership:S,resolveGroupIds:r(l=>k(l),"resolveGroupIds"),getEffectivePermissions:r(l=>e.permissions.many(l),"getEffectivePermissions"),listResourceKeys:r((l,m)=>e.permissions.resourceKeys(m),"listResourceKeys")}),x=Ke({resolveTenantId:r(()=>c,"resolveTenantId"),resolveUserId:R,assertTenantMembership:r(({ctx:l,tenantId:m})=>S(l,m),"assertTenantMembership"),getEffectivePermissionsMany:r(async l=>e.permissions.many({...l,groupIds:l.userId===null?[]:await b(Number(l.userId))}),"getEffectivePermissionsMany"),scopedGrants:"deny"}),H=new WeakMap,z=Fe({requirePermissions:r((l,m)=>x(l,m),"requirePermissions"),contextOf:r(l=>{let m=H.get(l);if(m===void 0)throw new Error("[@aiquants/vault-host] the vault asked about a request context this host's resolveContext did not make");return m},"contextOf"),appKey:i,resourcePrefix:e.resourcePrefix});return{signedInOf:f,resolveUserId:R,requirePermission:V.requirePermission,getMyPermissions:V.getMyPermissions,vaultAuthorizer:z,rememberContext:r((l,m)=>(H.set(l,m),l),"rememberContext")}},"createVaultHostAuthz");import{accessFailureResponse as Ye}from"@aiquants/auth-core";import{vaultUserAgentOf as Ze}from"@aiquants/vault-react-router/server";var we=r(e=>async t=>{let n=await e.authz.signedInOf(t);if(n===null)throw Ye("unauthenticated");let a=t.headers.get(e.clientAddressHeader);if(a===null||a.trim()==="")throw new Error(`[@aiquants/vault-host] the trusted proxy wrote no client address into ${e.clientAddressHeader}`);if(n.displayName===null||n.displayName.trim()==="")throw new Error(`[@aiquants/vault-host] user ${n.userId} has no display name; set it on the user admin screen`);let i={actor:{kind:"user",id:String(n.userId),displayName:n.displayName},origin:{kind:"request",address:a,userAgent:Ze(t)},requestId:t.headers.get(e.requestIdHeader)};return e.authz.rememberContext(i,t)},"createVaultHostContextResolver");import{AsyncLocalStorage as Je}from"async_hooks";import{GOOGLE_PROVIDER as Qe}from"@aiquants/auth-core";import{assertGroupMayBeLinked as Xe,createDirectoryCatalogReader as et,createDirectoryLinkStore as tt,createOpenidMemberResolver as rt,defaultDirectoryLinkRefusals as nt,defaultExternalGroupGuardMessage as ot,withExternalGroupGuards as at}from"@aiquants/auth-directory-drizzle";import{createAdminLockoutGuard as st,createAuthzAdminStore as it}from"@aiquants/authz-drizzle";import{and as ut,eq as ve}from"drizzle-orm";var C={category:"directory",key:"AUTH_DIRECTORY_STALENESS_SECONDS"},lt="SYSTEM",dt=r(async(e,t,n)=>{let a=t.systemParameter,i=await e.select({tenantId:a.tenantId,value:a.value}).from(a).where(ut(ve(a.category,C.category),ve(a.key,C.key))),u=i.find(y=>y.tenantId===n),c=u===void 0?i.find(y=>y.tenantId===lt):u,p=c!==void 0&&/^[1-9]\d*$/u.test(c.value)?Number(c.value):Number.NaN;if(!Number.isSafeInteger(p))throw new Error(`[@aiquants/vault-host] the system parameter ${C.category}/${C.key} must be a positive integer for the tenant or SYSTEM`);return p},"readDirectoryStalenessSeconds"),ct=r(e=>({users:{table:e.users,id:e.users.id,email:e.users.email,isActive:e.users.isActive},subjects:{table:e.openid,provider:e.openid.provider,subject:e.openid.openid,userId:e.openid.userId,isActive:e.openid.isActive}}),"openidBindingOf"),pt=r(e=>({onRetry:r(({attempt:t,attempts:n})=>{e.warn("vault-host-authz-retried",{operation:"authz-transaction",compartment:null,secretId:null,version:null,reason:`${t}/${n-1}`,cause:null})},"onRetry")}),"authzRetryOf"),mt=r((e,t)=>{let n=new Je,a=r(c=>(n.getStore()??e).withTransaction((p,y)=>c(p,y)),"withAuthzTransaction");return{withAuthzTransaction:a,withAmbientAuthzTransaction:r((c,p)=>n.run(c,p),"withAmbientAuthzTransaction"),assertLinkableAndWrite:r((c,p,y)=>a(async(A,d)=>{await Xe(A,c,p,t),await y(d)}),"assertLinkableAndWrite")}},"authzTransactionsOf"),yt=r((e,t)=>n=>dt(e,t,n),"stalenessReaderOf"),Ve=r(e=>{let{db:t,tables:n,tenantId:a,appKey:i,adminResourceKey:u}=e,c=e.lockoutMessage===void 0?{}:{lockoutMessage:e.lockoutMessage},p=ct(n),y=rt(t,p,{}),A=it(t,n.authz,{userTable:n.users,userScope:{kind:"global"},userActiveColumn:n.users.isActive,adminAppKey:i,adminResourceKey:u,lockPrincipal:e.lockPrincipal,transactionRetry:pt(e.logger),...c}),d={adminAppKey:i,adminResourceKey:u,message:ot},f=mt(A,d),R=tt(t,n.directory,n.authz,{linkable:{assertLinkableAndWrite:f.assertLinkableAndWrite},resolveStalenessThresholdSec:yt(t,n),isEnabled:e.directoryEnabled,provider:Qe,refusals:nt,memberResolver:y}),b=at(A,{...d,linkLookup:R}),k=st(t,n.authz,{userTable:n.users,userScope:{kind:"global"},userActiveColumn:n.users.isActive,adminAppKey:i,adminResourceKey:u,lockPrincipal:e.lockPrincipal,...c}),O=e.directoryEnabled?et(t,n.directory,{}):null;return{tenantId:a,binding:p,memberResolver:y,authzAdminStore:b,directoryLinkStore:R,adminLockoutGuard:k,withAuthzTransaction:f.withAuthzTransaction,withAmbientAuthzTransaction:f.withAmbientAuthzTransaction,directoryCatalog:O}},"createVaultHostIdentity");var X=r(e=>({operation:"sign-in",compartment:null,secretId:null,version:null,reason:null,cause:e}),"detailsOf"),j=r(e=>({info:r((...t)=>e.info("vault-host-sign-in",X(t)),"info"),warn:r((...t)=>e.warn("vault-host-sign-in",X(t)),"warn"),error:r((...t)=>e.error("vault-host-sign-in",X(t)),"error")}),"signInLoggerOf");import{defineAuthDirectorySchema as gt,defineSessionGenerationSchema as ft}from"@aiquants/auth-directory-drizzle";import{defineAuthzSchema as ht}from"@aiquants/authz-drizzle";import{bigint as B,bit as ee,datetime as Ie,datetime2 as ke,mssqlSchema as He,nvarchar as w,primaryKey as te}from"drizzle-orm/mssql-core";var At=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u,Se=r(e=>{for(let t of["vault","authz","users","parameters"]){let n=typeof e=="object"&&e!==null?e[t]:void 0;if(typeof n!="string"||!At.test(n))throw new RangeError(`[@aiquants/vault-host] schemas.${t} must be a regular SQL Server identifier`)}if([e.authz,e.users,e.parameters].some(t=>t.toLowerCase()===e.vault.toLowerCase()))throw new RangeError("[@aiquants/vault-host] schemas.vault must differ from the identity schemas");return Object.freeze({vault:e.vault,authz:e.authz,users:e.users,parameters:e.parameters})},"checkedSchemas"),Re=r(e=>{let t=He(e.users),n=t.table("TDUsers",{id:B("id",{mode:"number"}).identity().notNull(),uuid:w("uuid",{length:100}),username:w("username",{length:100}).notNull(),email:w("email",{length:100}),hashedPassword:w("hashed_password",{length:200}),isPasswordDisabled:ee("is_password_disabled").notNull(),isActive:ee("is_active").notNull(),displayId:w("display_id",{length:100}),displayName:w("display_name",{length:100}),createdAt:ke("created_at"),createdBy:w("created_by",{length:50}),updatedAt:ke("updated_at"),updatedBy:w("updated_by",{length:50})},y=>[te({columns:[y.id]})]),a=t.table("TDOpenid",{id:B("id",{mode:"number"}).identity().notNull(),provider:w("provider",{length:50}).notNull(),openid:w("openid",{length:1e3}).notNull(),email:w("email",{length:200}),name:w("name",{length:200}),givenName:w("given_name",{length:200}),familyName:w("family_name",{length:200}),picture:w("picture",{length:"max"}),locale:w("locale",{length:200}),userId:B("user_id",{mode:"number"}).notNull(),isActive:ee("is_active").notNull(),createdAt:Ie("created_at").notNull(),createdBy:w("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at"),updatedBy:w("updated_by",{length:50})},y=>[te({columns:[y.id]})]),i=ht(e.authz,{userTable:n}),u=gt(e.authz,{groupTable:i.TMGroup,userTable:n}),c=ft(e.authz),p=He(e.parameters).table("tm_system_parameter",{id:B("id",{mode:"number"}).identity().notNull(),tenantId:w("tenant_id",{length:64}).notNull(),category:w("param_category",{length:32}).notNull(),key:w("param_key",{length:64}).notNull(),value:w("param_value",{length:"max"}).notNull()},y=>[te({columns:[y.id]})]);return{users:n,openid:a,authz:i,directory:u,sessionGeneration:c,systemParameter:p}},"defineVaultHostTables");import{hostedDomainAllowlist as bt}from"@aiquants/auth-core";import{createOpenidSignup as wt}from"@aiquants/auth-directory-drizzle";import{createGoogleTokenVerifier as vt}from"@aiquants/auth-react-router/server";var $="signup",Vt=r((e,t)=>{let n=bt([e]);return async(a,i)=>!n(i)||typeof a!="string"||a.trim()===""?!1:t.isEmailAllowedByGroup(a)},"vaultSignInRuleOf"),It=r(e=>({identify:e.identify,lockPrincipal:e.lockPrincipal,isEmailAllowed:r((t,n)=>e.mayEnter(t,n.hostedDomain),"isEmailAllowed"),newUser:r(({identity:t,profile:n,now:a})=>_(t.email,n.displayName,a,$),"newUser"),newSubject:r(({identity:t,profile:n,now:a})=>({email:t.email,name:n.displayName,givenName:n.name.givenName,familyName:n.name.familyName,createdAt:a,createdBy:$,updatedAt:a,updatedBy:$}),"newSubject"),promotion:{tables:e.tables.directory,authzTables:e.tables.authz,tenantId:e.tenantId,actor:$},transactionRetry:{onRetry:r(({attempt:t,attempts:n})=>{e.logger.warn("vault-host-sign-up-retried",{operation:"sign-up",compartment:null,secretId:null,version:null,reason:`${t}/${n-1}`,cause:null})},"onRetry")}}),"vaultHostSignupOptions"),Te=r(e=>{let t=Vt(e.signInDomain,e.ledger),n=K(e.db,e.tables),a=vt({clientIds:[e.googleClientId],logger:j(e.logger)}),i=wt(e.db,e.binding,It({tables:e.tables,tenantId:e.tenantId,identify:a.identify,mayEnter:t,lockPrincipal:e.signupLockPrincipal,logger:e.logger}));return{mayEnter:t,isEmailAllowed:r((u,c)=>t(u,c.hostedDomain),"isEmailAllowed"),isUserActive:r(async u=>{let[c]=u.emails;if(!await t(c===void 0?null:c.value,u.hostedDomain))return!1;let p=await n(u.provider,u.id);return p===null||p.active},"isUserActive"),backendAuth:{verify:a.verify,signup:i}}},"createVaultHostSignIn");var kt=Object.freeze({items:{name:"items",description:"See, create, change and remove the items of the compartment."},values:{name:"values",description:"Reveal and copy the values of the compartment's items."},export:{name:"export",description:"Export the compartment's items as a file."},seal:{name:"Vault seal",description:"Seal the vault and take part in unsealing it."},audit:{name:"Vault audit log",description:"Read the vault's audit log."},compartments:{name:"Vault compartments",description:"Add compartments and rename them."}}),Oe=Object.freeze({authMessages:Object.freeze({emailNotVerified:"Your email address is not verified.",googleFailed:"Signing in with Google failed.",consentDenied:"You did not allow the sign-in on Google's screen, so you are not signed in.",backendFailed:"The sign-in could not be completed on the server.",notAllowed:"You may not use this application.",backendUnreachable:"The sign-in service could not be reached. Try again later.",unexpected:"An unexpected error occurred while signing in.",returnToRefused:"The sign-in did not start, because the address to return to could not be accepted.",signOutRefused:"The sign-out request was not accepted. Sign out again with the sign-out button on the screen."}),refusals:Object.freeze({userNotFound:r(e=>`User not found: ${e}`,"userNotFound"),groupNotFound:r(e=>`Group not found: ${e}`,"groupNotFound"),upstreamOwned:r(e=>`The members and the name of this group are owned by the upstream directory (${e}). Change them there.`,"upstreamOwned"),patternEntriesUnused:"The vault admits people by its sign-in groups and its Google Workspace domain only, so address and domain entries are not used. Add the person to a sign-in group instead."}),resourceNameOf:r((e,t)=>{let n=kt[e];return t===null?n:{name:`Vault ${t.name} (${t.code}): ${n.name}`,description:n.description}},"resourceNameOf")});import{defaultAuthMessages as Ht}from"@aiquants/auth-core";var St=Object.freeze({items:{name:"\u9805\u76EE",description:"\u533A\u753B\u306E\u9805\u76EE\u3092\u898B\u308B\u30FB\u4F5C\u308B\u30FB\u76F4\u3059\u30FB\u6D88\u3059\u3002"},values:{name:"\u5024",description:"\u533A\u753B\u306E\u9805\u76EE\u306E\u5024\u3092\u898B\u305B\u308B\u30FB\u5199\u3059\u3002"},export:{name:"\u66F8\u304D\u51FA\u3057",description:"\u533A\u753B\u306E\u9805\u76EE\u3092\u30D5\u30A1\u30A4\u30EB\u306B\u66F8\u304D\u51FA\u3059\u3002"},seal:{name:"\u4FDD\u7BA1\u5EAB\u306E\u5C01",description:"\u4FDD\u7BA1\u5EAB\u3092\u5C01\u3058\u3001\u5C01\u3092\u89E3\u304F\u3053\u3068\u306B\u52A0\u308F\u308B\u3002"},audit:{name:"\u4FDD\u7BA1\u5EAB\u306E\u8A18\u9332",description:"\u4FDD\u7BA1\u5EAB\u306E\u64CD\u4F5C\u306E\u8A18\u9332\u3092\u8AAD\u3080\u3002"},compartments:{name:"\u4FDD\u7BA1\u5EAB\u306E\u533A\u753B",description:"\u533A\u753B\u3092\u8DB3\u3057\u3001\u533A\u753B\u306E\u540D\u3092\u66FF\u3048\u308B\u3002"}}),Le=Object.freeze({authMessages:Ht,refusals:Object.freeze({userNotFound:r(e=>`\u5229\u7528\u8005\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${e}`,"userNotFound"),groupNotFound:r(e=>`\u30B0\u30EB\u30FC\u30D7\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${e}`,"groupNotFound"),upstreamOwned:r(e=>`\u3053\u306E\u30B0\u30EB\u30FC\u30D7\u306E\u6240\u5C5E\u3068\u540D\u79F0\u306F\u4E0A\u6D41\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA (${e}) \u304C\u6240\u6709\u3057\u3066\u3044\u307E\u3059\u3002\u5909\u66F4\u306F\u4E0A\u6D41\u5074\u3067\u884C\u3063\u3066\u304F\u3060\u3055\u3044\u3002`,"upstreamOwned"),patternEntriesUnused:"\u4FDD\u7BA1\u5EAB\u306F\u3001\u30B5\u30A4\u30F3\u30A4\u30F3\u3092\u8A31\u3059\u30B0\u30EB\u30FC\u30D7\u3068 Google Workspace \u306E\u30C9\u30E1\u30A4\u30F3\u3060\u3051\u3067\u4EBA\u3092\u901A\u3059\u306E\u3067\u3001\u30A2\u30C9\u30EC\u30B9\u3068\u30C9\u30E1\u30A4\u30F3\u306E\u8A31\u3057\u306F\u4F7F\u3044\u307E\u305B\u3093\u3002\u305D\u306E\u4EBA\u3092\u30B5\u30A4\u30F3\u30A4\u30F3\u3092\u8A31\u3059\u30B0\u30EB\u30FC\u30D7\u306B\u5165\u308C\u3066\u304F\u3060\u3055\u3044\u3002"}),resourceNameOf:r((e,t)=>{let n=St[e];return t===null?n:{name:`\u4FDD\u7BA1\u5EAB ${t.name} (${t.code}) \u306E${n.name}`,description:n.description}},"resourceNameOf")});import{UserAdminOperatorError as q}from"@aiquants/auth-react-router/admin";import{outputInto as re}from"@aiquants/mssql/drizzle";import{and as M,asc as F,eq as I}from"drizzle-orm";var ne=r(e=>e,"guardTransactionOf"),L="user-admin",P=r((...e)=>Math.min(...e.map(t=>{if(typeof t.length!="number")throw new Error(`[@aiquants/vault-host] column ${t.name} declares no width`);return t.length})),"narrowestWidth"),xe=r(e=>{let{users:t}=e,{TMGroup:n}=e.authz,{TMAllowlist:a,TDAllowlistGroup:i,TDGroupExternalLink:u}=e.directory;return{user:{displayName:P(t.displayName),email:P(t.email,t.username,t.displayId)},group:{groupKey:P(n.groupKey),name:P(n.name),description:P(n.description)},allowlist:{pattern:P(a.pattern),description:P(a.description)},allowlistGroup:{description:P(i.description)},link:{externalId:P(u.externalId),externalKey:P(u.externalKey)}}},"vaultHostFieldLimitsOf"),Rt=r(({linkId:e,groupId:t,tenantId:n,...a})=>a,"listedLinkOf"),Tt=r(e=>new Error(`[@aiquants/vault-host] ${e} answered no inserted row`),"noInsertedRow"),W=r((e,t)=>{let[n]=e;if(n===void 0)throw Tt(t);let{id:a}=n;if(typeof a!="number"||!Number.isSafeInteger(a)||a<1)throw new Error(`[@aiquants/vault-host] ${t} read back an ID that is not a positive safe integer`);return a},"insertedIdOf"),Pe=r(e=>{let{db:t,tables:n,tenantId:a,links:i,lockoutGuard:u,transactions:c,refusals:p,now:y}=e,{users:A}=n,{TMGroup:d,TDGroupMember:f,TDGroupRole:R}=n.authz,{TDGroupExternalLink:b}=n.directory,k=re({id:A.id}),O=re({id:d.id}),E=re({id:f.id}),S=r(async()=>(await t.select({id:A.id,email:A.email,displayName:A.displayName,isActive:A.isActive}).from(A).orderBy(F(A.email))).map(s=>({id:s.id,email:s.email??"",displayName:s.displayName??"",isActive:s.isActive})),"readUsers"),V=r(async o=>{let s=(await S()).find(g=>g.id===o);if(s===void 0)throw new q(p.userNotFound(o));return s},"readUser"),x=r(o=>M(I(d.id,o),I(d.tenantId,a)),"groupInTenant"),H=r(async()=>{let[o,s]=await Promise.all([t.select({id:d.id,groupKey:d.groupKey,name:d.name,description:d.description,isActive:d.isActive}).from(d).where(I(d.tenantId,a)).orderBy(F(d.name)),i.listLinks(a)]),g=new Map(s.map(h=>[h.groupId,h]));return o.map(h=>{let T=g.get(h.id);return{id:h.id,groupKey:h.groupKey,name:h.name,description:h.description===null||h.description===""?void 0:h.description,isActive:h.isActive,readOnly:T!==void 0,...T===void 0?{}:{externalLink:Rt(T)}}})},"readGroups"),z=r(async o=>{let s=(await H()).find(g=>g.id===o);if(s===void 0)throw new q(p.groupNotFound(o));return s},"readGroup"),l=r(async o=>{let[s]=await t.select({id:d.id}).from(d).where(x(o));if(s===void 0)throw new q(p.groupNotFound(o))},"assertGroupInTenant"),m=r(async o=>{let[s]=await t.select({externalKey:b.externalKey}).from(b).where(M(I(b.groupId,o),I(b.tenantId,a)));if(s!==void 0)throw new q(p.upstreamOwned(s.externalKey))},"assertGroupIsLocallyManaged");return{listUsers:S,createUser:r(async o=>{let s=y(),g=await k.run(t,t.insert(A).output({id:k.field}).values({..._(o.email,o.displayName,s,L),email:o.email,isActive:!0}));return V(W(g,"TDUsers"))},"createUser"),updateUser:r(async(o,s)=>(await t.update(A).set({email:s.email,displayName:s.displayName,updatedAt:y(),updatedBy:L}).where(I(A.id,o)),V(o)),"updateUser"),toggleUserActive:r(async(o,s)=>{let g={isActive:s,updatedAt:y(),updatedBy:L};return s?await t.update(A).set(g).where(I(A.id,o)):await u.guardedWrite(a,{deactivateUserId:o},"deactivate-user",h=>ne(h).update(A).set(g).where(I(A.id,o))),V(o)},"toggleUserActive"),listGroups:H,createGroup:r(async o=>{let s=await O.run(t,t.insert(d).output({id:O.field}).values({tenantId:a,groupKey:o.groupKey,name:o.name,description:o.description??null,isActive:!0,createdAt:y(),createdBy:L}));return z(W(s,"TMGroup"))},"createGroup"),createLinkedGroup:r(async o=>{let s=await c.withAuthzTransaction(async(g,h)=>{let T=h,N=await O.run(T,T.insert(d).output({id:O.field}).values({tenantId:a,groupKey:o.groupKey,name:o.name,description:o.description??null,isActive:!0,createdAt:y(),createdBy:L})),G=W(N,"TMGroup");return await c.withAmbientAuthzTransaction(g,()=>i.linkGroup(a,G,{provider:o.provider,externalId:o.externalId,externalKey:o.externalKey,membershipMode:o.membershipMode},L)),G});return z(s)},"createLinkedGroup"),updateGroup:r(async(o,s)=>(await m(o),await t.update(d).set({name:s.name,description:s.description??null,updatedAt:y(),updatedBy:L}).where(x(o)),z(o)),"updateGroup"),deleteGroup:r(async o=>{await m(o),await u.guardedWrite(a,{removeGroupId:o},"delete-group",async s=>{let g=ne(s),[h]=await g.select({id:d.id}).from(d).where(x(o));if(h===void 0)throw new q(p.groupNotFound(o));await g.delete(R).where(I(R.groupId,o)),await g.delete(f).where(I(f.groupId,o)),await g.delete(d).where(x(o))})},"deleteGroup"),listGroupMembers:r(async()=>(await t.select({id:f.id,groupId:f.groupId,userId:f.userId}).from(f).innerJoin(d,M(I(d.id,f.groupId),I(d.tenantId,a))).orderBy(F(f.groupId),F(f.userId))).map(s=>({id:s.id,groupId:s.groupId,userId:s.userId})),"listGroupMembers"),addGroupMember:r(async(o,s)=>{await l(o),await m(o);let[g]=await t.select({id:f.id}).from(f).where(M(I(f.groupId,o),I(f.userId,s)));if(g!==void 0)return{id:g.id,groupId:o,userId:s};let h=await E.run(t,t.insert(f).output({id:E.field}).values({groupId:o,userId:s,createdAt:y(),createdBy:L}));return{id:W(h,"TDGroupMember"),groupId:o,userId:s}},"addGroupMember"),removeGroupMember:r(async(o,s)=>{await l(o),await m(o),await u.guardedWrite(a,{removeGroupMembership:{groupId:o,userId:s}},"remove-group-member",g=>ne(g).delete(f).where(M(I(f.groupId,o),I(f.userId,s))))},"removeGroupMember"),listAllowlist:r(()=>i.listAllowlistGroups(a),"listAllowlist"),addAllowlistEntry:r(async()=>{throw new q(p.patternEntriesUnused)},"addAllowlistEntry"),removeAllowlistEntry:r(async()=>{throw new q(p.patternEntriesUnused)},"removeAllowlistEntry"),addAllowlistGroup:r((o,s)=>i.addAllowlistGroup(a,o,s,L),"addAllowlistGroup"),removeAllowlistGroup:r(o=>i.removeAllowlistGroup(a,o),"removeAllowlistGroup"),linkDirectoryGroup:r((o,s)=>i.linkGroup(a,o,{provider:s.provider,externalId:s.externalId,externalKey:s.externalKey,membershipMode:s.membershipMode},L),"linkDirectoryGroup"),unlinkDirectoryGroup:r(o=>i.unlinkGroup(a,o),"unlinkDirectoryGroup"),setDirectorySyncEnabled:r((o,s)=>i.setSyncEnabled(a,o,s,L),"setDirectorySyncEnabled"),requestDirectorySync:r((o,s)=>i.requestSync(a,o,s),"requestDirectorySync"),getDirectoryStatus:r(()=>i.getStatus(a),"getDirectoryStatus")}},"createVaultHostUserAdminStore");var ze="aiquants-vault-host",Ft="vault-host",Wt="sign-out",Yt=2048,Zt=/^(\/[A-Za-z0-9_~-][A-Za-z0-9._~-]*)+$/u,Jt=r(e=>{let t=["vault","signIn","signInCallback","signOut","authzAdmin","userAdmin"];for(let n of t){let a=typeof e=="object"&&e!==null?e[n]:void 0;if(typeof a!="string"||!Zt.test(a)||a.split("/").some(i=>i==="."||i===".."))throw new RangeError(`[@aiquants/vault-host] paths.${n} must be an absolute route path without a trailing slash`)}if(new Set(t.map(n=>e[n])).size!==t.length)throw new RangeError("[@aiquants/vault-host] the six paths must all differ");return Object.freeze({vault:e.vault,signIn:e.signIn,signInCallback:e.signInCallback,signOut:e.signOut,authzAdmin:e.authzAdmin,userAdmin:e.userAdmin})},"checkedPaths"),Qt=r((e,t)=>{if(!U.includes(e.locale))throw new RangeError(`[@aiquants/vault-host] locale must be one of ${U.join(", ")}`);let{placement:n,logger:a,connect:i,authzAdminResource:u}=e;if(typeof n!="object"||n===null||typeof n.secretIdRule!="function"||typeof n.listWhileSealed!="boolean")throw new TypeError("[@aiquants/vault-host] placement needs secretIdRule (a function), compartmentOf and listWhileSealed (a boolean)");if(typeof a!="object"||a===null||[a.info,a.warn,a.error].some(y=>typeof y!="function"))throw new TypeError("[@aiquants/vault-host] logger needs info, warn and error functions");if(typeof i!="function")throw new TypeError("[@aiquants/vault-host] connect must be a function (nodeMssqlVaultHostConnection)");let c=typeof u=="object"&&u!==null?u.key:void 0,p=typeof u=="object"&&u!==null?u.name:void 0;if(typeof c!="string"||c.trim()===""||typeof p!="string"||p.trim()==="")throw new RangeError("[@aiquants/vault-host] authzAdminResource needs a non-blank key and name");if(c===t||c.startsWith(`${t}.`))throw new RangeError(`[@aiquants/vault-host] authzAdminResource.key must not be under the vault's resource prefix (${t})`)},"checkOptions"),Xt=r(e=>{let t=new URL(e.url);return`${t.pathname}${t.search}`},"returnToOf"),er=r(e=>{let t=ae(e.env);Qt(e,t.authz.resourcePrefix);let n=Jt(e.paths),a=Se(e.schemas),{locale:i,logger:u,placement:c,authzAdminResource:p}=e,y=i==="ja",A=y?Le:Oe,{tenantId:d,appKey:f,resourcePrefix:R}=t.authz,{numbers:b}=t,k=Re(a),O=oe(t.database,t.runtime,ze),E=e.connect(O),{db:S}=E,V=Ve({db:S,tables:k,tenantId:d,appKey:f,adminResourceKey:p.key,directoryEnabled:t.directoryEnabled,lockoutMessage:y?qt:void 0,lockPrincipal:t.authz.lockPrincipal,logger:u}),x=Te({db:S,tables:k,binding:V.binding,tenantId:d,ledger:V.directoryLinkStore,signInDomain:t.signInDomain,googleClientId:t.google.clientId,signupLockPrincipal:t.signupLockPrincipal,logger:u}),H=Pt({google:{clientId:t.google.clientId,clientSecret:t.google.clientSecret,redirectURI:t.google.redirectUrl},session:{secrets:[t.sessionSecret],secure:!0},messages:A.authMessages,logger:j(u),isEmailAllowed:x.isEmailAllowed,isUserActive:x.isUserActive,sessionGeneration:{store:Ot(S,k.sessionGeneration,{actor:Wt})},readerCheck:!0,backendAuth:x.backendAuth,loginPath:n.signIn,postLoginRedirect:n.vault,postLogoutRedirect:n.signIn,returnTo:{allowedPaths:[n.vault,n.authzAdmin,n.userAdmin],pages:{excludedPathPrefixes:[`${n.vault}/-/api/`,n.signIn,n.signInCallback,n.signOut],maxLength:Yt}}}),z=r(v=>H.getSessionUser(v),"sessionUserOf"),l=be({db:S,tables:k,identity:V,permissions:Ae(S,k,f),appKey:f,resourcePrefix:R,sessionUserOf:z,logger:u}),m=we({authz:l,clientAddressHeader:t.headers.clientAddress,requestIdHeader:t.headers.requestId}),o=Mt({storage:Dt({db:S,schema:Ut(a.vault),lockTimeoutMs:b.lockTimeoutMs,ceremonyLockTimeoutMs:b.ceremonyLockTimeoutMs,lockPrincipal:t.lockPrincipal,transactionRetry:le(b.transactionRetryAttempts,u),openSessionConnection:ie}),authorizer:l.vaultAuthorizer,logger:u,clock:J,secretIdRule:c.secretIdRule,compartmentOf:c.compartmentOf,listWhileSealed:c.listWhileSealed,unseal:{progressTtlSeconds:b.unsealProgressTtlSeconds,failureLimit:b.unsealFailureLimit,lockoutSeconds:b.unsealLockoutSeconds},limits:{maxBodyBytes:b.maxBodyBytes,maxAttachmentCount:b.maxAttachmentCount,maxRequestBytes:b.maxRequestBytes},audit:{pageSize:b.auditPageSize}}),s=se({store:V.authzAdminStore,tenantId:d,appKey:f,resourcePrefix:R,nameOf:A.resourceNameOf}),g=_t({vault:o,basePath:n.vault,crossOrigin:Kt({mountPath:n.vault}),resolveContext:m,reveal:{hideSeconds:b.revealHideSeconds},logger:u,compartments:ue(s),labels:{...y?Bt:jt,timeZone:b.exportTimeZone}}),h=r(v=>H.requireUser(v,Xt(v)),"requireUser"),T=Gt({store:V.authzAdminStore,basePath:n.authzAdmin,resourceKey:p.key,requireUser:h,requirePermission:l.requirePermission,labels:y?{...Nt,adminResourceName:p.name}:{adminResourceName:p.name}}),N=Lt(de({store:Pe({db:S,tables:k,tenantId:d,links:V.directoryLinkStore,lockoutGuard:V.adminLockoutGuard,transactions:V,refusals:A.refusals,now:J}),fieldLimits:xe(k),labels:y?xt:void 0,resource:p,requireUser:h,requirePermission:l.requirePermission,getMyPermissions:l.getMyPermissions,sessionUserOf:z,catalog:V.directoryCatalog,tenantId:d,logger:u})),G=ce({sessionUserOf:z,readerStampOf:H.readerStampOf,locale:i,timeZone:b.exportTimeZone,paths:n}),Y=me({open:r(()=>E.open(),"open"),checkLocks:ge({check:r((v,Ne)=>Ct(S,v,Ne),"check"),roles:[{lockPrincipal:t.authz.lockPrincipal,settingName:D.authz},{lockPrincipal:t.lockPrincipal,settingName:D.vault},{lockPrincipal:t.signupLockPrincipal,settingName:D.signup}]}),listResources:r(v=>V.authzAdminStore.listResources(v),"listResources"),listCompartments:r(()=>o.listCompartments(),"listCompartments"),register:s,tenantId:d,appKey:f,adminResourceKey:p.key,actor:Ft}),Z=fe({disposeVault:r(()=>o.dispose(),"disposeVault"),close:r(()=>E.close(),"close")}),Ee=pe({refusalOf:zt,refusalResponse:r(()=>Et(H.messages),"refusalResponse"),signOut:r(v=>H.logoutAndRedirect(v),"signOut"),logger:u}),Ge=Object.freeze({root:Object.freeze({loader:G}),vault:Object.freeze({loader:ye(h,g.ui.loader),action:r(v=>g.ui.action(v),"action"),headers:$t}),vaultApi:Object.freeze({action:r(v=>g.api.action(v),"action")}),signIn:Object.freeze({loader:r(({request:v})=>H.loginLoader({request:v}),"loader"),action:r(({request:v})=>H.loginAction({request:v}),"action")}),signInCallback:Object.freeze({loader:r(({request:v})=>H.googleCallbackLoader({request:v}),"loader")}),signOut:Object.freeze({loader:Ee}),authzAdmin:Object.freeze({loader:T.loader,action:T.action}),userAdmin:Object.freeze({loader:N.loader,action:N.action})});return Object.freeze({vault:o,vaultApp:g,auth:H,authzAdmin:T,userAdmin:N,routes:Ge,start:Y,dispose:Z,locale:i,paths:n})},"createVaultHost");export{C as DIRECTORY_STALENESS_PARAMETER,ze as VAULT_HOST_APP_NAME,U as VAULT_HOST_LOCALES,Me as VAULT_HOST_ROOT_ROUTE_ID,qe as VaultHostConfigError,er as createVaultHost,Ce as nodeMssqlVaultHostConnection};
package/package.json CHANGED
@@ -1,6 +1,143 @@
1
1
  {
2
2
  "name": "@aiquants/vault-host",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "Assembles a vault app from its database and environment: Google sign-in limited to one Workspace domain and the vault's allowlist groups, authz and its admin screens, user and group admin with directory links, the vault screens with their compartment face, and the key ceremony.",
5
+ "sideEffects": false,
6
+ "main": "dist/server.js",
7
+ "module": "dist/server.mjs",
8
+ "types": "dist/server.d.ts",
9
+ "exports": {
10
+ "./server": {
11
+ "import": {
12
+ "types": "./dist/server.d.mts",
13
+ "default": "./dist/server.mjs"
14
+ },
15
+ "require": {
16
+ "types": "./dist/server.d.ts",
17
+ "default": "./dist/server.js"
18
+ }
19
+ },
20
+ "./client": {
21
+ "import": {
22
+ "types": "./dist/client.d.mts",
23
+ "default": "./dist/client.mjs"
24
+ },
25
+ "require": {
26
+ "types": "./dist/client.d.ts",
27
+ "default": "./dist/client.js"
28
+ }
29
+ },
30
+ "./cli": {
31
+ "import": {
32
+ "types": "./dist/cli.d.mts",
33
+ "default": "./dist/cli.mjs"
34
+ },
35
+ "require": {
36
+ "types": "./dist/cli.d.ts",
37
+ "default": "./dist/cli.js"
38
+ }
39
+ }
40
+ },
41
+ "files": [
42
+ "dist",
43
+ "!dist/metafile-*.json",
44
+ "README.md",
45
+ "LICENSE"
46
+ ],
47
+ "keywords": [
48
+ "vault",
49
+ "secrets",
50
+ "react-router",
51
+ "authz",
52
+ "google-workspace",
53
+ "typescript"
54
+ ],
55
+ "author": {
56
+ "name": "fehde-k",
57
+ "url": "https://x.com/fehdek"
58
+ },
59
+ "license": "MIT",
60
+ "devDependencies": {
61
+ "@aiquants/auth-core": "0.9.6",
62
+ "@aiquants/auth-directory-core": "0.6.0",
63
+ "@aiquants/auth-directory-drizzle": "0.23.0",
64
+ "@aiquants/auth-react-router": "0.54.0",
65
+ "@aiquants/authz-core": "0.7.1",
66
+ "@aiquants/authz-drizzle": "4.0.0",
67
+ "@aiquants/authz-react-router": "0.36.0",
68
+ "@aiquants/console-ui": "0.12.1",
69
+ "@aiquants/fuzzy-search": "3.2.3",
70
+ "@aiquants/mssql": "0.5.0",
71
+ "@aiquants/request-isolation": "0.1.1",
72
+ "@aiquants/select-box": "0.24.1",
73
+ "@aiquants/vault-core": "0.7.0",
74
+ "@aiquants/vault-drizzle": "0.5.0",
75
+ "@aiquants/vault-react-router": "0.4.0",
76
+ "@aiquants/virtualscroll": "3.31.4",
77
+ "@testing-library/jest-dom": "^6.9.1",
78
+ "@testing-library/react": "^16.3.2",
79
+ "@types/mssql": "^9.1.9",
80
+ "@types/node": "^24.10.3",
81
+ "@types/react": "^19.2.7",
82
+ "@types/react-dom": "^19.2.3",
83
+ "@vitest/coverage-v8": "^4.1.10",
84
+ "drizzle-orm": "1.0.0-rc.4",
85
+ "jsdom": "^27.4.0",
86
+ "mssql": "^11.0.1",
87
+ "react": "^19.2.7",
88
+ "react-dom": "^19.2.7",
89
+ "react-icons": "^5.5.0",
90
+ "react-router": "^8.3.0",
91
+ "remix-auth": "^4.2.0",
92
+ "remix-auth-oauth2": "^3.4.1",
93
+ "rimraf": "^6.1.2",
94
+ "tsup": "^8.5.1",
95
+ "typescript": "^5.9.3",
96
+ "vite": "^7.3.1",
97
+ "vitest": "^4.1.10",
98
+ "zod": "^3.25.76"
99
+ },
100
+ "peerDependencies": {
101
+ "@aiquants/auth-core": "^0.9.6",
102
+ "@aiquants/auth-directory-core": "^0.6.0",
103
+ "@aiquants/auth-directory-drizzle": "^0.23.0",
104
+ "@aiquants/auth-react-router": "^0.54.0",
105
+ "@aiquants/authz-core": "^0.7.1",
106
+ "@aiquants/authz-drizzle": "^4.0.0",
107
+ "@aiquants/authz-react-router": "^0.36.0",
108
+ "@aiquants/console-ui": "^0.12.1",
109
+ "@aiquants/mssql": "^0.5.0",
110
+ "@aiquants/vault-core": "^0.7.0",
111
+ "@aiquants/vault-drizzle": "^0.5.0",
112
+ "@aiquants/vault-react-router": "^0.4.0",
113
+ "drizzle-orm": ">=1.0.0-beta.4 <2.0.0",
114
+ "mssql": "^11.0.1",
115
+ "react": "^19.2.7",
116
+ "react-router": "^7.0.0 || ^8.0.0"
117
+ },
118
+ "engines": {
119
+ "node": ">=24.0.0",
120
+ "pnpm": ">=8.0.0"
121
+ },
122
+ "publishConfig": {
123
+ "access": "public"
124
+ },
125
+ "scripts": {
126
+ "build": "pnpm -w run workspace:build \"$PNPM_SCRIPT_SRC_DIR\"",
127
+ "prebuild:self": "pnpm -w run workspace:sync \"$PNPM_SCRIPT_SRC_DIR\"",
128
+ "build:self": "rimraf dist && tsup && node ../../.config/scripts/strip-dts-comments.mjs dist",
129
+ "build:watch": "tsup --watch",
130
+ "dev": "tsup --watch",
131
+ "typecheck": "tsc --noEmit",
132
+ "clean": "rimraf dist",
133
+ "publish:patch": "pnpm run typecheck && pnpm run --if-present test && pnpm run build && node ../../.config/scripts/check-publish-leaks.mjs && node ../../.config/scripts/check-peer-floors.mjs --bump patch && pnpm version patch --no-git-tag-version --no-git-checks && pnpm publish --no-git-checks",
134
+ "publish:minor": "pnpm run typecheck && pnpm run --if-present test && pnpm run build && node ../../.config/scripts/check-publish-leaks.mjs && node ../../.config/scripts/check-peer-floors.mjs --bump minor && pnpm version minor --no-git-tag-version --no-git-checks && pnpm publish --no-git-checks",
135
+ "publish:major": "pnpm run typecheck && pnpm run --if-present test && pnpm run build && node ../../.config/scripts/check-publish-leaks.mjs && node ../../.config/scripts/check-peer-floors.mjs --bump major && pnpm version major --no-git-tag-version --no-git-checks && pnpm publish --no-git-checks",
136
+ "lint": "biome lint src/",
137
+ "check": "biome check src/",
138
+ "check:fix": "biome check --write src/",
139
+ "license-check": "pnpm dlx license-checker --production --onlyAllow \"MIT;Apache-2.0;BSD-2-Clause;BSD-3-Clause;ISC;Unlicense\"",
140
+ "test": "vitest run",
141
+ "test:coverage": "vitest run --coverage"
142
+ }
6
143
  }