From 5b3352183257f48b94180dd46c2b21588bd9a93c Mon Sep 17 00:00:00 2001 From: Sawyer Date: Thu, 17 Sep 2026 08:56:34 -0700 Subject: [PATCH 1/3] test(onboarding): drop signup-gate coverage ahead of access-policy deletion The closed-signup gate genesis.ts called through @workbench/access-policy was never wired into any hub composition; these cases tested behavior the next commit deletes. Claude-Session: https://claude.ai/code/session_01RweuMUskU2nvcFhdckc7EG --- packages/access-policy/LICENSE | 176 ------------- packages/access-policy/README.md | 42 --- packages/access-policy/package.json | 30 --- packages/access-policy/src/gate.test.ts | 91 ------- packages/access-policy/src/gate.ts | 39 --- packages/access-policy/src/index.ts | 45 ---- packages/access-policy/src/migrations.ts | 83 ------ packages/access-policy/src/policy.test.ts | 246 ------------------ packages/access-policy/src/policy.ts | 139 ---------- packages/access-policy/src/routes.ts | 134 ---------- packages/access-policy/src/schema.ts | 35 --- packages/access-policy/src/store.ts | 135 ---------- packages/access-policy/src/types.ts | 45 ---- .../access-policy/test/store.drizzle.test.ts | 229 ---------------- packages/access-policy/tsconfig.json | 29 --- packages/access-policy/tsconfig.src.json | 27 -- packages/onboarding/test/genesis.test.ts | 142 ---------- packages/settings-ui/src/access-policy-api.ts | 60 ----- packages/settings-ui/src/access-policy.tsx | 213 --------------- .../test/access-policy-api.test.ts | 92 ------- 20 files changed, 2032 deletions(-) delete mode 100644 packages/access-policy/LICENSE delete mode 100644 packages/access-policy/README.md delete mode 100644 packages/access-policy/package.json delete mode 100644 packages/access-policy/src/gate.test.ts delete mode 100644 packages/access-policy/src/gate.ts delete mode 100644 packages/access-policy/src/index.ts delete mode 100644 packages/access-policy/src/migrations.ts delete mode 100644 packages/access-policy/src/policy.test.ts delete mode 100644 packages/access-policy/src/policy.ts delete mode 100644 packages/access-policy/src/routes.ts delete mode 100644 packages/access-policy/src/schema.ts delete mode 100644 packages/access-policy/src/store.ts delete mode 100644 packages/access-policy/src/types.ts delete mode 100644 packages/access-policy/test/store.drizzle.test.ts delete mode 100644 packages/access-policy/tsconfig.json delete mode 100644 packages/access-policy/tsconfig.src.json delete mode 100644 packages/settings-ui/src/access-policy-api.ts delete mode 100644 packages/settings-ui/src/access-policy.tsx delete mode 100644 packages/settings-ui/test/access-policy-api.test.ts diff --git a/packages/access-policy/LICENSE b/packages/access-policy/LICENSE deleted file mode 100644 index c6487f4fdf..0000000000 --- a/packages/access-policy/LICENSE +++ /dev/null @@ -1,176 +0,0 @@ -GNU LESSER GENERAL PUBLIC LICENSE - -Version 2.1, February 1999 - -Copyright (C) 1991, 1999 Free Software Foundation, Inc. -51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] - -Preamble - -The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. - -This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. - -When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. - -To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. - -For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. - -We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. - -To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. - -Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. - -Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. - -When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. - -We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. - -For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. - -In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. - -Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. - -The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. - -GNU LESSER GENERAL PUBLIC LICENSE -TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - -0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". - -A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. - -The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) - -"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. - -Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. - -1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. - -You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. - -2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. - -(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. - -3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. - -Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. - -This option is useful when you wish to copy part of the code of the Library into a program that is not a library. - -4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. - -If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. - -5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. - -However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. - -When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. - -If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) - -Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. - -6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. - -You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: - - a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. - - e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. - -For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. - -It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. - -7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. - - b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. - -8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. - -9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. - -10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. - -11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. - -This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. - -12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. - -13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. - -14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. - -NO WARRANTY - -15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -END OF TERMS AND CONDITIONS - -How to Apply These Terms to Your New Libraries - -If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). - -To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. - - one line to give the library's name and an idea of what it does. - Copyright (C) year name of author - - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: - -Yoyodyne, Inc., hereby disclaims all copyright interest in -the library `Frob' (a library for tweaking knobs) written -by James Random Hacker. - -signature of Ty Coon, 1 April 1990 -Ty Coon, President of Vice -That's all there is to it! diff --git a/packages/access-policy/README.md b/packages/access-policy/README.md deleted file mode 100644 index c98bd57b63..0000000000 --- a/packages/access-policy/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# @workbench/access-policy - -Closed-by-default access policy for the hub: per-tenant self-signup and -sub-workbench creation rules, layered over Interchange's native -tenancy/RBAC without patching vendor routes. Signup stays closed unless -an explicit policy row or env flag opens it. New humans join only when -an operator creates them through native APIs. - -## Composition over Interchange - -- No parallel tenancy or RBAC model: tenant creation and role checks - all go through native `@intx/hub-api` routes and grants. -- `policy.ts` is the pure evaluation core (no DB, no HTTP, no env) — - every decision (can this email self-sign-up, can this role create a - sub-workbench) reduces to a function call over plain data. -- `gate.ts` composes `policy.ts` with `store.ts` for the signup-gate - entry point `packages/onboarding`'s first-login hook calls. - -## Key modules - -- `policy.ts` — pure decision functions: `resolveAccessPolicy`, - `domainAllowed`, `evaluateSignupGate`, `canCreateTenancy`. -- `gate.ts` — composes policy + store for the onboarding first-login hook. -- `routes.ts` — tenant-scoped HTTP surface: read/edit a tenant's own - policy row and the gated `POST .../child-tenants` surface. -- `store.ts` — Postgres-backed persistence plus an in-memory fake for - tests that don't need a real database. -- `schema.ts` — the product table (`policy`), siloed in its own - `access_policy` Postgres schema, never `public`. -- `migrations.ts` — package-owned migrations with their own ledger table, - so the package can be extracted without disentangling platform history. -- `types.ts` — arktype shapes for anything crossing a trust boundary - (route bodies, DB columns). - -## Tests - -``` -cd packages/access-policy && bun test -``` - -`test/store.drizzle.test.ts` needs a real database: -`DATABASE_URL=postgres://localhost:5432/workbench_e2e bun test`. diff --git a/packages/access-policy/package.json b/packages/access-policy/package.json deleted file mode 100644 index 557ae865c2..0000000000 --- a/packages/access-policy/package.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "@workbench/access-policy", - "private": true, - "description": "Closed-by-default access policy for the hub: per-tenant self-signup and sub-workbench creation rules, layered over native tenancy/RBAC without patching vendor routes.", - "version": "0.0.1", - "license": "LGPL-2.1-or-later", - "type": "module", - "exports": { - ".": "./src/index.ts", - "./migrations": "./src/migrations.ts" - }, - "scripts": { - "typecheck": "tsc --noEmit", - "test": "bun test" - }, - "dependencies": { - "@corbits/error-sink": "workspace:*", - "@corbits/migration-runner": "workspace:*", - "@intx/hub-api": "workspace:*", - "@corbits/hub-api-client": "workspace:*", - "arktype": "catalog:", - "drizzle-orm": "catalog:", - "hono": "catalog:", - "postgres": "catalog:" - }, - "devDependencies": { - "@types/bun": "catalog:", - "typescript": "catalog:" - } -} diff --git a/packages/access-policy/src/gate.test.ts b/packages/access-policy/src/gate.test.ts deleted file mode 100644 index db48a19353..0000000000 --- a/packages/access-policy/src/gate.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { describe, expect, test } from "bun:test"; - -import { checkSignupGate } from "./gate"; -import { createInMemoryAccessPolicyStore } from "./store"; - -const verified = { emailVerified: true, allowUnverifiedEmails: false }; - -describe("checkSignupGate", () => { - test("no operator tenant configured -> closed defaults", async () => { - const store = createInMemoryAccessPolicyStore(); - const result = await checkSignupGate({ - store, - email: "person@acme.example", - ...verified, - }); - expect(result).toEqual({ allowed: false, reason: "signup_closed" }); - }); - - test("operator tenant with no policy row yet -> closed defaults", async () => { - const store = createInMemoryAccessPolicyStore(); - const result = await checkSignupGate({ - store, - operatorTenantId: "tnt_operator", - email: "person@acme.example", - ...verified, - }); - expect(result).toEqual({ allowed: false, reason: "signup_closed" }); - }); - - test("operator tenant with an explicit closed row stays closed", async () => { - const store = createInMemoryAccessPolicyStore(); - await store.upsertPolicy("tnt_operator", { selfSignup: "off" }); - const result = await checkSignupGate({ - store, - operatorTenantId: "tnt_operator", - email: "person@acme.example", - ...verified, - }); - expect(result).toEqual({ allowed: false, reason: "signup_closed" }); - }); - - test("operator tenant with an explicit open row allows", async () => { - const store = createInMemoryAccessPolicyStore(); - await store.upsertPolicy("tnt_operator", { selfSignup: "open" }); - const result = await checkSignupGate({ - store, - operatorTenantId: "tnt_operator", - email: "person@acme.example", - ...verified, - }); - expect(result).toEqual({ allowed: true, reason: "policy_open" }); - }); - - test("a policy row scoped to a different tenant never leaks into this check", async () => { - const store = createInMemoryAccessPolicyStore(); - await store.upsertPolicy("tnt_other", { selfSignup: "open" }); - const result = await checkSignupGate({ - store, - operatorTenantId: "tnt_operator", - email: "person@acme.example", - ...verified, - }); - expect(result).toEqual({ allowed: false, reason: "signup_closed" }); - }); - - test("exploit: an unverified email cannot self-sign-up even with an open policy", async () => { - const store = createInMemoryAccessPolicyStore(); - await store.upsertPolicy("tnt_operator", { selfSignup: "open" }); - const result = await checkSignupGate({ - store, - operatorTenantId: "tnt_operator", - email: "attacker@acme.example", - emailVerified: false, - allowUnverifiedEmails: false, - }); - expect(result).toEqual({ allowed: false, reason: "email_unverified" }); - }); - - test("allowUnverifiedEmails opt-out restores the ordinary decision", async () => { - const store = createInMemoryAccessPolicyStore(); - await store.upsertPolicy("tnt_operator", { selfSignup: "open" }); - const result = await checkSignupGate({ - store, - operatorTenantId: "tnt_operator", - email: "dev@acme.example", - emailVerified: false, - allowUnverifiedEmails: true, - }); - expect(result).toEqual({ allowed: true, reason: "policy_open" }); - }); -}); diff --git a/packages/access-policy/src/gate.ts b/packages/access-policy/src/gate.ts deleted file mode 100644 index dedadb6b5a..0000000000 --- a/packages/access-policy/src/gate.ts +++ /dev/null @@ -1,39 +0,0 @@ -// Composition over `./policy.ts`'s pure functions and `./store.ts`'s -// persistence: the signup-gate entry point `packages/onboarding`'s -// first-login hook calls. -import { evaluateSignupGate, type SignupGateResult } from "./policy"; -import type { AccessPolicyStore } from "./store"; - -export type SignupGateCheckArgs = { - readonly store: AccessPolicyStore; - /** The tenant a fresh personal bench would be parented under, if - * any — the same `operatorTenantId` the onboarding hook already - * threads into tenant creation. No operator tenant means there is no - * tenant to hold a policy row, so the closed defaults apply. */ - readonly operatorTenantId?: string; - readonly email: string; - readonly emailVerified: boolean; - readonly allowUnverifiedEmails: boolean; -}; - -/** - * The one signup-gate check the first-login hook calls before minting a - * personal bench. Looks up whether the operator tenant carries an - * explicit policy row; if so that row decides outright, otherwise the - * closed defaults apply. - */ -export async function checkSignupGate( - args: SignupGateCheckArgs, -): Promise { - let policy: Awaited> | undefined; - if (args.operatorTenantId !== undefined) { - const hasRow = await args.store.hasPolicyRow(args.operatorTenantId); - if (hasRow) policy = await args.store.getPolicy(args.operatorTenantId); - } - return evaluateSignupGate({ - policy, - email: args.email, - emailVerified: args.emailVerified, - allowUnverifiedEmails: args.allowUnverifiedEmails, - }); -} diff --git a/packages/access-policy/src/index.ts b/packages/access-policy/src/index.ts deleted file mode 100644 index e8265fd67f..0000000000 --- a/packages/access-policy/src/index.ts +++ /dev/null @@ -1,45 +0,0 @@ -export { - DEFAULT_ACCESS_POLICY, - AccessPolicy, - UpdateAccessPolicy, - SelfSignupMode, - TenancyCreationMode, -} from "./types"; - -export { - resolveAccessPolicy, - domainOf, - domainAllowed, - evaluateSignupGate, - canCreateTenancy, - parseAllowedDomainsColumn, - serializeAllowedDomains, -} from "./policy"; -export type { - SignupGateArgs, - SignupGateReason, - SignupGateResult, -} from "./policy"; - -export { - createDrizzleAccessPolicyStore, - createInMemoryAccessPolicyStore, -} from "./store"; -export type { AccessPolicyStore } from "./store"; - -export { checkSignupGate } from "./gate"; -export type { SignupGateCheckArgs } from "./gate"; - -export { createAccessPolicyRoutes } from "./routes"; -export type { CreateAccessPolicyRoutesDeps } from "./routes"; - -export { accessPolicySchema, policy } from "./schema"; - -export { - accessPolicyMigrations, - applyAccessPolicyMigrations, -} from "./migrations"; -export type { - AccessPolicyMigration, - ApplyAccessPolicyMigrationsReport, -} from "./migrations"; diff --git a/packages/access-policy/src/migrations.ts b/packages/access-policy/src/migrations.ts deleted file mode 100644 index 91ffceb7b3..0000000000 --- a/packages/access-policy/src/migrations.ts +++ /dev/null @@ -1,83 +0,0 @@ -// Package-owned migrations for @workbench/access-policy. Bookkeeping -// uses its own ledger table so the package can be extracted without -// disentangling history from the platform drizzle journal. Every table -// this package owns — including its ledger — lives in its own -// `access_policy` Postgres schema, never `public`; see -// docs/package-migrations.md. Mechanics (schema/ledger bootstrap, -// transactional apply, the advisory lock across concurrent hub -// replicas) live in @corbits/migration-runner — this file owns only -// the domain SQL. -import { - applyPackageMigrations, - type ApplyPackageMigrationsReport, - type PackageMigration, -} from "@corbits/migration-runner"; - -export type AccessPolicyMigration = PackageMigration; - -const SCHEMA = "access_policy"; - -export const accessPolicyMigrations: readonly AccessPolicyMigration[] = [ - { - name: "0001_policy", - sql: ` - CREATE TABLE IF NOT EXISTS "access_policy"."policy" ( - "tenant_id" text PRIMARY KEY, - "self_signup" text NOT NULL DEFAULT 'off', - "allowed_domains" text NOT NULL DEFAULT '[]', - "tenancy_creation" text NOT NULL DEFAULT 'owners', - "created_at" timestamptz NOT NULL DEFAULT now(), - "updated_at" timestamptz NOT NULL DEFAULT now(), - CONSTRAINT "policy_self_signup_check" - CHECK ("self_signup" IN ('off', 'allowed-domains', 'open')), - CONSTRAINT "policy_tenancy_creation_check" - CHECK ("tenancy_creation" IN ('owners', 'owners-admins', 'none')) - ); - `, - }, - { - name: "0002_pending_invite", - sql: ` - CREATE TABLE IF NOT EXISTS "access_policy"."pending_invite" ( - "id" text PRIMARY KEY, - "tenant_id" text NOT NULL, - "match_type" text NOT NULL, - "value" text NOT NULL, - "role_id" text, - "invited_by" text, - "created_at" timestamptz NOT NULL DEFAULT now(), - "consumed_at" timestamptz, - CONSTRAINT "pending_invite_match_type_check" - CHECK ("match_type" IN ('email', 'domain')) - ); - CREATE INDEX IF NOT EXISTS "pending_invite_value_idx" - ON "access_policy"."pending_invite" ("value"); - CREATE INDEX IF NOT EXISTS "pending_invite_tenant_idx" - ON "access_policy"."pending_invite" ("tenant_id"); - `, - }, - { - name: "0003_drop_pending_invite", - sql: ` - DROP INDEX IF EXISTS "access_policy"."pending_invite_value_idx"; - DROP INDEX IF EXISTS "access_policy"."pending_invite_tenant_idx"; - DROP TABLE IF EXISTS "access_policy"."pending_invite"; - `, - }, -]; - -const LEDGER_TABLE = "access_policy_migrations"; - -export type ApplyAccessPolicyMigrationsReport = ApplyPackageMigrationsReport; - -export async function applyAccessPolicyMigrations( - databaseUrl: string, -): Promise { - return applyPackageMigrations({ - databaseUrl, - schema: SCHEMA, - ledgerTable: LEDGER_TABLE, - migrations: accessPolicyMigrations, - packageLabel: "access_policy", - }); -} diff --git a/packages/access-policy/src/policy.test.ts b/packages/access-policy/src/policy.test.ts deleted file mode 100644 index 6e671eca02..0000000000 --- a/packages/access-policy/src/policy.test.ts +++ /dev/null @@ -1,246 +0,0 @@ -import { describe, expect, test } from "bun:test"; - -import { - canCreateTenancy, - domainAllowed, - domainOf, - evaluateSignupGate, - resolveAccessPolicy, -} from "./policy"; -import { DEFAULT_ACCESS_POLICY, type AccessPolicy } from "./types"; - -describe("domainOf", () => { - test("lowercases and takes everything after the last @", () => { - expect(domainOf("Alice@Acme.Example")).toBe("acme.example"); - }); - - test("rejects a value with no @", () => { - expect(domainOf("not-an-email")).toBeUndefined(); - }); - - test("rejects an @ with nothing after it", () => { - expect(domainOf("alice@")).toBeUndefined(); - }); - - test("rejects an @ with nothing before it", () => { - expect(domainOf("@acme.example")).toBeUndefined(); - }); -}); - -describe("domainAllowed", () => { - test("an empty allowlist permits any domain", () => { - expect(domainAllowed("acme.example", [])).toBe(true); - }); - - test("matches case-insensitively against the allowlist", () => { - expect(domainAllowed("acme.example", ["ACME.example"])).toBe(true); - }); - - test("rejects a domain not on a non-empty allowlist", () => { - expect(domainAllowed("evil.example", ["acme.example"])).toBe(false); - }); -}); - -describe("resolveAccessPolicy", () => { - test("an absent row resolves to closed defaults", () => { - expect(resolveAccessPolicy(undefined)).toEqual(DEFAULT_ACCESS_POLICY); - }); - - test("a row's allowed_domains JSON column round-trips", () => { - const resolved = resolveAccessPolicy({ - tenantId: "tnt_1", - selfSignup: "allowed-domains", - allowedDomains: JSON.stringify(["acme.example", "widgets.example"]), - tenancyCreation: "owners-admins", - }); - expect(resolved).toEqual({ - selfSignup: "allowed-domains", - allowedDomains: ["acme.example", "widgets.example"], - tenancyCreation: "owners-admins", - }); - }); - - test("a corrupt allowed_domains column fails closed to an empty list", () => { - const resolved = resolveAccessPolicy({ - tenantId: "tnt_1", - selfSignup: "allowed-domains", - allowedDomains: "{not json", - tenancyCreation: "owners", - }); - expect(resolved.allowedDomains).toEqual([]); - }); -}); - -describe("evaluateSignupGate", () => { - const email = "person@acme.example"; - const verified = { emailVerified: true, allowUnverifiedEmails: false }; - - test("rejects an unparseable email regardless of policy", () => { - const result = evaluateSignupGate({ - policy: { ...DEFAULT_ACCESS_POLICY, selfSignup: "open" }, - email: "not-an-email", - ...verified, - }); - expect(result).toEqual({ allowed: false, reason: "invalid_email" }); - }); - - test("no policy row -> closed defaults", () => { - const result = evaluateSignupGate({ - policy: undefined, - email, - ...verified, - }); - expect(result).toEqual({ allowed: false, reason: "signup_closed" }); - }); - - test("an explicit closed row stays closed", () => { - const policy: AccessPolicy = { - selfSignup: "off", - allowedDomains: [], - tenancyCreation: "owners", - }; - const result = evaluateSignupGate({ - policy, - email, - ...verified, - }); - expect(result).toEqual({ allowed: false, reason: "signup_closed" }); - }); - - test("an explicit open row allows", () => { - const policy: AccessPolicy = { - selfSignup: "open", - allowedDomains: [], - tenancyCreation: "owners", - }; - const result = evaluateSignupGate({ - policy, - email, - ...verified, - }); - expect(result).toEqual({ allowed: true, reason: "policy_open" }); - }); - - test("policy row allowed-domains: a matching domain is allowed", () => { - const policy: AccessPolicy = { - selfSignup: "allowed-domains", - allowedDomains: ["acme.example"], - tenancyCreation: "owners", - }; - const result = evaluateSignupGate({ - policy, - email, - ...verified, - }); - expect(result).toEqual({ allowed: true, reason: "policy_domain_match" }); - }); - - test("policy row allowed-domains: a non-matching domain is rejected", () => { - const policy: AccessPolicy = { - selfSignup: "allowed-domains", - allowedDomains: ["widgets.example"], - tenancyCreation: "owners", - }; - const result = evaluateSignupGate({ - policy, - email, - ...verified, - }); - expect(result).toEqual({ allowed: false, reason: "domain_not_allowed" }); - }); - - test("exploit: an unverified email cannot pass an allowed-domains policy match", () => { - const policy: AccessPolicy = { - selfSignup: "allowed-domains", - allowedDomains: ["acme.example"], - tenancyCreation: "owners", - }; - const result = evaluateSignupGate({ - policy, - email, - emailVerified: false, - allowUnverifiedEmails: false, - }); - expect(result).toEqual({ allowed: false, reason: "email_unverified" }); - }); - - test("exploit: an unverified email cannot pass a fully open policy", () => { - const policy: AccessPolicy = { - selfSignup: "open", - allowedDomains: [], - tenancyCreation: "owners", - }; - const result = evaluateSignupGate({ - policy, - email, - emailVerified: false, - allowUnverifiedEmails: false, - }); - expect(result).toEqual({ allowed: false, reason: "email_unverified" }); - }); - - test("the allowUnverifiedEmails dev escape hatch restores the normal decision", () => { - const policy: AccessPolicy = { - selfSignup: "open", - allowedDomains: [], - tenancyCreation: "owners", - }; - const result = evaluateSignupGate({ - policy, - email, - emailVerified: false, - allowUnverifiedEmails: true, - }); - expect(result).toEqual({ allowed: true, reason: "policy_open" }); - }); - - test("email-verification is checked before policy, so it also fails closed for selfSignup off", () => { - const result = evaluateSignupGate({ - policy: { ...DEFAULT_ACCESS_POLICY, selfSignup: "off" }, - email, - emailVerified: false, - allowUnverifiedEmails: false, - }); - expect(result).toEqual({ allowed: false, reason: "email_unverified" }); - }); -}); - -describe("canCreateTenancy", () => { - test("owners mode: only an owner role passes", () => { - const policy: AccessPolicy = { - ...DEFAULT_ACCESS_POLICY, - tenancyCreation: "owners", - }; - expect(canCreateTenancy(policy, ["owner"])).toBe(true); - expect(canCreateTenancy(policy, ["admin"])).toBe(false); - expect(canCreateTenancy(policy, ["member"])).toBe(false); - expect(canCreateTenancy(policy, [])).toBe(false); - }); - - test("owners-admins mode: owner or admin passes, member does not", () => { - const policy: AccessPolicy = { - ...DEFAULT_ACCESS_POLICY, - tenancyCreation: "owners-admins", - }; - expect(canCreateTenancy(policy, ["owner"])).toBe(true); - expect(canCreateTenancy(policy, ["admin"])).toBe(true); - expect(canCreateTenancy(policy, ["member"])).toBe(false); - }); - - test("none mode: nobody passes, not even an owner", () => { - const policy: AccessPolicy = { - ...DEFAULT_ACCESS_POLICY, - tenancyCreation: "none", - }; - expect(canCreateTenancy(policy, ["owner"])).toBe(false); - expect(canCreateTenancy(policy, ["admin"])).toBe(false); - }); - - test("role names are matched case-insensitively", () => { - const policy: AccessPolicy = { - ...DEFAULT_ACCESS_POLICY, - tenancyCreation: "owners", - }; - expect(canCreateTenancy(policy, ["Owner"])).toBe(true); - }); -}); diff --git a/packages/access-policy/src/policy.ts b/packages/access-policy/src/policy.ts deleted file mode 100644 index 00bee06dcc..0000000000 --- a/packages/access-policy/src/policy.ts +++ /dev/null @@ -1,139 +0,0 @@ -// The pure evaluation core: no DB, no HTTP, no env access. Every -// decision this package makes — can this email self-sign-up, can this -// role create a sub-workbench — reduces to one of the functions below, -// called with plain data. Everything else in the package (store.ts, -// gate.ts, routes.ts) is composition around this file. -import { type } from "arktype"; - -import { - AccessPolicy, - DEFAULT_ACCESS_POLICY, - type PolicyRowShape, -} from "./types"; - -/** Parses the `allowed_domains` column's JSON text. A malformed value - * (should never happen — the column is only ever written by this - * package) is treated as empty rather than thrown, so a corrupt row - * fails closed on domain matching instead of crashing the request. */ -export function parseAllowedDomainsColumn(raw: string): string[] { - let parsed: unknown; - try { - parsed = JSON.parse(raw); - } catch { - return []; - } - const result = type("string[]")(parsed); - return result instanceof type.errors ? [] : result; -} - -export function serializeAllowedDomains(domains: readonly string[]): string { - return JSON.stringify(domains); -} - -/** Absent row = closed defaults: signup off, owners-only sub-workbench - * creation. This is the one place that default is expressed. */ -export function resolveAccessPolicy( - row: PolicyRowShape | undefined, -): AccessPolicy { - if (row === undefined) return DEFAULT_ACCESS_POLICY; - return { - selfSignup: row.selfSignup, - allowedDomains: parseAllowedDomainsColumn(row.allowedDomains), - tenancyCreation: row.tenancyCreation, - }; -} - -/** The lowercased domain half of an email, or undefined for anything - * that isn't shaped like `local@domain`. */ -export function domainOf(email: string): string | undefined { - const trimmed = email.trim().toLowerCase(); - const at = trimmed.lastIndexOf("@"); - if (at <= 0 || at === trimmed.length - 1) return undefined; - const domain = trimmed.slice(at + 1); - return domain.length > 0 ? domain : undefined; -} - -/** An empty allowlist means "any domain". */ -export function domainAllowed( - domain: string, - allowedDomains: readonly string[], -): boolean { - if (allowedDomains.length === 0) return true; - const needle = domain.toLowerCase(); - return allowedDomains.some((d) => d.toLowerCase() === needle); -} - -export type SignupGateReason = - | "invalid_email" - | "email_unverified" - | "signup_closed" - | "domain_not_allowed" - | "policy_open" - | "policy_domain_match"; - -export type SignupGateResult = { - readonly allowed: boolean; - readonly reason: SignupGateReason; -}; - -export type SignupGateArgs = { - /** The tenant's own policy row, resolved through `resolveAccessPolicy` - * — pass `undefined` only when no row exists at all, in which case - * the closed defaults apply. */ - readonly policy: AccessPolicy | undefined; - readonly email: string; - /** better-auth is configured without `requireEmailVerification`, so - * an unverified address can claim any domain. Every email-trust - * decision this gate makes requires `emailVerified` unless - * `allowUnverifiedEmails` opts out (dev/test only). Checked before - * the policy is ever consulted, so no policy can allow an - * unverified email through. */ - readonly emailVerified: boolean; - readonly allowUnverifiedEmails: boolean; -}; - -/** - * The one signup-gate evaluation function. The tenant's policy row - * decides outright; with no row yet the closed defaults apply, so a - * hub without an explicit open row never self-grants membership. - */ -export function evaluateSignupGate(args: SignupGateArgs): SignupGateResult { - const domain = domainOf(args.email); - if (domain === undefined) return { allowed: false, reason: "invalid_email" }; - - if (!args.emailVerified && !args.allowUnverifiedEmails) { - return { allowed: false, reason: "email_unverified" }; - } - - const policy = args.policy ?? DEFAULT_ACCESS_POLICY; - if (policy.selfSignup === "off") { - return { allowed: false, reason: "signup_closed" }; - } - if (policy.selfSignup === "open") { - return { allowed: true, reason: "policy_open" }; - } - return domainAllowed(domain, policy.allowedDomains) - ? { allowed: true, reason: "policy_domain_match" } - : { allowed: false, reason: "domain_not_allowed" }; -} - -/** - * Whether a principal holding these role names may create a - * sub-workbench (a child tenant) under the tenant this policy governs. - * `roleNames` are native role names ("owner", "admin", ...) — this - * function has no opinion on how they were resolved. - */ -export function canCreateTenancy( - policy: AccessPolicy, - roleNames: readonly string[], -): boolean { - const names = new Set(roleNames.map((n) => n.toLowerCase())); - switch (policy.tenancyCreation) { - case "owners": - return names.has("owner"); - case "owners-admins": - return names.has("owner") || names.has("admin"); - case "none": - return false; - } -} diff --git a/packages/access-policy/src/routes.ts b/packages/access-policy/src/routes.ts deleted file mode 100644 index b1a92926dd..0000000000 --- a/packages/access-policy/src/routes.ts +++ /dev/null @@ -1,134 +0,0 @@ -// Tenant-scoped HTTP surface: reading/editing this tenant's own policy -// row, and the one gated tenant-creation surface — -// `POST .../child-tenants` — that checks `tenancyCreation` against the -// caller's native roles (read back through the native principal-detail -// route) before ever calling `POST /api/tenants` itself. Every native -// call goes through the injected `ApiCall`, the same self-HTTP-call -// seam `@workbench/onboarding` already uses — nothing here -// reimplements tenant creation or role resolution. -import { Hono } from "hono"; -import { type } from "arktype"; -import type { RequireGrant, TenantEnv } from "@intx/hub-api"; -import { makeErrorEnvelope, reportError } from "@corbits/error-sink"; -import { cookiesFromHeader, type ApiCall } from "@corbits/hub-api-client"; - -import { canCreateTenancy } from "./policy"; -import type { AccessPolicyStore } from "./store"; -import { UpdateAccessPolicy } from "./types"; - -const CreateChildTenant = type({ - name: "string > 0", - slug: "string > 0", -}); - -export type CreateAccessPolicyRoutesDeps = { - store: AccessPolicyStore; - requireGrant: RequireGrant; - api: ApiCall; -}; - -export function createAccessPolicyRoutes( - deps: CreateAccessPolicyRoutesDeps, -): Hono { - const app = new Hono(); - - app.get("/", deps.requireGrant("access-policy:*", "read"), async (c) => { - const tenant = c.get("tenant"); - const policy = await deps.store.getPolicy(tenant.id); - return c.json(policy); - }); - - app.patch("/", deps.requireGrant("access-policy:*", "manage"), async (c) => { - const tenant = c.get("tenant"); - const raw: unknown = await c.req.json().catch(() => undefined); - const patch = UpdateAccessPolicy(raw); - if (patch instanceof type.errors) { - return c.json( - makeErrorEnvelope({ - code: "bad_request", - userMessage: `invalid policy: ${patch.summary}`, - }), - 400, - ); - } - const updated = await deps.store.upsertPolicy(tenant.id, patch); - return c.json(updated); - }); - - // The gated tenant-creation surface: any signed-in member of this - // tenant may attempt it, but only one whose native roles satisfy this - // tenant's own `tenancyCreation` mode ever reaches `POST /api/tenants`. - app.post("/child-tenants", async (c) => { - const tenant = c.get("tenant"); - const principal = c.get("principal"); - const raw: unknown = await c.req.json().catch(() => undefined); - const body = CreateChildTenant(raw); - if (body instanceof type.errors) { - return c.json( - makeErrorEnvelope({ - code: "bad_request", - userMessage: `invalid tenant: ${body.summary}`, - }), - 400, - ); - } - - const cookies = cookiesFromHeader(c.req.header("cookie")); - const policy = await deps.store.getPolicy(tenant.id); - - const principalResponse = await deps.api( - "GET", - `/api/tenants/${tenant.id}/principals/${principal.id}`, - undefined, - cookies, - ); - if (principalResponse.status !== 200) { - const userMessage = "Could not resolve your roles on this workbench."; - const refId = reportError( - new Error(`principal lookup returned ${principalResponse.status}`), - { - operation: "accessPolicy.childTenant.roleLookup", - tenantId: tenant.id, - extra: { status: principalResponse.status }, - }, - ); - return c.json( - makeErrorEnvelope({ - code: "role_lookup_failed", - userMessage, - refId, - }), - 502, - ); - } - const roleData = principalResponse.data as { - roles?: { name?: unknown }[]; - }; - const roleNames = (roleData.roles ?? []) - .map((r) => r.name) - .filter((n): n is string => typeof n === "string"); - - if (!canCreateTenancy(policy, roleNames)) { - return c.json( - makeErrorEnvelope({ - code: "tenancy_creation_forbidden", - userMessage: - "This workbench's policy doesn't allow you to create a sub-workbench here.", - }), - 403, - ); - } - - const created = await deps.api( - "POST", - "/api/tenants", - { name: body.name, slug: body.slug, parentId: tenant.id }, - cookies, - ); - if (created.status === 201) return c.json(created.data, 201); - if (created.status === 409) return c.json(created.data, 409); - return c.json(created.data, 500); - }); - - return app; -} diff --git a/packages/access-policy/src/schema.ts b/packages/access-policy/src/schema.ts deleted file mode 100644 index 952ab49054..0000000000 --- a/packages/access-policy/src/schema.ts +++ /dev/null @@ -1,35 +0,0 @@ -// The product table `@workbench/access-policy` owns: one closed-by- -// default policy row per tenant (`policy`). It lives in its own -// `access_policy` Postgres schema, never `public` — see -// docs/package-migrations.md. Tenancy, principals, roles, and grants -// stay entirely native (vendor/intx/db); this package never declares -// its own copy of any of them, it only opines on top. -import { pgSchema, text, timestamp } from "drizzle-orm/pg-core"; - -export const accessPolicySchema = pgSchema("access_policy"); - -export const policy = accessPolicySchema.table("policy", { - tenantId: text("tenant_id").primaryKey(), - selfSignup: text("self_signup", { - enum: ["off", "allowed-domains", "open"], - }) - .notNull() - .default("off"), - // Stored as JSON text rather than a native array column so the - // literal-SQL migration stays a single portable CREATE TABLE; parsed - // through the arktype schema in ./types.ts at every read. - allowedDomains: text("allowed_domains").notNull().default("[]"), - tenancyCreation: text("tenancy_creation", { - enum: ["owners", "owners-admins", "none"], - }) - .notNull() - .default("owners"), - createdAt: timestamp("created_at", { withTimezone: true }) - .notNull() - .defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }) - .notNull() - .defaultNow(), -}); - -export type PolicyRow = typeof policy.$inferSelect; diff --git a/packages/access-policy/src/store.ts b/packages/access-policy/src/store.ts deleted file mode 100644 index 1ba63f4ee5..0000000000 --- a/packages/access-policy/src/store.ts +++ /dev/null @@ -1,135 +0,0 @@ -// Postgres-backed persistence for this package's policy table, plus an -// in-memory fake with the same shape for tests that don't need a real -// database. -import { eq } from "drizzle-orm"; -import type { PostgresJsDatabase } from "drizzle-orm/postgres-js"; - -import { resolveAccessPolicy, serializeAllowedDomains } from "./policy"; -import { policy } from "./schema"; -import { - DEFAULT_ACCESS_POLICY, - type AccessPolicy, - type UpdateAccessPolicy, -} from "./types"; - -export interface AccessPolicyStore { - getPolicy(tenantId: string): Promise; - /** Whether an explicit policy row exists for this tenant — distinct - * from `getPolicy`, which always returns an effective policy - * (closed defaults when no row exists). The signup gate needs this - * distinction to know whether the env-flag bootstrap still applies - * or whether an explicit row has taken over. */ - hasPolicyRow(tenantId: string): Promise; - upsertPolicy( - tenantId: string, - patch: UpdateAccessPolicy, - ): Promise; -} - -export function createDrizzleAccessPolicyStore< - TSchema extends Record, ->(db: PostgresJsDatabase): AccessPolicyStore { - return { - async getPolicy(tenantId) { - const [row] = await db - .select() - .from(policy) - .where(eq(policy.tenantId, tenantId)); - return resolveAccessPolicy(row); - }, - - async hasPolicyRow(tenantId) { - const [row] = await db - .select({ tenantId: policy.tenantId }) - .from(policy) - .where(eq(policy.tenantId, tenantId)); - return row !== undefined; - }, - - // Read-modify-write under a transaction with a row lock rather than - // an optimistic version-stamp check: two transactions starting in - // the same wall-clock tick could still both pass a version check, - // which is exactly the lost-update bug this closes. - // - // Because this method's row may not exist yet (it is an upsert), - // `SELECT ... FOR UPDATE` alone has nothing to lock for a brand-new - // tenant. The `INSERT ... ON CONFLICT DO NOTHING` below guarantees - // a row first: two concurrent first-writes for the same tenant - // serialize on that insert's unique-index conflict — the loser - // blocks until the winner's transaction commits, then no-ops and - // its own subsequent `SELECT ... FOR UPDATE` sees the winner's - // committed row rather than racing it. - async upsertPolicy(tenantId, patch) { - return db.transaction(async (tx) => { - const now = new Date(); - await tx - .insert(policy) - .values({ - tenantId, - selfSignup: DEFAULT_ACCESS_POLICY.selfSignup, - allowedDomains: serializeAllowedDomains( - DEFAULT_ACCESS_POLICY.allowedDomains, - ), - tenancyCreation: DEFAULT_ACCESS_POLICY.tenancyCreation, - createdAt: now, - updatedAt: now, - }) - .onConflictDoNothing({ target: policy.tenantId }); - - const [current] = await tx - .select() - .from(policy) - .where(eq(policy.tenantId, tenantId)) - .for("update"); - if (current === undefined) { - throw new Error( - `upsertPolicy: no access_policy.policy row for tenant ${tenantId} after ensuring one exists`, - ); - } - const existing = resolveAccessPolicy(current); - const next: AccessPolicy = { - selfSignup: patch.selfSignup ?? existing.selfSignup, - allowedDomains: patch.allowedDomains ?? existing.allowedDomains, - tenancyCreation: patch.tenancyCreation ?? existing.tenancyCreation, - }; - await tx - .update(policy) - .set({ - selfSignup: next.selfSignup, - allowedDomains: serializeAllowedDomains(next.allowedDomains), - tenancyCreation: next.tenancyCreation, - updatedAt: new Date(), - }) - .where(eq(policy.tenantId, tenantId)); - return next; - }); - }, - }; -} - -/** The fake this package's own route/gate tests drive through — no - * Postgres required, same matching semantics as the real store. */ -export function createInMemoryAccessPolicyStore(): AccessPolicyStore { - const policies = new Map(); - - return { - async getPolicy(tenantId) { - return policies.get(tenantId) ?? DEFAULT_ACCESS_POLICY; - }, - - async hasPolicyRow(tenantId) { - return policies.has(tenantId); - }, - - async upsertPolicy(tenantId, patch) { - const existing = policies.get(tenantId) ?? DEFAULT_ACCESS_POLICY; - const next: AccessPolicy = { - selfSignup: patch.selfSignup ?? existing.selfSignup, - allowedDomains: patch.allowedDomains ?? existing.allowedDomains, - tenancyCreation: patch.tenancyCreation ?? existing.tenancyCreation, - }; - policies.set(tenantId, next); - return next; - }, - }; -} diff --git a/packages/access-policy/src/types.ts b/packages/access-policy/src/types.ts deleted file mode 100644 index 3386b9615c..0000000000 --- a/packages/access-policy/src/types.ts +++ /dev/null @@ -1,45 +0,0 @@ -// Trust-boundary shapes for the access policy this package owns. -// Anything that crosses a wire (a route body, a raw DB column, an env -// value) is parsed through one of these before the rest of the package -// touches it — never cast. -import { type } from "arktype"; - -export const SelfSignupMode = type("'off' | 'allowed-domains' | 'open'"); -export type SelfSignupMode = typeof SelfSignupMode.infer; - -export const TenancyCreationMode = type("'owners' | 'owners-admins' | 'none'"); -export type TenancyCreationMode = typeof TenancyCreationMode.infer; - -export const AllowedDomains = type("string[]"); - -export const AccessPolicy = type({ - selfSignup: SelfSignupMode, - allowedDomains: AllowedDomains, - tenancyCreation: TenancyCreationMode, -}); -export type AccessPolicy = typeof AccessPolicy.infer; - -/** Closed-by-default: an absent policy row is exactly this — signup - * off, sub-workbench creation restricted to owners. */ -export const DEFAULT_ACCESS_POLICY: AccessPolicy = { - selfSignup: "off", - allowedDomains: [], - tenancyCreation: "owners", -}; - -export const UpdateAccessPolicy = type({ - "selfSignup?": SelfSignupMode, - "allowedDomains?": AllowedDomains, - "tenancyCreation?": TenancyCreationMode, -}); -export type UpdateAccessPolicy = typeof UpdateAccessPolicy.infer; - -/** A row as read out of `access_policy.policy`, with `allowedDomains` - * still the raw JSON-text column — parsed via `parseAllowedDomainsColumn` - * in ./policy.ts before it becomes an `AccessPolicy`. */ -export type PolicyRowShape = { - readonly tenantId: string; - readonly selfSignup: SelfSignupMode; - readonly allowedDomains: string; - readonly tenancyCreation: TenancyCreationMode; -}; diff --git a/packages/access-policy/test/store.drizzle.test.ts b/packages/access-policy/test/store.drizzle.test.ts deleted file mode 100644 index ff1a5cdfb4..0000000000 --- a/packages/access-policy/test/store.drizzle.test.ts +++ /dev/null @@ -1,229 +0,0 @@ -// DB-gated: skipped when no DATABASE_URL is reachable (a fresh checkout -// still runs the unit gates), mirroring `@workbench/onboarding`'s own -// `pending-seed-store.drizzle.test.ts`. Runs against its own scratch -// database, never the developer's or the walking-skeleton suite's. -// -// Proves what the in-memory fake cannot: that -// `createDrizzleAccessPolicyStore` actually persists across separate -// connections, that an upsert replaces rather than duplicates the -// single policy row per tenant, and that the real migrations produce a -// schema the store's queries actually run against. -import { afterAll, beforeAll, expect, test } from "bun:test"; -import { drizzle } from "drizzle-orm/postgres-js"; -import postgres from "postgres"; - -import { e2eDatabaseUrl } from "../../../scripts/e2e/database-url"; -import { applyAccessPolicyMigrations } from "../src/migrations"; -import { createDrizzleAccessPolicyStore } from "../src/store"; -import { dbGate } from "../../../scripts/e2e/db-gate"; - -function scratchUrlFor(e2eUrl: string): string { - const url = new URL(e2eUrl); - const database = url.pathname.replace(/^\//, ""); - url.pathname = `/${database}_access_policy_store_test`; - return url.toString(); -} - -const databaseUrl = e2eDatabaseUrl(); -const describeIfDb = dbGate(databaseUrl, import.meta.path); - -describeIfDb("createDrizzleAccessPolicyStore", () => { - const scratchUrl = scratchUrlFor( - databaseUrl ?? "postgres://localhost:5432/unused", - ); - const scratchDatabase = new URL(scratchUrl).pathname.replace(/^\//, ""); - - beforeAll(async () => { - const maintenanceUrl = new URL(scratchUrl); - maintenanceUrl.pathname = "/postgres"; - const maintenance = postgres(maintenanceUrl.toString(), { - max: 1, - onnotice: () => undefined, - }); - try { - await maintenance.unsafe(`DROP DATABASE IF EXISTS "${scratchDatabase}"`); - await maintenance.unsafe(`CREATE DATABASE "${scratchDatabase}"`); - } finally { - await maintenance.end(); - } - await applyAccessPolicyMigrations(scratchUrl); - }, 20000); - - afterAll(async () => { - const maintenanceUrl = new URL(scratchUrl); - maintenanceUrl.pathname = "/postgres"; - const maintenance = postgres(maintenanceUrl.toString(), { - max: 1, - onnotice: () => undefined, - }); - try { - await maintenance.unsafe(`DROP DATABASE IF EXISTS "${scratchDatabase}"`); - } finally { - await maintenance.end(); - } - }, 20000); - - test("getPolicy on a tenant with no row returns closed defaults", async () => { - const sql = postgres(scratchUrl, { max: 1 }); - try { - const store = createDrizzleAccessPolicyStore(drizzle(sql)); - const policy = await store.getPolicy("tnt_none"); - expect(policy).toEqual({ - selfSignup: "off", - allowedDomains: [], - tenancyCreation: "owners", - }); - expect(await store.hasPolicyRow("tnt_none")).toBe(false); - } finally { - await sql.end(); - } - }); - - test("upsertPolicy inserts, then updates the same row rather than duplicating it", async () => { - const sql = postgres(scratchUrl, { max: 1 }); - try { - const store = createDrizzleAccessPolicyStore(drizzle(sql)); - await store.upsertPolicy("tnt_upsert", { - selfSignup: "allowed-domains", - allowedDomains: ["acme.example"], - }); - await store.upsertPolicy("tnt_upsert", { tenancyCreation: "none" }); - - const rows = - await sql`select self_signup, allowed_domains, tenancy_creation from access_policy.policy where tenant_id = 'tnt_upsert'`; - expect(rows).toHaveLength(1); - expect(rows[0]?.["self_signup"]).toBe("allowed-domains"); - expect(rows[0]?.["tenancy_creation"]).toBe("none"); - expect(JSON.parse(String(rows[0]?.["allowed_domains"]))).toEqual([ - "acme.example", - ]); - - const policy = await store.getPolicy("tnt_upsert"); - expect(policy).toEqual({ - selfSignup: "allowed-domains", - allowedDomains: ["acme.example"], - tenancyCreation: "none", - }); - expect(await store.hasPolicyRow("tnt_upsert")).toBe(true); - } finally { - await sql.end(); - } - }); - - test("persists across separate connections", async () => { - const writeSql = postgres(scratchUrl, { max: 1 }); - try { - const writeStore = createDrizzleAccessPolicyStore(drizzle(writeSql)); - await writeStore.upsertPolicy("tnt_restart", { selfSignup: "open" }); - } finally { - await writeSql.end(); - } - - const readSql = postgres(scratchUrl, { max: 1 }); - try { - const readStore = createDrizzleAccessPolicyStore(drizzle(readSql)); - const policy = await readStore.getPolicy("tnt_restart"); - expect(policy.selfSignup).toBe("open"); - } finally { - await readSql.end(); - } - }); - - test("upsertPolicy is atomic: two concurrent patches to different fields on an existing row both land, neither reverts the other", async () => { - const setupSql = postgres(scratchUrl, { max: 1 }); - try { - const store = createDrizzleAccessPolicyStore(drizzle(setupSql)); - await store.upsertPolicy("tnt_race_existing", { - selfSignup: "off", - allowedDomains: [], - tenancyCreation: "owners", - }); - } finally { - await setupSql.end(); - } - - // A plain `Promise.all` of two real calls does not reliably force - // the worst-case interleaving on a fast local connection: one - // call's whole read-modify-write often finishes before the other's - // read even starts, so the two never actually overlap. Instead, a - // third connection takes the row's lock first and holds it open - // while both real `upsertPolicy` calls start and queue up behind - // it — releasing it then guarantees both calls' reads had to - // happen without seeing the other's write yet, exactly the - // interleaving that silently reverted one admin's change. - const holderSql = postgres(scratchUrl, { max: 1 }); - const sqlA = postgres(scratchUrl, { max: 1 }); - const sqlB = postgres(scratchUrl, { max: 1 }); - try { - const storeA = createDrizzleAccessPolicyStore(drizzle(sqlA)); - const storeB = createDrizzleAccessPolicyStore(drizzle(sqlB)); - - let holderReady: () => void = () => undefined; - const holderHasLock = new Promise((resolve) => { - holderReady = resolve; - }); - let releaseHolder: () => void = () => undefined; - const releaseSignal = new Promise((resolve) => { - releaseHolder = resolve; - }); - const holderTx = holderSql.begin(async (tx) => { - await tx`select * from access_policy.policy where tenant_id = 'tnt_race_existing' for update`; - holderReady(); - await releaseSignal; - }); - - await holderHasLock; - - const racers = Promise.all([ - storeA.upsertPolicy("tnt_race_existing", { selfSignup: "open" }), - storeB.upsertPolicy("tnt_race_existing", { - allowedDomains: ["acme.example"], - }), - ]); - // Give both calls time to actually issue their row-locking read - // and start queuing behind the holder before it releases. - await new Promise((resolve) => setTimeout(resolve, 100)); - - releaseHolder(); - await holderTx; - await racers; - - const policy = await storeA.getPolicy("tnt_race_existing"); - expect(policy.selfSignup).toBe("open"); - expect(policy.allowedDomains).toEqual(["acme.example"]); - expect(policy.tenancyCreation).toBe("owners"); - } finally { - await holderSql.end(); - await sqlA.end(); - await sqlB.end(); - } - }); - - test("upsertPolicy is atomic: two concurrent first-writes for a brand-new tenant both land, neither reverts the other", async () => { - const sql = postgres(scratchUrl, { max: 5 }); - try { - const store = createDrizzleAccessPolicyStore(drizzle(sql)); - - // No row exists yet for this tenant, so both calls race the - // create path too — the ensure-row-then-lock step inside - // `upsertPolicy` has to serialize this case as well, not only - // the existing-row case above. - await Promise.all([ - store.upsertPolicy("tnt_race_new", { selfSignup: "open" }), - store.upsertPolicy("tnt_race_new", { - allowedDomains: ["acme.example"], - }), - ]); - - const policy = await store.getPolicy("tnt_race_new"); - expect(policy.selfSignup).toBe("open"); - expect(policy.allowedDomains).toEqual(["acme.example"]); - - const rows = - await sql`select count(*)::int as count from access_policy.policy where tenant_id = 'tnt_race_new'`; - expect(rows[0]?.["count"]).toBe(1); - } finally { - await sql.end(); - } - }); -}); diff --git a/packages/access-policy/tsconfig.json b/packages/access-policy/tsconfig.json deleted file mode 100644 index 9f1ba34128..0000000000 --- a/packages/access-policy/tsconfig.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "extends": "./tsconfig.src.json", - "compilerOptions": { - "composite": false, - "noEmit": true, - "disableSourceOfProjectReferenceRedirect": true, - "declaration": false, - "declarationMap": false, - "emitDeclarationOnly": false, - "tsBuildInfoFile": "tsconfig.tsbuildinfo", - "rootDir": "../.." - }, - "include": ["src", "test"], - "exclude": [], - "references": [ - { - "path": "../../vendor/intx/hub-api/tsconfig.src.json" - }, - { - "path": "../error-sink/tsconfig.src.json" - }, - { - "path": "../hub-api-client/tsconfig.src.json" - }, - { - "path": "../migration-runner/tsconfig.src.json" - } - ] -} diff --git a/packages/access-policy/tsconfig.src.json b/packages/access-policy/tsconfig.src.json deleted file mode 100644 index 8e7a2ec4c6..0000000000 --- a/packages/access-policy/tsconfig.src.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "include": ["src", "package.json", "src/**/*.json"], - "exclude": ["src/**/*.test.ts", "src/**/*.test.tsx"], - "compilerOptions": { - "types": ["bun"], - "noEmit": true, - "composite": true, - "emitDeclarationOnly": true, - "outDir": "dist", - "tsBuildInfoFile": "dist/tsconfig.tsbuildinfo" - }, - "references": [ - { - "path": "../../vendor/intx/hub-api/tsconfig.src.json" - }, - { - "path": "../error-sink/tsconfig.src.json" - }, - { - "path": "../hub-api-client/tsconfig.src.json" - }, - { - "path": "../migration-runner/tsconfig.src.json" - } - ] -} diff --git a/packages/onboarding/test/genesis.test.ts b/packages/onboarding/test/genesis.test.ts index a88d563bcb..e8d3889d7a 100644 --- a/packages/onboarding/test/genesis.test.ts +++ b/packages/onboarding/test/genesis.test.ts @@ -1,6 +1,5 @@ import { describe, expect, test } from "bun:test"; import type { ApiCall } from "@corbits/hub-api-client"; -import type { AccessPolicyStore } from "@workbench/access-policy"; import { genesisOrJoinHubSignup, ProvisionError, @@ -18,63 +17,6 @@ function collector() { return { lines, log: (line: string) => lines.push(line) }; } -/** An ApiCall that lets a genesis mint succeed: the first principals - * read is empty, the create answers 201, and every later principals - * read reports membership in the minted tenant. */ -function genesisApi(): ApiCall { - let principalsCalls = 0; - return async (method, path) => { - if (method === "GET" && path === "/api/me/principals") { - principalsCalls += 1; - if (principalsCalls === 1) return principalsResponse([]); - return principalsResponse([ - { - principalId: PRINCIPAL_ID, - tenantId: TENANT_ID, - tenantSlug: TENANT_SLUG, - }, - ]); - } - if (method === "POST" && path === "/api/tenants") { - return { - status: 201, - data: { - id: TENANT_ID, - name: "Acme", - slug: TENANT_SLUG, - domain: `${TENANT_SLUG}.localhost`, - createdAt: "2026-01-01T00:00:00.000Z", - updatedAt: "2026-01-01T00:00:00.000Z", - }, - cookies: [], - }; - } - throw new Error(`unexpected call: ${method} ${path}`); - }; -} - -function accessPolicy( - overrides?: Partial< - Pick< - NonNullable, - "allowUnverifiedEmails" - > - >, -): NonNullable { - return { - // No operator tenant is threaded here, so the store is never read — - // a throwing store proves that. With no policy row the closed - // defaults apply. - store: { - getPolicy: async () => { - throw new Error("signup gate must evaluate rowless here"); - }, - } as unknown as AccessPolicyStore, - allowUnverifiedEmails: false, - ...overrides, - }; -} - function tenancy(state: { users?: number; tenants?: number; @@ -123,7 +65,6 @@ function argsFor(partial: { tenancy: HubSignupTenancy; displayName?: string; log?: (line: string) => void; - accessPolicy?: NonNullable; userEmailVerified?: boolean; userEmail?: string; }): GenesisOrJoinArgs { @@ -137,8 +78,6 @@ function argsFor(partial: { tenancy: partial.tenancy, log: partial.log ?? collector().log, }; - if (partial.accessPolicy !== undefined) - args.accessPolicy = partial.accessPolicy; if (partial.displayName !== undefined) args.displayName = partial.displayName; return args; } @@ -218,73 +157,6 @@ describe("genesisOrJoinHubSignup", () => { ]); }); - test("a closed hub rejects join with signup_not_allowed and never adds a member", async () => { - const joins: { tenantId: string; userId: string; roleName: string }[] = []; - const api: ApiCall = async (method, path) => { - if (method === "GET" && path === "/api/me/principals") { - return principalsResponse([]); - } - throw new Error(`unexpected call: ${method} ${path}`); - }; - - await expect( - genesisOrJoinHubSignup( - argsFor({ - api, - tenancy: tenancy({ - users: 2, - tenants: 1, - root: { id: TENANT_ID, slug: TENANT_SLUG }, - joins, - }), - displayName: "Bob", - accessPolicy: accessPolicy(), - }), - ), - ).rejects.toMatchObject({ - name: "ProvisionError", - code: "signup_not_allowed", - errorKind: "permanent", - }); - expect(joins).toEqual([]); - }); - - test("genesis rejects an unverified email unless allowUnverifiedEmails", async () => { - const probeOnly: ApiCall = async (method, path) => { - if (method === "GET" && path === "/api/me/principals") { - return principalsResponse([]); - } - throw new Error(`unexpected call: ${method} ${path}`); - }; - - await expect( - genesisOrJoinHubSignup( - argsFor({ - api: probeOnly, - tenancy: tenancy({ users: 1, tenants: 0, root: null }), - displayName: "Acme", - userEmailVerified: false, - accessPolicy: accessPolicy(), - }), - ), - ).rejects.toMatchObject({ - name: "ProvisionError", - code: "signup_not_allowed", - }); - - // The dev/test escape hatch still admits the genesis caller. - const result = await genesisOrJoinHubSignup( - argsFor({ - api: genesisApi(), - tenancy: tenancy({ users: 1, tenants: 0, root: null }), - displayName: "Acme", - userEmailVerified: false, - accessPolicy: accessPolicy({ allowUnverifiedEmails: true }), - }), - ); - expect(result.kind).toBe("genesis"); - }); - test("countUsers > 1 with zero tenants still lets the caller genesis", async () => { let tenantCreates = 0; const joins: { tenantId: string; userId: string; roleName: string }[] = []; @@ -497,20 +369,6 @@ describe("genesisOrJoinHubSignup", () => { code: "slug_conflict_no_principal", }); }); - - test("genesis on an empty hub waives signup_closed but still evaluates the gate", async () => { - // No policy row: the empty-hub exception waives signup_closed, so - // the first verified user still mints the root. - const result = await genesisOrJoinHubSignup( - argsFor({ - api: genesisApi(), - tenancy: tenancy({ users: 1, tenants: 0, root: null }), - displayName: "Acme", - accessPolicy: accessPolicy(), - }), - ); - expect(result.kind).toBe("genesis"); - }); }); test("ProvisionError is constructible for route mapping", () => { diff --git a/packages/settings-ui/src/access-policy-api.ts b/packages/settings-ui/src/access-policy-api.ts deleted file mode 100644 index b162f49912..0000000000 --- a/packages/settings-ui/src/access-policy-api.ts +++ /dev/null @@ -1,60 +0,0 @@ -// The People section's seam to `@workbench/access-policy`'s tenant-scoped -// routes (see that package's `src/routes.ts`, mounted at -// `/api/tenants/:tenantId/access-policy`). Every response is parsed with an -// arktype schema at the boundary, the same convention `./tenancy-api.ts` -// already holds for the native routes. - -import { type } from "arktype"; - -import { apiRequest, type Validator } from "./api-request"; - -export const AccessPolicy = type({ - selfSignup: "'off' | 'allowed-domains' | 'open'", - allowedDomains: "string[]", - tenancyCreation: "'owners' | 'owners-admins' | 'none'", -}); -export type AccessPolicy = typeof AccessPolicy.infer; - -export type UpdateAccessPolicy = { - readonly selfSignup?: AccessPolicy["selfSignup"]; - readonly allowedDomains?: readonly string[]; - readonly tenancyCreation?: AccessPolicy["tenancyCreation"]; -}; - -export class AccessPolicyApiError extends Error { - constructor( - message: string, - readonly status?: number, - ) { - super(message); - } -} - -function request( - path: string, - schema: Validator, - verb: string, - init?: RequestInit, -): Promise { - return apiRequest(path, schema, verb, AccessPolicyApiError, init); -} - -export function getAccessPolicy(tenantId: string): Promise { - return request( - `/api/tenants/${tenantId}/access-policy`, - AccessPolicy, - "loading who can join", - ); -} - -export function updateAccessPolicy( - tenantId: string, - patch: UpdateAccessPolicy, -): Promise { - return request( - `/api/tenants/${tenantId}/access-policy`, - AccessPolicy, - "saving who can join", - { method: "PATCH", body: JSON.stringify(patch) }, - ); -} diff --git a/packages/settings-ui/src/access-policy.tsx b/packages/settings-ui/src/access-policy.tsx deleted file mode 100644 index 3e0a9a98e3..0000000000 --- a/packages/settings-ui/src/access-policy.tsx +++ /dev/null @@ -1,213 +0,0 @@ -// The "Who can join" block for the People section: a plain-language editor -// over `@workbench/access-policy`'s per-tenant policy row (self-signup mode, -// allowed email domains, who may create a sub-workbench here). Closed by -// default — an absent row reads exactly like an explicit "off" / "owners -// only" row; see that package's `resolveAccessPolicy`. - -import { Badge, Button, Input } from "@corbits/react-ui"; -import { X } from "@corbits/icons"; -import { useCallback, useEffect, useState } from "react"; - -import type { APIQuery } from "@corbits/api-query"; -import { - QueryView, - UnauthenticatedError, - describeQueryError, -} from "@corbits/api-query"; -import { - getAccessPolicy, - updateAccessPolicy, - type AccessPolicy, -} from "./access-policy-api"; -import { SETTINGS_STRINGS } from "./strings"; - -export function AccessPolicyBlock({ tenantId }: { readonly tenantId: string }) { - const [query, setQuery] = useState>({ - kind: "loading", - }); - const [saving, setSaving] = useState(false); - const [saveError, setSaveError] = useState(null); - - const load = useCallback(() => { - let cancelled = false; - setQuery({ kind: "loading" }); - getAccessPolicy(tenantId) - .then((policy) => { - if (!cancelled) setQuery({ kind: "ready", data: policy }); - }) - .catch((cause: unknown) => { - if (cancelled) return; - if (cause instanceof UnauthenticatedError) { - setQuery({ kind: "unauthenticated" }); - return; - } - setQuery({ - kind: "error", - message: describeQueryError(cause), - retry: load, - }); - }); - return () => { - cancelled = true; - }; - }, [tenantId]); - - useEffect(() => load(), [load]); - - function save(patch: Partial) { - setSaving(true); - setSaveError(null); - updateAccessPolicy(tenantId, patch) - .then((policy) => setQuery({ kind: "ready", data: policy })) - .catch(() => setSaveError(SETTINGS_STRINGS.accessPolicySaveError)) - .finally(() => setSaving(false)); - } - - return ( - - {(policy) => ( - - )} - - ); -} - -export function AccessPolicyEditor({ - policy, - saving, - error = null, - onChange, -}: { - readonly policy: AccessPolicy; - readonly saving: boolean; - readonly error?: string | null; - readonly onChange: (patch: Partial) => void; -}) { - const [domainDraft, setDomainDraft] = useState(""); - - function addDomain() { - const domain = domainDraft.trim().toLowerCase(); - if (domain.length === 0 || policy.allowedDomains.includes(domain)) { - setDomainDraft(""); - return; - } - onChange({ allowedDomains: [...policy.allowedDomains, domain] }); - setDomainDraft(""); - } - - function removeDomain(domain: string) { - onChange({ - allowedDomains: policy.allowedDomains.filter((d) => d !== domain), - }); - } - - return ( -
-

- {SETTINGS_STRINGS.accessPolicyHeading} - {saving && ( - {SETTINGS_STRINGS.accessPolicySaving} - )} -

- - - - {policy.selfSignup === "allowed-domains" && ( -
- {SETTINGS_STRINGS.accessPolicyDomainsLabel} - {policy.allowedDomains.length === 0 ? ( -

- {SETTINGS_STRINGS.accessPolicyDomainsEmptyHint} -

- ) : ( -
- {policy.allowedDomains.map((domain) => ( - - {domain} - - - ))} -
- )} -
- setDomainDraft(event.target.value)} - onKeyDown={(event) => { - if (event.key === "Enter") { - event.preventDefault(); - addDomain(); - } - }} - placeholder={SETTINGS_STRINGS.accessPolicyDomainsPlaceholder} - /> - -
-
- )} - - - - {error !== null && ( -

- {error} -

- )} -

{SETTINGS_STRINGS.accessPolicyNote}

-
- ); -} diff --git a/packages/settings-ui/test/access-policy-api.test.ts b/packages/settings-ui/test/access-policy-api.test.ts deleted file mode 100644 index f41598847d..0000000000 --- a/packages/settings-ui/test/access-policy-api.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -// Access-policy API client: stub global fetch, assert request + parse, and -// that a fallback error never leaks the raw route to a person. - -import { afterEach, describe, expect, test } from "bun:test"; - -import { - AccessPolicyApiError, - getAccessPolicy, - updateAccessPolicy, -} from "../src/access-policy-api"; - -const realFetch = globalThis.fetch; -afterEach(() => { - globalThis.fetch = realFetch; -}); - -const json = (body: unknown, status = 200) => - new Response(body === undefined ? null : JSON.stringify(body), { - status, - headers: { "content-type": "application/json" }, - }); - -const policy = { - selfSignup: "off" as const, - allowedDomains: [], - tenancyCreation: "owners" as const, -}; - -describe("getAccessPolicy", () => { - test("fetches the tenant's access policy", async () => { - let requestedPath = ""; - globalThis.fetch = (async (input: RequestInfo | URL) => { - requestedPath = String(input); - return json(policy); - }) as unknown as typeof fetch; - - const result = await getAccessPolicy("tnt_1"); - expect(requestedPath).toBe("/api/tenants/tnt_1/access-policy"); - expect(result).toEqual(policy); - }); - - test("prefers the server's envelope message on a non-2xx", async () => { - globalThis.fetch = (async () => - json( - { - error: { - code: "forbidden", - userMessage: "Not on this bench.", - refId: "ref_1", - }, - }, - 403, - )) as unknown as typeof fetch; - - await expect(getAccessPolicy("tnt_1")).rejects.toMatchObject({ - message: "Not on this bench.", - }); - }); - - test("falls back to a path-free message when there is no envelope", async () => { - globalThis.fetch = (async () => - json(undefined, 401)) as unknown as typeof fetch; - - try { - await getAccessPolicy("tnt_1"); - throw new Error("expected getAccessPolicy to reject"); - } catch (cause) { - expect(cause).toBeInstanceOf(AccessPolicyApiError); - expect((cause as Error).message).toBe( - "The server answered 401 while loading who can join.", - ); - expect((cause as Error).message).not.toContain("/api/"); - } - }); -}); - -describe("updateAccessPolicy", () => { - test("PATCHes the given fields", async () => { - let requestedBody: unknown; - globalThis.fetch = (async ( - _input: RequestInfo | URL, - init?: RequestInit, - ) => { - requestedBody = - init?.body !== undefined ? JSON.parse(String(init.body)) : undefined; - return json(policy); - }) as unknown as typeof fetch; - - await updateAccessPolicy("tnt_1", { selfSignup: "open" }); - expect(requestedBody).toEqual({ selfSignup: "open" }); - }); -}); From e2806c2ec2bf670ac42c71ce4970d83e7b594faa Mon Sep 17 00:00:00 2001 From: Sawyer Date: Thu, 17 Sep 2026 08:57:18 -0700 Subject: [PATCH 2/3] feat(hub-zero)!: delete @workbench/access-policy, cut signup gate (CL-8130) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The closed-signup/sub-workbench policy table, checkSignupGate, and the tenant-scoped access-policy routes had no native equivalent and were never mounted by any hub composition (T1/T2 already repointed first-login onto native setup-status and left onboarding's provisioning routes unwired). Per CL-7575's ruling, native POST /api/tenants grant-gating is the only signup/child-tenant gate now; there is nothing to keep as a Workbench-side gate, so the package is deleted rather than carried forward unwired. - packages/onboarding: drops its dependency on @workbench/access-policy; genesis/provision no longer thread an accessPolicy gate through first-login (it was already always-undefined in production). - scripts/db-setup.ts, scripts/checks/no-product-tenancy.ts, scripts/checks/report-error-baseline.txt, tsconfig.build.json: drop the deleted package from migration wiring, the schema-table allowlist, the report-error baseline, and the build project graph. - packages/settings-ui: deletes the "Who can join" People-section panel and its API client — it called /api/tenants/:tenantId/access-policy, a route no hub composition ever mounted. Overlaps with the in-flight PR #745 (CL-8085), which independently deletes packages/onboarding's genesis/provisioner and adds an empty-hub count read to access-policy; whichever of the two lands second will need a small rebase against the other. Claude-Session: https://claude.ai/code/session_01RweuMUskU2nvcFhdckc7EG --- apps/hub/src/hub-error-handler.ts | 5 +-- bun.lock | 41 +++++---------------- packages/onboarding/package.json | 1 - packages/onboarding/src/genesis.ts | 37 ------------------- packages/onboarding/src/provision.ts | 16 -------- packages/onboarding/src/routes.ts | 11 ------ packages/settings-ui/src/index.ts | 1 - packages/settings-ui/src/people-section.tsx | 2 - packages/settings-ui/src/strings.ts | 22 ----------- packages/settings-ui/src/styles.css | 9 ----- scripts/checks/no-product-tenancy.ts | 5 --- scripts/checks/report-error-baseline.txt | 1 - scripts/db-setup.ts | 2 - tsconfig.build.json | 3 -- 14 files changed, 11 insertions(+), 145 deletions(-) diff --git a/apps/hub/src/hub-error-handler.ts b/apps/hub/src/hub-error-handler.ts index 100fc4ed32..384004edc3 100644 --- a/apps/hub/src/hub-error-handler.ts +++ b/apps/hub/src/hub-error-handler.ts @@ -33,9 +33,8 @@ function hasGuidance(err: unknown): err is Error & { guidance: string } { * `app.onError` runs for routes mounted both inside and outside the * platform's tenant middleware, so `c`'s `Variables` aren't statically * known here; this borrows the same `TenantEnv` a tenant-scoped route - * types `c.get("tenant")` with (see `packages/access-policy/src/routes.ts`) - * to read `tenant.id` when a tenant-scoped route set it, without claiming - * the wider type up front. + * types `c.get("tenant")` with to read `tenant.id` when a tenant-scoped + * route set it, without claiming the wider type up front. */ function extractTenantId(c: Context): string | undefined { return (c as unknown as Context).var.tenant?.id; diff --git a/bun.lock b/bun.lock index d22351d39b..825881cc32 100644 --- a/bun.lock +++ b/bun.lock @@ -203,24 +203,6 @@ "vite": "^7.1.0", }, }, - "packages/access-policy": { - "name": "@workbench/access-policy", - "version": "0.0.1", - "dependencies": { - "@corbits/error-sink": "workspace:*", - "@corbits/hub-api-client": "workspace:*", - "@corbits/migration-runner": "workspace:*", - "@intx/hub-api": "workspace:*", - "arktype": "catalog:", - "drizzle-orm": "catalog:", - "hono": "catalog:", - "postgres": "catalog:", - }, - "devDependencies": { - "@types/bun": "catalog:", - "typescript": "catalog:", - }, - }, "packages/access-tools": { "name": "@corbits/access-tools", "version": "0.0.2", @@ -1097,7 +1079,6 @@ "@intx/hub-api": "workspace:*", "@intx/hub-common": "workspace:*", "@intx/types": "workspace:*", - "@workbench/access-policy": "workspace:*", "@workbench/templates": "workspace:*", "arktype": "catalog:", "drizzle-orm": "catalog:", @@ -2693,8 +2674,6 @@ "@vitejs/plugin-react": ["@vitejs/plugin-react@5.2.0", "", { "dependencies": { "@babel/core": "^7.29.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-rc.3", "@types/babel__core": "^7.20.5", "react-refresh": "^0.18.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-YmKkfhOAi3wsB1PhJq5Scj3GXMn3WvtQ/JC0xoopuHoXSdmtdStOpFrYaT1kie2YgFBcIe64ROzMYRjCrYOdYw=="], - "@workbench/access-policy": ["@workbench/access-policy@workspace:packages/access-policy"], - "@workbench/hub": ["@workbench/hub@workspace:apps/hub"], "@workbench/onboarding": ["@workbench/onboarding@workspace:packages/onboarding"], @@ -3519,17 +3498,11 @@ "@babel/helper-compilation-targets/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], - "@corbits/artifacts-hub/@corbits/artifacts": ["@corbits/artifacts@github:corbitsdev/corbits-artifacts#dc435ba", { "dependencies": { "@hono/standard-validator": "^0.2.3" }, "peerDependencies": { "@intx/hub-api": "^0.2.2", "@intx/types": "^0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.2", "hono": "^4.12.32", "hono-openapi": "^1.2.0", "postgres": "^3.4.9" } }, "corbitsdev-corbits-artifacts-dc435ba", "sha512-VksIyrrJY9nRke0QyjgqGdW3gLD73Bi3+CzpJWG+l8vRJKdUxVi7ms2Mp95NmJXr4TpVX6i1z4odufX/QBxnSw=="], - - "@corbits/chat-ui/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], - - "@corbits/context-menu/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], + "@corbits/inbox/@corbits/mailbox": ["@corbits/mailbox@github:corbitsdev/corbits-mailbox#118a2cd", { "dependencies": { "@hono/standard-validator": "0.2.3", "@standard-community/standard-json": "0.3.5", "@standard-community/standard-openapi": "0.2.9", "arktype": "2.1.29", "hono-openapi": "1.3.1" }, "peerDependencies": { "@intx/log": "^0.2.2", "@intx/mime": "^0.2.2", "@intx/types": "^0.2.2", "drizzle-orm": "^0.45.2", "hono": "^4.12.0", "postgres": "^3.4.0" } }, "corbitsdev-corbits-mailbox-118a2cd", "sha512-jVRl6/IH34JBPVUz7mqWyBm1w7uJxvYAI27gjw7zL1dFO4L+D0E5q/8b+mpwKMNOKKlGXU6UF5pdHnY8ilYx8g=="], "@corbits/mailbox/hono-openapi": ["hono-openapi@1.3.1", "", { "peerDependencies": { "@hono/standard-validator": "^0.2.0", "@standard-community/standard-json": "^0.3.5", "@standard-community/standard-openapi": "^0.2.9", "@types/json-schema": "^7.0.15", "hono": "^4.11.2", "openapi-types": "^12.1.3" }, "optionalPeers": ["@hono/standard-validator", "hono"] }, "sha512-NLVeVkhKZ3drmQNEIPac8HX8Y54uf1hJAgIM/7MfDsaeVVmB+QILWQxx5x3R3NvRHgedcbEbOCGY2uR7WQYyMw=="], - "@corbits/plugins-ui/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], - - "@corbits/settings-ui/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], + "@corbits/memory-hub/@corbits/memory": ["@corbits/memory@github:corbitsdev/corbits-memory#9e6f213", { "dependencies": { "@intx/agent": "0.2.2", "@intx/authz": "0.2.2", "@intx/hub-api": "0.2.2", "@intx/log": "0.2.2", "@intx/workflow": "0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.1", "hono": "^4.9.0", "hono-openapi": "^1.3.1", "postgres": "^3.4.7" } }, "corbitsdev-corbits-memory-9e6f213", "sha512-utnM4ZT2zmslcPXYWAAqxlDNLcpGsXFiTOtj8h7+OXnhCP0Eaw8yl25+yCTyHpvt3jcdeG4h5uFsSj7ou0BZCA=="], "@esbuild-kit/core-utils/esbuild": ["esbuild@0.18.20", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="], @@ -3551,11 +3524,11 @@ "@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.9", "", {}, "sha512-brTTsvFRt5C1gGHtPst/281UjPD5t9fBqbgoMPlVWy11ZLTPfu7HxK4ZYqO9H7o/yC9rSTCI85EaQ4OoY12qYw=="], - "@workbench/hub/@corbits/artifacts": ["@corbits/artifacts@github:corbitsdev/corbits-artifacts#dc435ba", { "dependencies": { "@hono/standard-validator": "^0.2.3" }, "peerDependencies": { "@intx/hub-api": "^0.2.2", "@intx/types": "^0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.2", "hono": "^4.12.32", "hono-openapi": "^1.2.0", "postgres": "^3.4.9" } }, "corbitsdev-corbits-artifacts-dc435ba", "sha512-VksIyrrJY9nRke0QyjgqGdW3gLD73Bi3+CzpJWG+l8vRJKdUxVi7ms2Mp95NmJXr4TpVX6i1z4odufX/QBxnSw=="], + "@workbench/hub/@corbits/mailbox": ["@corbits/mailbox@github:corbitsdev/corbits-mailbox#118a2cd", { "dependencies": { "@hono/standard-validator": "0.2.3", "@standard-community/standard-json": "0.3.5", "@standard-community/standard-openapi": "0.2.9", "arktype": "2.1.29", "hono-openapi": "1.3.1" }, "peerDependencies": { "@intx/log": "^0.2.2", "@intx/mime": "^0.2.2", "@intx/types": "^0.2.2", "drizzle-orm": "^0.45.2", "hono": "^4.12.0", "postgres": "^3.4.0" } }, "corbitsdev-corbits-mailbox-118a2cd", "sha512-jVRl6/IH34JBPVUz7mqWyBm1w7uJxvYAI27gjw7zL1dFO4L+D0E5q/8b+mpwKMNOKKlGXU6UF5pdHnY8ilYx8g=="], - "@workbench/sidecar/@corbits/oauth-core": ["@corbits/oauth-core@github:corbitsdev/corbits-oauth-core#e1e69e6", { "dependencies": { "arktype": "2.2.3" } }, "corbitsdev-corbits-oauth-core-e1e69e6", "sha512-wUrD73iVyk/Dtb4yRn3hCh6N8syfsEvAkRz4XYqT0FIB3sYDSMYEWHcDMJx9nq64my/HBOeN1J6PHIOtpjhtPg=="], + "@workbench/hub/@corbits/memory": ["@corbits/memory@github:corbitsdev/corbits-memory#9e6f213", { "dependencies": { "@intx/agent": "0.2.2", "@intx/authz": "0.2.2", "@intx/hub-api": "0.2.2", "@intx/log": "0.2.2", "@intx/workflow": "0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.1", "hono": "^4.9.0", "hono-openapi": "^1.3.1", "postgres": "^3.4.7" } }, "corbitsdev-corbits-memory-9e6f213", "sha512-utnM4ZT2zmslcPXYWAAqxlDNLcpGsXFiTOtj8h7+OXnhCP0Eaw8yl25+yCTyHpvt3jcdeG4h5uFsSj7ou0BZCA=="], - "@workbench/web/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], + "@workbench/sidecar/@corbits/oauth-core": ["@corbits/oauth-core@github:corbitsdev/corbits-oauth-core#e1e69e6", { "dependencies": { "arktype": "2.2.3" } }, "corbitsdev-corbits-oauth-core-e1e69e6", "sha512-wUrD73iVyk/Dtb4yRn3hCh6N8syfsEvAkRz4XYqT0FIB3sYDSMYEWHcDMJx9nq64my/HBOeN1J6PHIOtpjhtPg=="], "ajv-formats/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], @@ -3605,6 +3578,8 @@ "@babel/helper-compilation-targets/lru-cache/yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="], + "@corbits/inbox/@corbits/mailbox/hono-openapi": ["hono-openapi@1.3.1", "", { "peerDependencies": { "@hono/standard-validator": "^0.2.0", "@standard-community/standard-json": "^0.3.5", "@standard-community/standard-openapi": "^0.2.9", "@types/json-schema": "^7.0.15", "hono": "^4.11.2", "openapi-types": "^12.1.3" }, "optionalPeers": ["@hono/standard-validator", "hono"] }, "sha512-NLVeVkhKZ3drmQNEIPac8HX8Y54uf1hJAgIM/7MfDsaeVVmB+QILWQxx5x3R3NvRHgedcbEbOCGY2uR7WQYyMw=="], + "@esbuild-kit/core-utils/esbuild/@esbuild/android-arm": ["@esbuild/android-arm@0.18.20", "", { "os": "android", "cpu": "arm" }, "sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw=="], "@esbuild-kit/core-utils/esbuild/@esbuild/android-arm64": ["@esbuild/android-arm64@0.18.20", "", { "os": "android", "cpu": "arm64" }, "sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ=="], @@ -3651,6 +3626,8 @@ "@modelcontextprotocol/sdk/ajv/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], + "@workbench/hub/@corbits/mailbox/hono-openapi": ["hono-openapi@1.3.1", "", { "peerDependencies": { "@hono/standard-validator": "^0.2.0", "@standard-community/standard-json": "^0.3.5", "@standard-community/standard-openapi": "^0.2.9", "@types/json-schema": "^7.0.15", "hono": "^4.11.2", "openapi-types": "^12.1.3" }, "optionalPeers": ["@hono/standard-validator", "hono"] }, "sha512-NLVeVkhKZ3drmQNEIPac8HX8Y54uf1hJAgIM/7MfDsaeVVmB+QILWQxx5x3R3NvRHgedcbEbOCGY2uR7WQYyMw=="], + "ajv-formats/ajv/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], "minipass-flush/minipass/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], diff --git a/packages/onboarding/package.json b/packages/onboarding/package.json index 4066033d63..f007687d3c 100644 --- a/packages/onboarding/package.json +++ b/packages/onboarding/package.json @@ -38,7 +38,6 @@ "@intx/hub-api": "workspace:*", "@intx/hub-common": "workspace:*", "@intx/types": "workspace:*", - "@workbench/access-policy": "workspace:*", "@corbits/connections": "workspace:*", "@corbits/hub-api-client": "workspace:*", "@corbits/tool-registry-publish": "workspace:*", diff --git a/packages/onboarding/src/genesis.ts b/packages/onboarding/src/genesis.ts index 6132657872..a62ce35c5c 100644 --- a/packages/onboarding/src/genesis.ts +++ b/packages/onboarding/src/genesis.ts @@ -4,10 +4,6 @@ import { paginatedSchema, PrincipalSummary, TenantResponse } from "@intx/types"; import { parseAs, type ApiCall } from "@corbits/hub-api-client"; -import { - checkSignupGate, - type AccessPolicyStore, -} from "@workbench/access-policy"; export type HubSignupTenancy = { countUsers(): Promise; @@ -29,10 +25,6 @@ export type GenesisOrJoinArgs = { defaultTenantSlug: string; displayName?: string; tenancy: HubSignupTenancy; - accessPolicy?: { - store: AccessPolicyStore; - allowUnverifiedEmails: boolean; - }; log: (line: string) => void; }; @@ -101,32 +93,6 @@ async function joinRoot( }; } -/** - * Runs the signup gate before minting anything. `emptyHubException` - * waives only `signup_closed`: with zero tenants somebody has to be - * first, but email trust and the domain allowlist still bind even the - * genesis caller. A rejection is always a 403-shaped `ProvisionError`. - */ -async function requireSignupAllowed( - args: GenesisOrJoinArgs, - options: { readonly emptyHubException: boolean }, -): Promise { - if (args.accessPolicy === undefined) return; - const gate = await checkSignupGate({ - store: args.accessPolicy.store, - email: args.userEmail, - emailVerified: args.userEmailVerified, - allowUnverifiedEmails: args.accessPolicy.allowUnverifiedEmails, - }); - if (gate.allowed) return; - if (options.emptyHubException && gate.reason === "signup_closed") return; - throw new ProvisionError( - "signup_not_allowed", - `signup gate rejected ${args.userEmail} (${gate.reason})`, - "permanent", - ); -} - async function requireRoot(tenancy: HubSignupTenancy): Promise<{ id: string; slug: string; @@ -154,12 +120,9 @@ export async function genesisOrJoinHubSignup( // still genesis when no tenant exists. const tenantCount = await args.tenancy.countTenants(); if (tenantCount > 0) { - await requireSignupAllowed(args, { emptyHubException: false }); return joinRoot(args, await requireRoot(args.tenancy)); } - await requireSignupAllowed(args, { emptyHubException: true }); - if (args.displayName === undefined || args.displayName.trim().length === 0) { return { kind: "needs-onboarding" }; } diff --git a/packages/onboarding/src/provision.ts b/packages/onboarding/src/provision.ts index 3dc5c5545a..d4df0623af 100644 --- a/packages/onboarding/src/provision.ts +++ b/packages/onboarding/src/provision.ts @@ -7,7 +7,6 @@ // user's own credential, never by signup. import { type ApiCall } from "@corbits/hub-api-client"; -import type { AccessPolicyStore } from "@workbench/access-policy"; import { genesisOrJoinHubSignup, type HubSignupTenancy } from "./genesis"; export { ProvisionError } from "./genesis"; @@ -39,10 +38,6 @@ export type ProvisionArgs = { cookies: string[]; userId: string; userEmail: string; - /** better-auth is configured without `requireEmailVerification` — an - * unverified email must never pass a domain-allowlist meant for - * someone else. See `@workbench/access-policy`'s `evaluateSignupGate` - * doc comment. */ userEmailVerified: boolean; /** Slug for the genesis tenant — the first tenant on an empty hub. * Later signups join the existing root and never read this. */ @@ -53,14 +48,6 @@ export type ProvisionArgs = { displayName?: string; tenancy: HubSignupTenancy; log: (line: string) => void; - /** The closed-by-default access-policy gate. Join consults it - * outright (a closed hub never self-grants membership); genesis on an - * empty hub waives only `signup_closed` — email verification and the - * domain allowlist still bind the first user. */ - accessPolicy?: { - store: AccessPolicyStore; - allowUnverifiedEmails: boolean; - }; }; /** A lowercase-kebab personal-bench slug, unique per user without a @@ -98,9 +85,6 @@ export async function provisionPersonalTenantIfNeeded( defaultTenantSlug: args.defaultTenantSlug, tenancy: args.tenancy, log: args.log, - ...(args.accessPolicy !== undefined - ? { accessPolicy: args.accessPolicy } - : {}), ...(args.displayName !== undefined ? { displayName: args.displayName } : {}), diff --git a/packages/onboarding/src/routes.ts b/packages/onboarding/src/routes.ts index 69e9892fe1..74ed850707 100644 --- a/packages/onboarding/src/routes.ts +++ b/packages/onboarding/src/routes.ts @@ -28,7 +28,6 @@ import { } from "@corbits/hub-api-client"; import { Hono } from "hono"; import { type } from "arktype"; -import type { AccessPolicyStore } from "@workbench/access-policy"; import { generateRefId, makeErrorEnvelope, @@ -213,14 +212,6 @@ export type CreateOnboardingRoutesDeps = { * from `createDrizzlePendingSeedStore(db, credentialCipher)` in * production; tests inject `createInMemoryPendingSeedStore`. */ pendingSeedStore: PendingSeedStore; - /** The closed-by-default access-policy gate threaded straight into - * `provisionPersonalTenantIfNeeded` — see that function's own - * `accessPolicy` doc comment. Absent means no access-policy package - * is wired in at all; never a valid production shape. */ - accessPolicy?: { - store: AccessPolicyStore; - allowUnverifiedEmails: boolean; - }; /** Seals the OAuth connect state (PKCE verifier included) parked * between `/start` and `/callback`, so a hub restart in between * doesn't strand it — see `@corbits/connections`' `pkce.ts`. The same `CredentialCipher` @@ -487,8 +478,6 @@ export function createOnboardingRoutes( log: deps.log, }; if (body?.name !== undefined) provisionArgs.displayName = body.name; - if (deps.accessPolicy !== undefined) - provisionArgs.accessPolicy = deps.accessPolicy; const result = await provisionPersonalTenantIfNeeded(provisionArgs); diff --git a/packages/settings-ui/src/index.ts b/packages/settings-ui/src/index.ts index bd98541f65..4e93cf7cc1 100644 --- a/packages/settings-ui/src/index.ts +++ b/packages/settings-ui/src/index.ts @@ -23,7 +23,6 @@ export { // NotificationsSection is not exported: it is draft-only and not in the // registry (CL-6843). Re-export when a preference store backs it. export { AuditSection } from "./audit-section"; -export { AccessPolicyBlock, AccessPolicyEditor } from "./access-policy"; export { PeopleSection, PeopleTable } from "./people-section"; export { RolesSection, diff --git a/packages/settings-ui/src/people-section.tsx b/packages/settings-ui/src/people-section.tsx index 68c11aff9e..34be9b2e9b 100644 --- a/packages/settings-ui/src/people-section.tsx +++ b/packages/settings-ui/src/people-section.tsx @@ -30,7 +30,6 @@ import { } from "@corbits/api-query"; import { reportError } from "@corbits/error-sink"; import { PRINCIPAL_KIND_LABEL, principalLabel } from "./identity"; -import { AccessPolicyBlock } from "./access-policy"; import { SETTINGS_STRINGS } from "./strings"; import { @@ -213,7 +212,6 @@ export function PeopleSection({ handleRoleChange(p, roleId, people, roles) } /> - )} diff --git a/packages/settings-ui/src/strings.ts b/packages/settings-ui/src/strings.ts index 2caed8abd9..ce3e1ce3ba 100644 --- a/packages/settings-ui/src/strings.ts +++ b/packages/settings-ui/src/strings.ts @@ -74,28 +74,6 @@ export const SETTINGS_STRINGS = { peopleLastOwnerError: "This workbench needs at least one owner — make someone else an owner first.", - accessPolicyHeading: "Who can join", - accessPolicyLoadError: "who can join", - accessPolicySignupLabel: "Self-signup", - accessPolicySignupOff: "Off — no self-signup (default)", - accessPolicySignupAllowedDomains: "Anyone with an allowed email domain", - accessPolicySignupOpenOption: "Anyone with an account", - accessPolicyDomainsLabel: "Allowed email domains", - accessPolicyDomainsPlaceholder: "acme.example", - accessPolicyDomainsAdd: "Add", - accessPolicyDomainsEmptyHint: - "No domains added yet — with self-signup on and no domains listed, any email domain is allowed.", - accessPolicyDomainsRemove: "Remove", - accessPolicySubCreationLabel: "Who can create a sub-workbench here", - accessPolicySubCreationOwners: "Owners only (default)", - accessPolicySubCreationOwnersAdmins: "Owners and admins", - accessPolicySubCreationNone: "Nobody", - accessPolicySaveAction: "Save", - accessPolicySaving: "Saving…", - accessPolicySaveError: "Couldn't save that change — try again.", - accessPolicyNote: - "Closed by default: no open signup, no self-serve sub-workbenches. These settings apply to this workbench.", - rolesSectionTitle: "Roles", rolesSectionDescription: "This workbench's roles and who they're assigned to.", diff --git a/packages/settings-ui/src/styles.css b/packages/settings-ui/src/styles.css index dd6bd07bf1..acbabb6286 100644 --- a/packages/settings-ui/src/styles.css +++ b/packages/settings-ui/src/styles.css @@ -221,15 +221,6 @@ line-height: 1; } -.settings-access-policy { - display: flex; - flex-direction: column; - gap: 0.5rem; - margin-top: 1rem; - padding-top: 0.75rem; - border-top: 1px solid var(--border); -} - .settings-kind-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); diff --git a/scripts/checks/no-product-tenancy.ts b/scripts/checks/no-product-tenancy.ts index 3d689e270b..f3295b8d6f 100644 --- a/scripts/checks/no-product-tenancy.ts +++ b/scripts/checks/no-product-tenancy.ts @@ -128,11 +128,6 @@ const ALLOWLIST: readonly { maxOccurrences: 1, tables: ["bench_model_policy"], }, - { - relPath: "packages/access-policy/src/schema.ts", - maxOccurrences: 1, - tables: ["policy"], - }, { relPath: "packages/onboarding/src/schema.ts", maxOccurrences: 1, diff --git a/scripts/checks/report-error-baseline.txt b/scripts/checks/report-error-baseline.txt index 1f73654d53..44138a36a7 100644 --- a/scripts/checks/report-error-baseline.txt +++ b/scripts/checks/report-error-baseline.txt @@ -88,7 +88,6 @@ apps/web/src/session.ts 3 return { apps/web/src/shell/context-menu/items.tsx 1 toast("Couldn't copy the link"); apps/web/src/shell/workbench-list.tsx 1 // Revert the optimistic title on failure; the list will refetch on apps/web/src/shell/workbench-list.tsx 1 setPinned(!next); -packages/access-policy/src/policy.ts 1 return []; packages/agent-directory-tools/src/tool.ts 1 // The agent was genuinely created — that half-success must never packages/agent-directory-tools/src/tool.ts 1 if (err instanceof CreateAgentDefinitionError) { packages/agent-directory-tools/src/tool.ts 1 return errorResult(call.id, err); diff --git a/scripts/db-setup.ts b/scripts/db-setup.ts index 132c9a68a5..96546ac3f8 100644 --- a/scripts/db-setup.ts +++ b/scripts/db-setup.ts @@ -40,7 +40,6 @@ import { applyPreferencesMigrations } from "../packages/preferences/src/migratio import { applyBenchMigrations } from "../packages/bench/src/migrations"; import { applyAgentDirectoryMigrations } from "../packages/agent-directory/src/migrations"; import { applyOnboardingMigrations } from "../packages/onboarding/src/migrations"; -import { applyAccessPolicyMigrations } from "../packages/access-policy/src/migrations"; import { applyRunKeyHistoryMigrations } from "../packages/run-key-history/src/migrations"; import { applyInferenceCatalogMigrations } from "../packages/inference-catalog/src/migrations"; @@ -71,7 +70,6 @@ const INSTALLED_PACKAGE_MIGRATIONS: readonly { { name: "@corbits/bench", apply: applyBenchMigrations }, { name: "@corbits/agent-directory", apply: applyAgentDirectoryMigrations }, { name: "@workbench/onboarding", apply: applyOnboardingMigrations }, - { name: "@workbench/access-policy", apply: applyAccessPolicyMigrations }, { name: "@corbits/run-key-history", apply: applyRunKeyHistoryMigrations }, { name: "@corbits/inference-catalog", diff --git a/tsconfig.build.json b/tsconfig.build.json index 97591faf58..e52605d6cd 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -4,9 +4,6 @@ { "path": "./apps/sidecar/tsconfig.src.json" }, - { - "path": "./packages/access-policy/tsconfig.src.json" - }, { "path": "./packages/access-tools/tsconfig.src.json" }, From f76c727f4c57592cbfd5d841f577c54e8c8fe7dd Mon Sep 17 00:00:00 2001 From: Sawyer Date: Thu, 17 Sep 2026 08:57:24 -0700 Subject: [PATCH 3/3] docs: clear access-policy references after CL-8130 deletion TENANCY.md's Signup mode and sub-workbench-creation sections, the package glossary, the migration-shape reference implementation pointer, and two package READMEs all named @workbench/access-policy as retained-but-unwired; it is now deleted outright. Claude-Session: https://claude.ai/code/session_01RweuMUskU2nvcFhdckc7EG --- apps/hub/README.md | 2 +- docs/GLOSSARY.md | 4 +-- docs/TENANCY.md | 38 +++++++++++++------------- docs/package-migrations.md | 6 ++-- packages/inference-settings/src/api.ts | 5 ++-- packages/settings-ui/README.md | 1 - 6 files changed, 27 insertions(+), 29 deletions(-) diff --git a/apps/hub/README.md b/apps/hub/README.md index c8f1609552..fc87553e72 100644 --- a/apps/hub/README.md +++ b/apps/hub/README.md @@ -13,7 +13,7 @@ native tenant middleware. provide the platform's own routes, auth, and tenant middleware; this app never re-implements them. - Every `@corbits/*` and `@workbench/*` package route (chat, approvals, - bench, insights, access-policy, mailbox, memory, skills, artifacts, + bench, insights, mailbox, memory, skills, artifacts, routines, tasks, webhooks, and more) mounts here as one explicit import plus one `app.route(...)` call, inside or outside the tenant prefix as the extension requires. `src/index.ts` is the single diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md index aa290ffea3..ddb09ac29b 100644 --- a/docs/GLOSSARY.md +++ b/docs/GLOSSARY.md @@ -64,5 +64,5 @@ Naming conventions for this repository's packages: plain local domain code — with a kebab-case kind suffix where the package is one of a family (`-agent`, `-tool`). - `@workbench/*` is a legacy scope being migrated to `@corbits/*` package - by package; a handful of packages still carry it (`access-policy`, - `connections`, `onboarding`). New packages never use it. + by package; a handful of packages still carry it (`connections`, + `onboarding`). New packages never use it. diff --git a/docs/TENANCY.md b/docs/TENANCY.md index c30eb4efff..e4892dc341 100644 --- a/docs/TENANCY.md +++ b/docs/TENANCY.md @@ -11,14 +11,14 @@ requires an upstream Interchange change. **Do not patch `vendor/intx`.** ## What already works (consume, do not reimplement) -| Capability | Where | -| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Tenant `parentId` hierarchy | `@intx/db` tenant table; POST `/api/tenants` accepts `parentId` | -| Live ancestor-chain inheritance | `getAncestorChain` in `@intx/db` — catalog, credentials, providers walk ancestors at read time | -| Descendant walk | `getDescendantTenants` in `@intx/db` | -| Roles | Interchange native `owner` / `admin` / `member` — mirror 1:1 in UI; never invent a parallel role table | -| First-signup genesis / join | `packages/onboarding`'s `genesisOrJoinHubSignup` is retained but unwired: stock composition mounts no first-login provisioning hook, so signup mints no tenants — the first tenant still comes from an ordinary `POST /api/tenants` with a chosen slug | -| Memberships | Native principal + membership routes | +| Capability | Where | +| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Tenant `parentId` hierarchy | `@intx/db` tenant table; POST `/api/tenants` accepts `parentId` | +| Live ancestor-chain inheritance | `getAncestorChain` in `@intx/db` — catalog, credentials, providers walk ancestors at read time | +| Descendant walk | `getDescendantTenants` in `@intx/db` | +| Roles | Interchange native `owner` / `admin` / `member` — mirror 1:1 in UI; never invent a parallel role table | +| First-signup genesis / join | Stock composition mounts no first-login provisioning hook, so signup mints no tenants — the first tenant comes from an ordinary `POST /api/tenants` with a chosen slug | +| Memberships | Native principal + membership routes | Inheritance is **live**. Creating a sub-workbench must **not** copy catalog rows, credentials, or providers from the parent — resolution @@ -65,11 +65,12 @@ all gone, and nothing gates better-auth's `/sign-up/email` route or requires `user.emailVerified`. Anyone can register (rate-limited only — see `SIGNUP_RATE_LIMIT_*` in `.env.example`). -`@workbench/access-policy` and `packages/onboarding`'s first-login -provisioning hook are retained as packages but unwired: the hub never -calls them, so no policy row or env flag decides signup. A deployment -that needs closed signup gates it in the composition that embeds the -hub. +`@workbench/access-policy` (the closed-by-default signup/sub-workbench +policy table and gate) was deleted rather than kept unwired (CL-8130): +it had no native equivalent and nothing in the hub called it. A +deployment that needs closed signup gates it in the composition that +embeds the hub — there is no Workbench-side policy row or env flag to +configure. ### Workbench icon @@ -91,10 +92,11 @@ tenant with the caller as owner — no signup-gate landing zone, no membership check on `parentId`. `@workbench/access-policy`'s `POST /api/tenants/:tenantId/access-policy/ -child-tenants` is the polished UI-facing wrapper for creating a child -tenant under a parent — it makes the same decision and gives a clean -pre-flight 403, but with the guard above removed in the cutover the -wrapper alone does not close the gap. +child-tenants` — a polished UI-facing wrapper that pre-flighted this +same decision with a clean 403 — was deleted (CL-8130): it was never +mounted, so it never closed this gap either. Native `POST /api/tenants` +grant-gating is the only real gate; until the platform check lands +this gap stays open. Interchange currently does **not** validate `parentId` on POST and has **no** cycle constraint — see gaps below. @@ -289,8 +291,6 @@ needs a weaker role, that is an Interchange conversation first. - `@corbits/bench-ui` — `isRawIdentifier` raw-id guard, tenancy contracts (tenancy-kind helpers and the workbench-tenancy client were removed in the thread-native client-driver cutover) - `@workbench/onboarding` — genesis-or-join first-signup provisioning (retained, unwired in stock composition) -- `@workbench/access-policy` — signup/sub-workbench-creation policy - package (retained, but the hub's stock composition mounts no gate) - `apps/hub` — invite routes, icon routes; one of the explicitly-listed apps/hub mounts pending extraction into a package (see [ARCHITECTURE.md](../ARCHITECTURE.md), CL-6127) diff --git a/docs/package-migrations.md b/docs/package-migrations.md index 1397cb9ca3..929f78ed0a 100644 --- a/docs/package-migrations.md +++ b/docs/package-migrations.md @@ -72,7 +72,7 @@ package onto the transactional pattern — see below): 1. **Self-contained, transactional** — `@corbits/chat`, `@corbits/notify`, `@corbits/webhook-triggers`, `@corbits/insights`, `@corbits/skills`, `@corbits/bench`, `@corbits/preferences`, - `@corbits/inference-catalog`, `@corbits/evals`, `@corbits/access-policy`. + `@corbits/inference-catalog`, `@corbits/evals`. (`@corbits/workflows`'s `./deploy-source` followed this shape until CL-7591 deleted it; it is no longer wired through `scripts/db-setup.ts`.) @@ -84,7 +84,7 @@ package onto the transactional pattern — see below): table name, and migration array. `scripts/db-setup.ts` imports the package's `applyXMigrations(databaseUrl)` function directly and calls it after the platform's own migrations. See - `packages/access-policy/src/migrations.ts` for the reference + `packages/inference-catalog/src/migrations.ts` for the reference implementation every other package now matches. 2. **Delegated to an external package** — `@corbits/mailbox`. The package ships and owns its entire migration story (its own literal SQL, its own @@ -121,7 +121,7 @@ the new schema by running `bun run reset` rather than by an in-place ## Which shape to use for a new package **Transactional, self-contained** (shape 1 above), in a Postgres schema -named for the package. Copy `packages/access-policy/src/migrations.ts`'s +named for the package. Copy `packages/inference-catalog/src/migrations.ts`'s shape: a `pgSchema("")` in `schema.ts`, a literal migration array whose SQL qualifies every table/index with that schema, a package-named ledger table living in the same schema, and an `applyXMigrations` that diff --git a/packages/inference-settings/src/api.ts b/packages/inference-settings/src/api.ts index b1f6332470..b042dec6c5 100644 --- a/packages/inference-settings/src/api.ts +++ b/packages/inference-settings/src/api.ts @@ -65,9 +65,8 @@ type Validator = (data: unknown) => T | type.errors; // It exists so a server-side caller — `@corbits/config-profiles`' apply // route, composing a profile's writes out of these exact functions — can // pass a `fetch` bound to the hub's own base URL and the acting -// principal's session cookie, the same self-HTTP-call seam -// `@workbench/access-policy`'s routes use, rather than this module -// growing a second, duplicated write path for the server-side case. +// principal's session cookie, rather than this module growing a second, +// duplicated write path for the server-side case. // Exported (not `typeof fetch`) so a bound wrapper — which never carries // `fetch`'s own static `preconnect` member — satisfies the type too. // `string | URL | Request`, not DOM's `RequestInfo | URL` alias, so this diff --git a/packages/settings-ui/README.md b/packages/settings-ui/README.md index c7daa55656..5a835fadeb 100644 --- a/packages/settings-ui/README.md +++ b/packages/settings-ui/README.md @@ -32,7 +32,6 @@ toggles). draft until a preference store exists) - `access.ts` / `tenancy-api.ts` — tenancy-gate resolution and the principals/roles/grants HTTP client -- `access-policy.tsx` — the grant preview/editor shared by roles and grants ## Running tests