@aglyn/tenant-data-admin 1.0.0-beta.285 → 1.0.0-beta.288

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-data-admin",
3
- "version": "1.0.0-beta.285",
3
+ "version": "1.0.0-beta.288",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,12 +25,12 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.285",
29
- "@aglyn/shared-util-email": "1.0.0-beta.285",
30
- "@aglyn/shared-util-fbserver": "1.0.0-beta.285",
31
- "@aglyn/shared-util-first-touch": "1.0.0-beta.285",
32
- "@aglyn/shared-util-http": "1.0.0-beta.285",
33
- "@aglyn/shared-util-tools": "1.0.0-beta.285",
28
+ "@aglyn/aglyn": "1.0.0-beta.288",
29
+ "@aglyn/shared-util-email": "1.0.0-beta.288",
30
+ "@aglyn/shared-util-fbserver": "1.0.0-beta.288",
31
+ "@aglyn/shared-util-first-touch": "1.0.0-beta.288",
32
+ "@aglyn/shared-util-http": "1.0.0-beta.288",
33
+ "@aglyn/shared-util-tools": "1.0.0-beta.288",
34
34
  "@msgpack/msgpack": "^3.1.3",
35
35
  "@swc/helpers": "0.5.23",
36
36
  "sharp": "^0.35.5",
@@ -13,7 +13,7 @@
13
13
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
- */ import { ACCOUNT_ACQUISITION_FIELD, buildAccountAcquisition, readAccountAcquisition, signUpDoorFor } from "@aglyn/aglyn/app-utils/account-acquisition";
16
+ */ import { ACCOUNT_ACQUISITION_FIELD, buildAccountAcquisition, readAccountAcquisition, signUpDoorFor, signUpProviderFor } from "@aglyn/aglyn/app-utils/account-acquisition";
17
17
  import { readRequestCity, readRequestGeo, readRequestRegionLabel } from "@aglyn/aglyn/app-utils/request-geo";
18
18
  import { findUserByUidAcrossPools } from "./auth-pools.js";
19
19
  import firebaseAdmin from "./firebase-admin.js";
@@ -118,19 +118,24 @@ import firebaseAdmin from "./firebase-admin.js";
118
118
  *
119
119
  * `null` when the provider is not a sign-up door (SSO records its own).
120
120
  */ export async function recordSignUpAcquisition(input) {
121
- var _ref;
122
- const door = signUpDoorFor(input.provider, input.doorHint);
123
- if (!door) return null;
121
+ var _ref, _ref1;
122
+ // A `custom` token can name no door until the auth record says which
123
+ // provider made the account (AGL-3706), so the lookup comes first for it.
124
+ const custom = input.provider === 'custom';
125
+ if (!custom && !signUpDoorFor(input.provider, input.doorHint)) return null;
124
126
  // Across every pool, not the project's alone (AGL-1122): a lookup that
125
127
  // cannot see an account answers "not new", which writes nothing.
126
128
  const pooled = await findUserByUidAcrossPools(input.uid);
127
- const createdAtMs = Date.parse((_ref = pooled == null ? void 0 : pooled.record.metadata.creationTime) != null ? _ref : '');
129
+ const provider = signUpProviderFor(input.provider, ((_ref = pooled == null ? void 0 : pooled.record.providerData) != null ? _ref : []).map((info)=>info.providerId));
130
+ const door = signUpDoorFor(provider, input.doorHint);
131
+ if (!door) return null;
132
+ const createdAtMs = Date.parse((_ref1 = pooled == null ? void 0 : pooled.record.metadata.creationTime) != null ? _ref1 : '');
128
133
  return recordAccountAcquisition({
129
134
  uid: input.uid,
130
135
  accountCreatedAtMs: Number.isFinite(createdAtMs) ? createdAtMs : null,
131
136
  touch: input.touch,
132
137
  door,
133
- provider: input.provider,
138
+ provider,
134
139
  email: input.email,
135
140
  headers: input.headers,
136
141
  recordedBy: 'signup',
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/account-acquisition.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ACCOUNT_ACQUISITION_FIELD,\n buildAccountAcquisition,\n readAccountAcquisition,\n signUpDoorFor,\n type AccountAcquisition,\n type AcquisitionDoor,\n} from '@aglyn/aglyn/app-utils/account-acquisition'\nimport {\n readRequestCity,\n readRequestGeo,\n readRequestRegionLabel,\n type HeaderReader,\n} from '@aglyn/aglyn/app-utils/request-geo'\nimport { findUserByUidAcrossPools } from './auth-pools'\nimport firebaseAdmin from './firebase-admin'\n\n/**\n * Write where an account came from, ONCE, at account creation (AGL-3289).\n *\n * The capture kept the first touch on the visitor's device; the door that\n * created the account hands it here, with what only the server knows beside\n * it: the door, the sign-in provider from the verified token, where the\n * request came from as the edge reported it, and whether the address had an\n * invitation waiting. The record goes on `users/{uid}` inside a transaction\n * that writes nothing when one is already there — the first write wins, and\n * a retry, a second tab or a later call can never restate it.\n *\n * The rules deny the field to every client, so this Admin SDK write is the\n * only way in. `createOrganization` copies it onto the workspace the account\n * creates.\n */\n\n/**\n * How long after an account is created its door may still record where it\n * came from. A door calls within seconds of creating the account; a mobile\n * redirect or a slow verification page within minutes. Anything later is not\n * account creation, and a record written then would describe a later visit.\n */\nexport const ACCOUNT_ACQUISITION_WINDOW_MS = 30 * 60 * 1000\n\n/** What a door knows when it records an account. */\nexport interface RecordAccountAcquisitionInput {\n uid: string\n /** When the auth record says the account was created; null refuses. */\n accountCreatedAtMs: number | null\n /** The first touch the device kept — untrusted. */\n touch: unknown\n door: AcquisitionDoor\n /** From the verified token's `sign_in_provider`. */\n provider: string | null\n /** The account's address, for the invitation check; null when it has none. */\n email: string | null\n /** The organization an invitation the door already found came from. */\n invitedToOrgId?: string | null\n /** The account-creating request's headers, for its geography. */\n headers: HeaderReader\n recordedBy: 'signup' | 'sso'\n nowMs?: number\n firestore?: FirebaseFirestore.Firestore\n}\n\nexport type RecordAccountAcquisitionResult =\n | { status: 'recorded'; record: AccountAcquisition }\n | { status: 'exists'; record: AccountAcquisition | null }\n /** The account was not created just now, so this is not its creation. */\n | { status: 'not-new' }\n\n/**\n * The organization whose invitation this address has waiting, or null. The\n * same query the console's invitation banner runs, one address wide.\n */\nexport async function pendingInvitationOrgId(\n email: string | null,\n firestore: FirebaseFirestore.Firestore = firebaseAdmin.app().firestore(),\n): Promise<string | null> {\n const address = String(email ?? '').trim().toLowerCase()\n if (!address) return null\n try {\n const snapshot = await firestore\n .collectionGroup('invites')\n .where('email', 'in', [address])\n .where('acceptedAt', '==', null)\n .limit(1)\n .get()\n return snapshot.docs[0]?.ref.parent.parent?.id ?? null\n } catch (error) {\n // An unanswerable question costs the door's label, never the record.\n console.error('[account-acquisition] invitation lookup failed', error)\n return null\n }\n}\n\n/** Where the request came from, as a person reads it — no address, no coordinates. */\nexport function requestGeography(headers: HeaderReader): {\n country: string | null\n region: string | null\n city: string | null\n} {\n return {\n country: readRequestGeo(headers).country,\n region: readRequestRegionLabel(headers),\n city: readRequestCity(headers),\n }\n}\n\n/** Record the account's acquisition unless it already has one. */\nexport async function recordAccountAcquisition(\n input: RecordAccountAcquisitionInput,\n): Promise<RecordAccountAcquisitionResult> {\n const firestore = input.firestore ?? firebaseAdmin.app().firestore()\n const nowMs = input.nowMs ?? Date.now()\n if (\n input.accountCreatedAtMs === null ||\n !Number.isFinite(input.accountCreatedAtMs) ||\n nowMs - input.accountCreatedAtMs > ACCOUNT_ACQUISITION_WINDOW_MS\n ) {\n return { status: 'not-new' }\n }\n const invitedToOrgId =\n input.invitedToOrgId ??\n (input.door === 'signup-password' ||\n input.door === 'signup-google' ||\n input.door === 'signup-google-redirect'\n ? await pendingInvitationOrgId(input.email, firestore)\n : null)\n const record = buildAccountAcquisition({\n touch: input.touch,\n door: invitedToOrgId && input.door !== 'sso' ? 'invite' : input.door,\n provider: input.provider,\n geo: requestGeography(input.headers),\n invitedToOrgId,\n accountCreatedAtMs: input.accountCreatedAtMs,\n recordedBy: input.recordedBy,\n nowMs,\n })\n const userRef = firestore.collection('users').doc(input.uid)\n return firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(userRef)\n const existing = snapshot.exists ? snapshot.get(ACCOUNT_ACQUISITION_FIELD) : undefined\n if (existing !== undefined && existing !== null) {\n return { status: 'exists', record: readAccountAcquisition(existing) } as const\n }\n tx.set(userRef, { [ACCOUNT_ACQUISITION_FIELD]: record }, { merge: true })\n return { status: 'recorded', record } as const\n })\n}\n\n/** What a sign-up door knows about the account it is recording. */\nexport interface RecordSignUpAcquisitionInput {\n uid: string\n /** The verified token's `sign_in_provider`. */\n provider: string | null\n /** The verified token's address. */\n email: string | null\n /** The first touch the page sent, else the request's cookie — untrusted. */\n touch: unknown\n /** Which of the provider's doors the page says it was; see `signUpDoorFor`. */\n doorHint?: unknown\n headers: HeaderReader\n nowMs?: number\n firestore?: FirebaseFirestore.Firestore\n}\n\n/**\n * Record a self-serve sign-up's acquisition, deciding from the verified\n * provider and the auth record whether there is one to record.\n *\n * Shared by the two moments a sign-up passes through: the sign-up page's own\n * call, right after the account exists, and workspace creation, which is the\n * backstop for a page torn down before its call went out — the workspace\n * copies its creator's record at birth, so that is the last moment one can\n * still reach it. Both write through {@link recordAccountAcquisition}, so the\n * first one wins and neither can restate the other; an account older than\n * the window, or one a sign-up door did not create, writes nothing.\n *\n * `null` when the provider is not a sign-up door (SSO records its own).\n */\nexport async function recordSignUpAcquisition(\n input: RecordSignUpAcquisitionInput,\n): Promise<RecordAccountAcquisitionResult | null> {\n const door = signUpDoorFor(input.provider, input.doorHint)\n if (!door) return null\n // Across every pool, not the project's alone (AGL-1122): a lookup that\n // cannot see an account answers \"not new\", which writes nothing.\n const pooled = await findUserByUidAcrossPools(input.uid)\n const createdAtMs = Date.parse(pooled?.record.metadata.creationTime ?? '')\n return recordAccountAcquisition({\n uid: input.uid,\n accountCreatedAtMs: Number.isFinite(createdAtMs) ? createdAtMs : null,\n touch: input.touch,\n door,\n provider: input.provider,\n email: input.email,\n headers: input.headers,\n recordedBy: 'signup',\n nowMs: input.nowMs,\n firestore: input.firestore,\n })\n}\n"],"names":["ACCOUNT_ACQUISITION_FIELD","buildAccountAcquisition","readAccountAcquisition","signUpDoorFor","readRequestCity","readRequestGeo","readRequestRegionLabel","findUserByUidAcrossPools","firebaseAdmin","ACCOUNT_ACQUISITION_WINDOW_MS","pendingInvitationOrgId","email","firestore","app","address","String","trim","toLowerCase","snapshot","collectionGroup","where","limit","get","docs","ref","parent","id","error","console","requestGeography","headers","country","region","city","recordAccountAcquisition","input","nowMs","Date","now","accountCreatedAtMs","Number","isFinite","status","invitedToOrgId","door","record","touch","provider","geo","recordedBy","userRef","collection","doc","uid","runTransaction","tx","existing","exists","undefined","set","merge","recordSignUpAcquisition","doorHint","pooled","createdAtMs","parse","metadata","creationTime"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,yBAAyB,EACzBC,uBAAuB,EACvBC,sBAAsB,EACtBC,aAAa,QAGR,6CAA4C;AACnD,SACEC,eAAe,EACfC,cAAc,EACdC,sBAAsB,QAEjB,qCAAoC;AAC3C,SAASC,wBAAwB,QAAQ,kBAAc;AACvD,OAAOC,mBAAmB,sBAAkB;AAE5C;;;;;;;;;;;;;;CAcC,GAED;;;;;CAKC,GACD,OAAO,MAAMC,gCAAgC,KAAK,KAAK,KAAI;AA6B3D;;;CAGC,GACD,OAAO,eAAeC,uBACpBC,KAAoB,EACpBC,YAAyCJ,cAAcK,GAAG,GAAGD,SAAS,EAAE;IAExE,MAAME,UAAUC,OAAOJ,gBAAAA,QAAS,IAAIK,IAAI,GAAGC,WAAW;IACtD,IAAI,CAACH,SAAS,OAAO;IACrB,IAAI;;YAOKI,mCAAAA;QANP,MAAMA,WAAW,MAAMN,UACpBO,eAAe,CAAC,WACh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OD,MAAMC,KAAK;QAClBxB,WAAWuB,MAAMvB,SAAS;IAC5B;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/account-acquisition.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ACCOUNT_ACQUISITION_FIELD,\n buildAccountAcquisition,\n readAccountAcquisition,\n signUpDoorFor,\n signUpProviderFor,\n type AccountAcquisition,\n type AcquisitionDoor,\n} from '@aglyn/aglyn/app-utils/account-acquisition'\nimport {\n readRequestCity,\n readRequestGeo,\n readRequestRegionLabel,\n type HeaderReader,\n} from '@aglyn/aglyn/app-utils/request-geo'\nimport { findUserByUidAcrossPools } from './auth-pools'\nimport firebaseAdmin from './firebase-admin'\n\n/**\n * Write where an account came from, ONCE, at account creation (AGL-3289).\n *\n * The capture kept the first touch on the visitor's device; the door that\n * created the account hands it here, with what only the server knows beside\n * it: the door, the sign-in provider from the verified token, where the\n * request came from as the edge reported it, and whether the address had an\n * invitation waiting. The record goes on `users/{uid}` inside a transaction\n * that writes nothing when one is already there — the first write wins, and\n * a retry, a second tab or a later call can never restate it.\n *\n * The rules deny the field to every client, so this Admin SDK write is the\n * only way in. `createOrganization` copies it onto the workspace the account\n * creates.\n */\n\n/**\n * How long after an account is created its door may still record where it\n * came from. A door calls within seconds of creating the account; a mobile\n * redirect or a slow verification page within minutes. Anything later is not\n * account creation, and a record written then would describe a later visit.\n */\nexport const ACCOUNT_ACQUISITION_WINDOW_MS = 30 * 60 * 1000\n\n/** What a door knows when it records an account. */\nexport interface RecordAccountAcquisitionInput {\n uid: string\n /** When the auth record says the account was created; null refuses. */\n accountCreatedAtMs: number | null\n /** The first touch the device kept — untrusted. */\n touch: unknown\n door: AcquisitionDoor\n /** From the verified token's `sign_in_provider`. */\n provider: string | null\n /** The account's address, for the invitation check; null when it has none. */\n email: string | null\n /** The organization an invitation the door already found came from. */\n invitedToOrgId?: string | null\n /** The account-creating request's headers, for its geography. */\n headers: HeaderReader\n recordedBy: 'signup' | 'sso'\n nowMs?: number\n firestore?: FirebaseFirestore.Firestore\n}\n\nexport type RecordAccountAcquisitionResult =\n | { status: 'recorded'; record: AccountAcquisition }\n | { status: 'exists'; record: AccountAcquisition | null }\n /** The account was not created just now, so this is not its creation. */\n | { status: 'not-new' }\n\n/**\n * The organization whose invitation this address has waiting, or null. The\n * same query the console's invitation banner runs, one address wide.\n */\nexport async function pendingInvitationOrgId(\n email: string | null,\n firestore: FirebaseFirestore.Firestore = firebaseAdmin.app().firestore(),\n): Promise<string | null> {\n const address = String(email ?? '').trim().toLowerCase()\n if (!address) return null\n try {\n const snapshot = await firestore\n .collectionGroup('invites')\n .where('email', 'in', [address])\n .where('acceptedAt', '==', null)\n .limit(1)\n .get()\n return snapshot.docs[0]?.ref.parent.parent?.id ?? null\n } catch (error) {\n // An unanswerable question costs the door's label, never the record.\n console.error('[account-acquisition] invitation lookup failed', error)\n return null\n }\n}\n\n/** Where the request came from, as a person reads it — no address, no coordinates. */\nexport function requestGeography(headers: HeaderReader): {\n country: string | null\n region: string | null\n city: string | null\n} {\n return {\n country: readRequestGeo(headers).country,\n region: readRequestRegionLabel(headers),\n city: readRequestCity(headers),\n }\n}\n\n/** Record the account's acquisition unless it already has one. */\nexport async function recordAccountAcquisition(\n input: RecordAccountAcquisitionInput,\n): Promise<RecordAccountAcquisitionResult> {\n const firestore = input.firestore ?? firebaseAdmin.app().firestore()\n const nowMs = input.nowMs ?? Date.now()\n if (\n input.accountCreatedAtMs === null ||\n !Number.isFinite(input.accountCreatedAtMs) ||\n nowMs - input.accountCreatedAtMs > ACCOUNT_ACQUISITION_WINDOW_MS\n ) {\n return { status: 'not-new' }\n }\n const invitedToOrgId =\n input.invitedToOrgId ??\n (input.door === 'signup-password' ||\n input.door === 'signup-google' ||\n input.door === 'signup-google-redirect'\n ? await pendingInvitationOrgId(input.email, firestore)\n : null)\n const record = buildAccountAcquisition({\n touch: input.touch,\n door: invitedToOrgId && input.door !== 'sso' ? 'invite' : input.door,\n provider: input.provider,\n geo: requestGeography(input.headers),\n invitedToOrgId,\n accountCreatedAtMs: input.accountCreatedAtMs,\n recordedBy: input.recordedBy,\n nowMs,\n })\n const userRef = firestore.collection('users').doc(input.uid)\n return firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(userRef)\n const existing = snapshot.exists ? snapshot.get(ACCOUNT_ACQUISITION_FIELD) : undefined\n if (existing !== undefined && existing !== null) {\n return { status: 'exists', record: readAccountAcquisition(existing) } as const\n }\n tx.set(userRef, { [ACCOUNT_ACQUISITION_FIELD]: record }, { merge: true })\n return { status: 'recorded', record } as const\n })\n}\n\n/** What a sign-up door knows about the account it is recording. */\nexport interface RecordSignUpAcquisitionInput {\n uid: string\n /** The verified token's `sign_in_provider`. */\n provider: string | null\n /** The verified token's address. */\n email: string | null\n /** The first touch the page sent, else the request's cookie — untrusted. */\n touch: unknown\n /** Which of the provider's doors the page says it was; see `signUpDoorFor`. */\n doorHint?: unknown\n headers: HeaderReader\n nowMs?: number\n firestore?: FirebaseFirestore.Firestore\n}\n\n/**\n * Record a self-serve sign-up's acquisition, deciding from the verified\n * provider and the auth record whether there is one to record.\n *\n * Shared by the two moments a sign-up passes through: the sign-up page's own\n * call, right after the account exists, and workspace creation, which is the\n * backstop for a page torn down before its call went out — the workspace\n * copies its creator's record at birth, so that is the last moment one can\n * still reach it. Both write through {@link recordAccountAcquisition}, so the\n * first one wins and neither can restate the other; an account older than\n * the window, or one a sign-up door did not create, writes nothing.\n *\n * `null` when the provider is not a sign-up door (SSO records its own).\n */\nexport async function recordSignUpAcquisition(\n input: RecordSignUpAcquisitionInput,\n): Promise<RecordAccountAcquisitionResult | null> {\n // A `custom` token can name no door until the auth record says which\n // provider made the account (AGL-3706), so the lookup comes first for it.\n const custom = input.provider === 'custom'\n if (!custom && !signUpDoorFor(input.provider, input.doorHint)) return null\n // Across every pool, not the project's alone (AGL-1122): a lookup that\n // cannot see an account answers \"not new\", which writes nothing.\n const pooled = await findUserByUidAcrossPools(input.uid)\n const provider = signUpProviderFor(\n input.provider,\n (pooled?.record.providerData ?? []).map((info) => info.providerId),\n )\n const door = signUpDoorFor(provider, input.doorHint)\n if (!door) return null\n const createdAtMs = Date.parse(pooled?.record.metadata.creationTime ?? '')\n return recordAccountAcquisition({\n uid: input.uid,\n accountCreatedAtMs: Number.isFinite(createdAtMs) ? createdAtMs : null,\n touch: input.touch,\n door,\n provider,\n email: input.email,\n headers: input.headers,\n recordedBy: 'signup',\n nowMs: input.nowMs,\n firestore: input.firestore,\n })\n}\n"],"names":["ACCOUNT_ACQUISITION_FIELD","buildAccountAcquisition","readAccountAcquisition","signUpDoorFor","signUpProviderFor","readRequestCity","readRequestGeo","readRequestRegionLabel","findUserByUidAcrossPools","firebaseAdmin","ACCOUNT_ACQUISITION_WINDOW_MS","pendingInvitationOrgId","email","firestore","app","address","String","trim","toLowerCase","snapshot","collectionGroup","where","limit","get","docs","ref","parent","id","error","console","requestGeography","headers","country","region","city","recordAccountAcquisition","input","nowMs","Date","now","accountCreatedAtMs","Number","isFinite","status","invitedToOrgId","door","record","touch","provider","geo","recordedBy","userRef","collection","doc","uid","runTransaction","tx","existing","exists","undefined","set","merge","recordSignUpAcquisition","custom","doorHint","pooled","providerData","map","info","providerId","createdAtMs","parse","metadata","creationTime"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,yBAAyB,EACzBC,uBAAuB,EACvBC,sBAAsB,EACtBC,aAAa,EACbC,iBAAiB,QAGZ,6CAA4C;AACnD,SACEC,eAAe,EACfC,cAAc,EACd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ClC,IAAI,CAACe,UAAU,CAAC5D,cAAciC,MAAMY,QAAQ,EAAEZ,MAAM4B,QAAQ,GAAG,OAAO;IACtE,uEAAuE;IACvE,iEAAiE;IACjE,MAAMC,SAAS,MAAMzD,yBAAyB4B,MAAMkB,GAAG;IACvD,MAAMN,WAAW5C,kBACfgC,MAAMY,QAAQ,EACd,SAACiB,0BAAAA,OAAQnB,MAAM,CAACoB,YAAY,mBAAI,EAAE,EAAEC,GAAG,CAAC,CAACC,OAASA,KAAKC,UAAU;IAEnE,MAAMxB,OAAO1C,cAAc6C,UAAUZ,MAAM4B,QAAQ;IACnD,IAAI,CAACnB,MAAM,OAAO;IAClB,MAAMyB,cAAchC,KAAKiC,KAAK,UAACN,0BAAAA,OAAQnB,MAAM,CAAC0B,QAAQ,CAACC,YAAY,oBAAI;IACvE,OAAOtC,yBAAyB;QAC9BmB,KAAKlB,MAAMkB,GAAG;QACdd,oBAAoBC,OAAOC,QAAQ,CAAC4B,eAAeA,cAAc;QACjEvB,OAAOX,MAAMW,KAAK;QAClBF;QACAG;QACApC,OAAOwB,MAAMxB,KAAK;QAClBmB,SAASK,MAAML,OAAO;QACtBmB,YAAY;QACZb,OAAOD,MAAMC,KAAK;QAClBxB,WAAWuB,MAAMvB,SAAS;IAC5B;AACF"}
@@ -45,9 +45,11 @@ import type { Firestore } from 'firebase-admin/firestore';
45
45
  /** The fields an entry keeps: the resources route's `entry` allow-list. */
46
46
  export declare const CONTENT_ENTRY_DRAFT_FIELDS: readonly ["title", "slug", "excerpt", "body", "coverImage", "coverImageAlt", "coverVideo", "coverVideoDuration", "seoTitle", "seoDescription", "authorName", "categoryId", "category", "tags", "authorId"];
47
47
  /** The routes' refusal for a member who may not write the site's content. */
48
- export declare const CONTENT_DRAFT_ROLE_REFUSAL = "Editing requires the editor role";
48
+ /** Names "Edit site content" (`site.edit`, AGL-4047), never a role. */
49
+ export declare const CONTENT_DRAFT_ROLE_REFUSAL: string;
49
50
  /** The refusal for a member who may not publish it. */
50
- export declare const CONTENT_PUBLISH_ROLE_REFUSAL = "Publishing requires the publisher role";
51
+ /** Names "Publish site content" (`site.publish`, AGL-4047), never a role. */
52
+ export declare const CONTENT_PUBLISH_ROLE_REFUSAL: string;
51
53
  /** The collections route's refusal at the per-site cap. */
52
54
  export declare const CONTENT_COLLECTIONS_FULL_REFUSAL = "This site holds the maximum of 100 collections \u2014 delete one to make room";
53
55
  /** The resources route's refusal at the per-collection cap. */
@@ -18,7 +18,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
18
18
  import { COLLECTIONS_MAX_PER_HOST, ENTRIES_MAX_PER_COLLECTION } from "@aglyn/aglyn/app-utils/collection-entries";
19
19
  import { entryHasByline } from "@aglyn/aglyn/app-utils/content-authors";
20
20
  import { entryTitleSearchFields } from "@aglyn/aglyn/app-utils/content-query-fields";
21
- import { hostRoleCanPublish, hostRoleCanWrite } from "@aglyn/aglyn/app-utils/organizations";
21
+ import { holdsSiteKey, siteKeyRefusal } from "@aglyn/aglyn/app-utils/host-permissions";
22
22
  /**
23
23
  * A SITE'S POSTS WRITTEN ON A MEMBER'S BEHALF (AGL-3676).
24
24
  *
@@ -62,8 +62,8 @@ import { hostRoleCanPublish, hostRoleCanWrite } from "@aglyn/aglyn/app-utils/org
62
62
  'tags',
63
63
  'authorId'
64
64
  ];
65
- /** The routes' refusal for a member who may not write the site's content. */ export const CONTENT_DRAFT_ROLE_REFUSAL = 'Editing requires the editor role';
66
- /** The refusal for a member who may not publish it. */ export const CONTENT_PUBLISH_ROLE_REFUSAL = 'Publishing requires the publisher role';
65
+ /** The routes' refusal for a member who may not write the site's content. */ /** Names "Edit site content" (`site.edit`, AGL-4047), never a role. */ export const CONTENT_DRAFT_ROLE_REFUSAL = siteKeyRefusal('site.edit');
66
+ /** The refusal for a member who may not publish it. */ /** Names "Publish site content" (`site.publish`, AGL-4047), never a role. */ export const CONTENT_PUBLISH_ROLE_REFUSAL = siteKeyRefusal('site.publish');
67
67
  /** The collections route's refusal at the per-site cap. */ export const CONTENT_COLLECTIONS_FULL_REFUSAL = `This site holds the maximum of ${COLLECTIONS_MAX_PER_HOST} collections — delete one to make room`;
68
68
  /** The resources route's refusal at the per-collection cap. */ export const CONTENT_ENTRIES_FULL_REFUSAL = `A collection holds at most ${ENTRIES_MAX_PER_COLLECTION} entries — delete some to make room`;
69
69
  /** A collection slug the collections route accepts. */ const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
@@ -72,10 +72,6 @@ import { hostRoleCanPublish, hostRoleCanWrite } from "@aglyn/aglyn/app-utils/org
72
72
  const slug = title.normalize('NFKD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, CONTENT_ENTRY_SLUG_MAX).replace(/-+$/g, '');
73
73
  return slug || 'post';
74
74
  }
75
- function roleOf(host, uid) {
76
- var _host_get;
77
- return ((_host_get = host.get('memberRoles')) != null ? _host_get : {})[uid];
78
- }
79
75
  /**
80
76
  * The site's content collection under `id`, created when it does not exist:
81
77
  * the first of `slugs` no other content collection of the site serves, under
@@ -121,7 +117,7 @@ function roleOf(host, uid) {
121
117
  displayName: String((_existing_get1 = existing.get('displayName')) != null ? _existing_get1 : '')
122
118
  };
123
119
  }
124
- if (!hostRoleCanWrite(roleOf(host, request.uid))) return {
120
+ if (!holdsSiteKey(host, request.uid, 'site.edit')) return {
125
121
  ok: false,
126
122
  status: 403,
127
123
  error: CONTENT_DRAFT_ROLE_REFUSAL
@@ -207,7 +203,7 @@ function roleOf(host, uid) {
207
203
  error: 'Unknown collections document'
208
204
  };
209
205
  }
210
- if (!hostRoleCanWrite(roleOf(host, request.uid))) return {
206
+ if (!holdsSiteKey(host, request.uid, 'site.edit')) return {
211
207
  ok: false,
212
208
  status: 403,
213
209
  error: CONTENT_DRAFT_ROLE_REFUSAL
@@ -257,7 +253,7 @@ export const CONTENT_PUBLISH_GONE = 'It was deleted before it could be published
257
253
  status: 404,
258
254
  error: 'Unknown site'
259
255
  };
260
- if (!hostRoleCanPublish(roleOf(host, request.uid))) return {
256
+ if (!holdsSiteKey(host, request.uid, 'site.publish')) return {
261
257
  ok: false,
262
258
  status: 403,
263
259
  error: CONTENT_PUBLISH_ROLE_REFUSAL
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/content-entry-drafts.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { hostCollectionKind } from '@aglyn/aglyn/app-utils/collection-kind'\nimport {\n COLLECTIONS_MAX_PER_HOST,\n ENTRIES_MAX_PER_COLLECTION,\n} from '@aglyn/aglyn/app-utils/collection-entries'\nimport { entryHasByline } from '@aglyn/aglyn/app-utils/content-authors'\nimport { entryTitleSearchFields } from '@aglyn/aglyn/app-utils/content-query-fields'\nimport { hostRoleCanPublish, hostRoleCanWrite } from '@aglyn/aglyn/app-utils/organizations'\nimport type { Firestore } from 'firebase-admin/firestore'\n\n/**\n * A SITE'S POSTS WRITTEN ON A MEMBER'S BEHALF (AGL-3676).\n *\n * A blog is a core content collection — `hosts/{hostId}/collections/{id}`\n * with `kind: 'content'` and a slug the tenant serves its listing at — and\n * its posts are the collection's entries. The console makes both through two\n * routes: `/api/hosts/collections` claims the slug inside a transaction and\n * holds the per-site collection cap, and `/api/hosts/resources` creates an\n * entry from its allow-list, under the per-collection cap, born a DRAFT.\n *\n * A server job that writes a site's first posts (the guided start's) needs\n * the same writes without a browser's token, so they live here, in the lib\n * both runtimes already share, under the same rules:\n *\n * - THE ROLE is the member's on the site: one who may write its content\n * creates; one who may publish publishes. Refused in the routes' words.\n * - THE SLUG of a collection is claimed per host and per kind in the\n * transaction that creates it, and the collection cap is counted there.\n * - AN ENTRY keeps only the fields the resources route's allow-list keeps,\n * is counted against `ENTRIES_MAX_PER_COLLECTION`, and is stamped\n * `status: 'draft'` with its title's search keys — never sent published.\n * - PUBLISHING is a separate act, as it is in the console: it needs the\n * publish role and a byline (`entryHasByline`), and sets `publishedAt`.\n *\n * Every write is idempotent on the id its caller chose: asked again, it\n * reports what it already wrote.\n */\n\n/** The fields an entry keeps: the resources route's `entry` allow-list. */\nexport const CONTENT_ENTRY_DRAFT_FIELDS = [\n 'title',\n 'slug',\n 'excerpt',\n 'body',\n 'coverImage',\n 'coverImageAlt',\n 'coverVideo',\n 'coverVideoDuration',\n 'seoTitle',\n 'seoDescription',\n 'authorName',\n 'categoryId',\n 'category',\n 'tags',\n 'authorId',\n] as const\n\n/** The routes' refusal for a member who may not write the site's content. */\nexport const CONTENT_DRAFT_ROLE_REFUSAL = 'Editing requires the editor role'\n/** The refusal for a member who may not publish it. */\nexport const CONTENT_PUBLISH_ROLE_REFUSAL = 'Publishing requires the publisher role'\n/** The collections route's refusal at the per-site cap. */\nexport const CONTENT_COLLECTIONS_FULL_REFUSAL =\n `This site holds the maximum of ${COLLECTIONS_MAX_PER_HOST} collections — delete one to make room`\n/** The resources route's refusal at the per-collection cap. */\nexport const CONTENT_ENTRIES_FULL_REFUSAL =\n `A collection holds at most ${ENTRIES_MAX_PER_COLLECTION} entries — delete some to make room`\n\n/** A collection slug the collections route accepts. */\nconst SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/\n\n/** The longest entry slug this writer mints from a title. */\nexport const CONTENT_ENTRY_SLUG_MAX = 80\n\n/** A title as an entry slug: lowercase words joined by dashes. */\nexport function contentEntrySlug(title: string): string {\n const slug = title\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, CONTENT_ENTRY_SLUG_MAX)\n .replace(/-+$/g, '')\n return slug || 'post'\n}\n\nexport type ContentDraftRefusal = { ok: false; status: 400 | 403 | 404 | 409; error: string }\n\nexport type ContentCollectionWrite =\n | { ok: true; id: string; slug: string; displayName: string; replayed: boolean }\n | ContentDraftRefusal\n\nexport type ContentEntryWrite =\n | { ok: true; id: string; slug: string; title: string; replayed: boolean }\n | ContentDraftRefusal\n\nfunction roleOf(host: FirebaseFirestore.DocumentSnapshot, uid: string): unknown {\n return (host.get('memberRoles') ?? {})[uid]\n}\n\n/**\n * The site's content collection under `id`, created when it does not exist:\n * the first of `slugs` no other content collection of the site serves, under\n * the collection cap. Refused for a member who may not write the site, or\n * when every slug is taken.\n */\nexport async function writeContentCollection(\n firestore: Firestore,\n request: { hostId: string; uid: string; id: string; displayName: string; slugs: readonly string[]; now: Date },\n): Promise<ContentCollectionWrite> {\n const slugs = [...new Set(request.slugs.map((slug) => slug.trim().toLowerCase()))].filter((slug) => SLUG.test(slug))\n if (!slugs.length) return { ok: false, status: 400, error: 'Slug must be lowercase letters, numbers, and dashes' }\n const hostRef = firestore.collection('hosts').doc(request.hostId)\n const collections = hostRef.collection('collections')\n const ref = collections.doc(request.id)\n return firestore.runTransaction(async (tx): Promise<ContentCollectionWrite> => {\n // Every read before the write, which Firestore requires.\n const [host, existing] = await Promise.all([tx.get(hostRef), tx.get(ref)])\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n if (existing.exists) {\n if (hostCollectionKind(existing.data()) !== 'content') {\n return { ok: false, status: 409, error: 'That collection belongs to a different part of the console' }\n }\n return {\n ok: true,\n replayed: true,\n id: existing.id,\n slug: String(existing.get('slug') ?? ''),\n displayName: String(existing.get('displayName') ?? ''),\n }\n }\n if (!hostRoleCanWrite(roleOf(host, request.uid))) return { ok: false, status: 403, error: CONTENT_DRAFT_ROLE_REFUSAL }\n const held = await tx.get(collections.where('slug', 'in', slugs.slice(0, 10)))\n const taken = new Set(\n held.docs.filter((doc) => hostCollectionKind(doc.data()) === 'content').map((doc) => String(doc.get('slug'))),\n )\n const slug = slugs.find((candidate) => !taken.has(candidate))\n if (!slug) return { ok: false, status: 409, error: `Another collection already serves /${slugs[0]}` }\n const count = (await tx.get(collections.count())).data().count\n if (count >= COLLECTIONS_MAX_PER_HOST) return { ok: false, status: 403, error: CONTENT_COLLECTIONS_FULL_REFUSAL }\n tx.create(ref, { displayName: request.displayName, slug, kind: 'content', createdAt: request.now })\n return { ok: true, replayed: false, id: request.id, slug, displayName: request.displayName }\n })\n}\n\n/**\n * One draft entry of a content collection under `id`: the allow-listed\n * fields of `content`, a slug no other entry of the collection holds (from\n * the title when none is given), `status: 'draft'`, its title's search keys\n * and its author. Never published here.\n */\nexport async function writeContentEntryDraft(\n firestore: Firestore,\n request: {\n hostId: string\n collectionId: string\n uid: string\n id: string\n content: Readonly<Record<string, unknown>>\n now: Date\n },\n): Promise<ContentEntryWrite> {\n const title = typeof request.content['title'] === 'string' ? request.content['title'].trim() : ''\n if (!title) return { ok: false, status: 400, error: 'A post needs a title' }\n const fields: Record<string, unknown> = {}\n for (const key of CONTENT_ENTRY_DRAFT_FIELDS) {\n const value = request.content[key]\n if (value !== undefined && value !== null) fields[key] = value\n }\n fields['title'] = title\n const base = contentEntrySlug(typeof fields['slug'] === 'string' && fields['slug'] ? String(fields['slug']) : title)\n const hostRef = firestore.collection('hosts').doc(request.hostId)\n const parentRef = hostRef.collection('collections').doc(request.collectionId)\n const entries = parentRef.collection('entries')\n const ref = entries.doc(request.id)\n return firestore.runTransaction(async (tx): Promise<ContentEntryWrite> => {\n const [host, parent, existing] = await Promise.all([tx.get(hostRef), tx.get(parentRef), tx.get(ref)])\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n if (existing.exists) {\n return {\n ok: true,\n replayed: true,\n id: existing.id,\n slug: String(existing.get('slug') ?? ''),\n title: String(existing.get('title') ?? ''),\n }\n }\n if (!parent.exists || hostCollectionKind(parent.data()) !== 'content') {\n return { ok: false, status: 404, error: 'Unknown collections document' }\n }\n if (!hostRoleCanWrite(roleOf(host, request.uid))) return { ok: false, status: 403, error: CONTENT_DRAFT_ROLE_REFUSAL }\n const candidates = Array.from({ length: 10 }, (_, index) => (index === 0 ? base : `${base}-${index + 1}`))\n const held = new Set((await tx.get(entries.where('slug', 'in', candidates))).docs.map((doc) => String(doc.get('slug'))))\n const slug = candidates.find((candidate) => !held.has(candidate)) ?? `${base}-${request.id.slice(0, 8).toLowerCase()}`\n const count = (await tx.get(entries.count())).data().count\n if (count >= ENTRIES_MAX_PER_COLLECTION) return { ok: false, status: 403, error: CONTENT_ENTRIES_FULL_REFUSAL }\n tx.create(ref, {\n ...fields,\n slug,\n // Born a draft, as the resources route stamps it (AGL-2266).\n status: 'draft',\n ...entryTitleSearchFields(title),\n createdAt: request.now,\n updatedAt: request.now,\n createdBy: request.uid,\n })\n return { ok: true, replayed: false, id: request.id, slug, title }\n })\n}\n\n/** What publishing a set of entries came to. */\nexport interface ContentEntriesPublish {\n published: string[]\n /** Entries left as they were, each with the plain sentence for why. */\n kept: Array<{ id: string; reason: string }>\n}\n\n/** The console's refusal for an entry with no byline (`ENTRY_BYLINE_REQUIRED_MESSAGE`'s sense). */\nexport const CONTENT_PUBLISH_NO_BYLINE = 'It has no author yet. Add one in Content and publish it.'\nexport const CONTENT_PUBLISH_GONE = 'It was deleted before it could be published.'\n\n/**\n * Publishes draft entries of a collection on a member's behalf, as the\n * entry editor's Publish does: `status: 'published'` and `publishedAt`, for a\n * member who may publish the site and an entry that names its byline. An\n * entry already published stays as it is; one that cannot be published is\n * kept a draft and reported. Never throws for an entry.\n */\nexport async function publishContentEntries(\n firestore: Firestore,\n request: { hostId: string; collectionId: string; uid: string; ids: readonly string[]; now: Date },\n): Promise<ContentEntriesPublish | ContentDraftRefusal> {\n const hostRef = firestore.collection('hosts').doc(request.hostId)\n const host = await hostRef.get()\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n if (!hostRoleCanPublish(roleOf(host, request.uid))) return { ok: false, status: 403, error: CONTENT_PUBLISH_ROLE_REFUSAL }\n const entries = hostRef.collection('collections').doc(request.collectionId).collection('entries')\n const result: ContentEntriesPublish = { published: [], kept: [] }\n const batch = firestore.batch()\n for (const id of new Set(request.ids)) {\n const entry = await entries.doc(id).get()\n if (!entry.exists || entry.get('deletedAt') != null) {\n result.kept.push({ id, reason: CONTENT_PUBLISH_GONE })\n continue\n }\n if (entry.get('status') === 'published') {\n result.published.push(id)\n continue\n }\n if (!entryHasByline({ authorId: entry.get('authorId'), authorName: entry.get('authorName') })) {\n result.kept.push({ id, reason: CONTENT_PUBLISH_NO_BYLINE })\n continue\n }\n batch.set(entries.doc(id), { status: 'published', publishedAt: request.now, updatedAt: request.now }, { merge: true })\n result.published.push(id)\n }\n await batch.commit()\n return result\n}\n"],"names":["hostCollectionKind","COLLECTIONS_MAX_PER_HOST","ENTRIES_MAX_PER_COLLECTION","entryHasByline","entryTitleSearchFields","hostRoleCanPublish","hostRoleCanWrite","CONTENT_ENTRY_DRAFT_FIELDS","CONTENT_DRAFT_ROLE_REFUSAL","CONTENT_PUBLISH_ROLE_REFUSAL","CONTENT_COLLECTIONS_FULL_REFUSAL","CONTENT_ENTRIES_FULL_REFUSAL","SLUG","CONTENT_ENTRY_SLUG_MAX","contentEntrySlug","title","slug","normalize","replace","toLowerCase","slice","roleOf","host","uid","get","writeContentCollection","firestore","request","slugs","Set","map","trim","filter","test","length","ok","status","error","hostRef","collection","doc","hostId","collections","ref","id","runTransaction","tx","existing","Promise","all","exists","data","replayed","String","displayName","held","where","taken","docs","find","candidate","has","count","create","kind","createdAt","now","writeContentEntryDraft","content","fields","key","value","undefined","base","parentRef","collectionId","entries","candidates","parent","Array","from","_","index","updatedAt","createdBy","CONTENT_PUBLISH_NO_BYLINE","CONTENT_PUBLISH_GONE","publishContentEntries","result","published","kept","batch","ids","entry","push","reason","authorId","authorName","set","publishedAt","merge","commit"],"mappings":";AAAA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;QACAM,MAAMO,GAAG,CAACtB,QAAQpC,GAAG,CAACI,KAAK;YAAER,QAAQ;YAAa+D,aAAaxE,QAAQuC,GAAG;YAAEiB,WAAWxD,QAAQuC,GAAG;QAAC,GAAG;YAAEkC,OAAO;QAAK;QACpHZ,OAAOC,SAAS,CAACK,IAAI,CAAClD;IACxB;IACA,MAAM+C,MAAMU,MAAM;IAClB,OAAOb;AACT"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/content-entry-drafts.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { hostCollectionKind } from '@aglyn/aglyn/app-utils/collection-kind'\nimport {\n COLLECTIONS_MAX_PER_HOST,\n ENTRIES_MAX_PER_COLLECTION,\n} from '@aglyn/aglyn/app-utils/collection-entries'\nimport { entryHasByline } from '@aglyn/aglyn/app-utils/content-authors'\nimport { entryTitleSearchFields } from '@aglyn/aglyn/app-utils/content-query-fields'\nimport { holdsSiteKey, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport type { Firestore } from 'firebase-admin/firestore'\n\n/**\n * A SITE'S POSTS WRITTEN ON A MEMBER'S BEHALF (AGL-3676).\n *\n * A blog is a core content collection — `hosts/{hostId}/collections/{id}`\n * with `kind: 'content'` and a slug the tenant serves its listing at — and\n * its posts are the collection's entries. The console makes both through two\n * routes: `/api/hosts/collections` claims the slug inside a transaction and\n * holds the per-site collection cap, and `/api/hosts/resources` creates an\n * entry from its allow-list, under the per-collection cap, born a DRAFT.\n *\n * A server job that writes a site's first posts (the guided start's) needs\n * the same writes without a browser's token, so they live here, in the lib\n * both runtimes already share, under the same rules:\n *\n * - THE ROLE is the member's on the site: one who may write its content\n * creates; one who may publish publishes. Refused in the routes' words.\n * - THE SLUG of a collection is claimed per host and per kind in the\n * transaction that creates it, and the collection cap is counted there.\n * - AN ENTRY keeps only the fields the resources route's allow-list keeps,\n * is counted against `ENTRIES_MAX_PER_COLLECTION`, and is stamped\n * `status: 'draft'` with its title's search keys — never sent published.\n * - PUBLISHING is a separate act, as it is in the console: it needs the\n * publish role and a byline (`entryHasByline`), and sets `publishedAt`.\n *\n * Every write is idempotent on the id its caller chose: asked again, it\n * reports what it already wrote.\n */\n\n/** The fields an entry keeps: the resources route's `entry` allow-list. */\nexport const CONTENT_ENTRY_DRAFT_FIELDS = [\n 'title',\n 'slug',\n 'excerpt',\n 'body',\n 'coverImage',\n 'coverImageAlt',\n 'coverVideo',\n 'coverVideoDuration',\n 'seoTitle',\n 'seoDescription',\n 'authorName',\n 'categoryId',\n 'category',\n 'tags',\n 'authorId',\n] as const\n\n/** The routes' refusal for a member who may not write the site's content. */\n/** Names \"Edit site content\" (`site.edit`, AGL-4047), never a role. */\nexport const CONTENT_DRAFT_ROLE_REFUSAL = siteKeyRefusal('site.edit')\n/** The refusal for a member who may not publish it. */\n/** Names \"Publish site content\" (`site.publish`, AGL-4047), never a role. */\nexport const CONTENT_PUBLISH_ROLE_REFUSAL = siteKeyRefusal('site.publish')\n/** The collections route's refusal at the per-site cap. */\nexport const CONTENT_COLLECTIONS_FULL_REFUSAL =\n `This site holds the maximum of ${COLLECTIONS_MAX_PER_HOST} collections — delete one to make room`\n/** The resources route's refusal at the per-collection cap. */\nexport const CONTENT_ENTRIES_FULL_REFUSAL =\n `A collection holds at most ${ENTRIES_MAX_PER_COLLECTION} entries — delete some to make room`\n\n/** A collection slug the collections route accepts. */\nconst SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/\n\n/** The longest entry slug this writer mints from a title. */\nexport const CONTENT_ENTRY_SLUG_MAX = 80\n\n/** A title as an entry slug: lowercase words joined by dashes. */\nexport function contentEntrySlug(title: string): string {\n const slug = title\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, CONTENT_ENTRY_SLUG_MAX)\n .replace(/-+$/g, '')\n return slug || 'post'\n}\n\nexport type ContentDraftRefusal = { ok: false; status: 400 | 403 | 404 | 409; error: string }\n\nexport type ContentCollectionWrite =\n | { ok: true; id: string; slug: string; displayName: string; replayed: boolean }\n | ContentDraftRefusal\n\nexport type ContentEntryWrite =\n | { ok: true; id: string; slug: string; title: string; replayed: boolean }\n | ContentDraftRefusal\n\n\n/**\n * The site's content collection under `id`, created when it does not exist:\n * the first of `slugs` no other content collection of the site serves, under\n * the collection cap. Refused for a member who may not write the site, or\n * when every slug is taken.\n */\nexport async function writeContentCollection(\n firestore: Firestore,\n request: { hostId: string; uid: string; id: string; displayName: string; slugs: readonly string[]; now: Date },\n): Promise<ContentCollectionWrite> {\n const slugs = [...new Set(request.slugs.map((slug) => slug.trim().toLowerCase()))].filter((slug) => SLUG.test(slug))\n if (!slugs.length) return { ok: false, status: 400, error: 'Slug must be lowercase letters, numbers, and dashes' }\n const hostRef = firestore.collection('hosts').doc(request.hostId)\n const collections = hostRef.collection('collections')\n const ref = collections.doc(request.id)\n return firestore.runTransaction(async (tx): Promise<ContentCollectionWrite> => {\n // Every read before the write, which Firestore requires.\n const [host, existing] = await Promise.all([tx.get(hostRef), tx.get(ref)])\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n if (existing.exists) {\n if (hostCollectionKind(existing.data()) !== 'content') {\n return { ok: false, status: 409, error: 'That collection belongs to a different part of the console' }\n }\n return {\n ok: true,\n replayed: true,\n id: existing.id,\n slug: String(existing.get('slug') ?? ''),\n displayName: String(existing.get('displayName') ?? ''),\n }\n }\n if (!holdsSiteKey(host, request.uid, 'site.edit')) return { ok: false, status: 403, error: CONTENT_DRAFT_ROLE_REFUSAL }\n const held = await tx.get(collections.where('slug', 'in', slugs.slice(0, 10)))\n const taken = new Set(\n held.docs.filter((doc) => hostCollectionKind(doc.data()) === 'content').map((doc) => String(doc.get('slug'))),\n )\n const slug = slugs.find((candidate) => !taken.has(candidate))\n if (!slug) return { ok: false, status: 409, error: `Another collection already serves /${slugs[0]}` }\n const count = (await tx.get(collections.count())).data().count\n if (count >= COLLECTIONS_MAX_PER_HOST) return { ok: false, status: 403, error: CONTENT_COLLECTIONS_FULL_REFUSAL }\n tx.create(ref, { displayName: request.displayName, slug, kind: 'content', createdAt: request.now })\n return { ok: true, replayed: false, id: request.id, slug, displayName: request.displayName }\n })\n}\n\n/**\n * One draft entry of a content collection under `id`: the allow-listed\n * fields of `content`, a slug no other entry of the collection holds (from\n * the title when none is given), `status: 'draft'`, its title's search keys\n * and its author. Never published here.\n */\nexport async function writeContentEntryDraft(\n firestore: Firestore,\n request: {\n hostId: string\n collectionId: string\n uid: string\n id: string\n content: Readonly<Record<string, unknown>>\n now: Date\n },\n): Promise<ContentEntryWrite> {\n const title = typeof request.content['title'] === 'string' ? request.content['title'].trim() : ''\n if (!title) return { ok: false, status: 400, error: 'A post needs a title' }\n const fields: Record<string, unknown> = {}\n for (const key of CONTENT_ENTRY_DRAFT_FIELDS) {\n const value = request.content[key]\n if (value !== undefined && value !== null) fields[key] = value\n }\n fields['title'] = title\n const base = contentEntrySlug(typeof fields['slug'] === 'string' && fields['slug'] ? String(fields['slug']) : title)\n const hostRef = firestore.collection('hosts').doc(request.hostId)\n const parentRef = hostRef.collection('collections').doc(request.collectionId)\n const entries = parentRef.collection('entries')\n const ref = entries.doc(request.id)\n return firestore.runTransaction(async (tx): Promise<ContentEntryWrite> => {\n const [host, parent, existing] = await Promise.all([tx.get(hostRef), tx.get(parentRef), tx.get(ref)])\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n if (existing.exists) {\n return {\n ok: true,\n replayed: true,\n id: existing.id,\n slug: String(existing.get('slug') ?? ''),\n title: String(existing.get('title') ?? ''),\n }\n }\n if (!parent.exists || hostCollectionKind(parent.data()) !== 'content') {\n return { ok: false, status: 404, error: 'Unknown collections document' }\n }\n if (!holdsSiteKey(host, request.uid, 'site.edit')) return { ok: false, status: 403, error: CONTENT_DRAFT_ROLE_REFUSAL }\n const candidates = Array.from({ length: 10 }, (_, index) => (index === 0 ? base : `${base}-${index + 1}`))\n const held = new Set((await tx.get(entries.where('slug', 'in', candidates))).docs.map((doc) => String(doc.get('slug'))))\n const slug = candidates.find((candidate) => !held.has(candidate)) ?? `${base}-${request.id.slice(0, 8).toLowerCase()}`\n const count = (await tx.get(entries.count())).data().count\n if (count >= ENTRIES_MAX_PER_COLLECTION) return { ok: false, status: 403, error: CONTENT_ENTRIES_FULL_REFUSAL }\n tx.create(ref, {\n ...fields,\n slug,\n // Born a draft, as the resources route stamps it (AGL-2266).\n status: 'draft',\n ...entryTitleSearchFields(title),\n createdAt: request.now,\n updatedAt: request.now,\n createdBy: request.uid,\n })\n return { ok: true, replayed: false, id: request.id, slug, title }\n })\n}\n\n/** What publishing a set of entries came to. */\nexport interface ContentEntriesPublish {\n published: string[]\n /** Entries left as they were, each with the plain sentence for why. */\n kept: Array<{ id: string; reason: string }>\n}\n\n/** The console's refusal for an entry with no byline (`ENTRY_BYLINE_REQUIRED_MESSAGE`'s sense). */\nexport const CONTENT_PUBLISH_NO_BYLINE = 'It has no author yet. Add one in Content and publish it.'\nexport const CONTENT_PUBLISH_GONE = 'It was deleted before it could be published.'\n\n/**\n * Publishes draft entries of a collection on a member's behalf, as the\n * entry editor's Publish does: `status: 'published'` and `publishedAt`, for a\n * member who may publish the site and an entry that names its byline. An\n * entry already published stays as it is; one that cannot be published is\n * kept a draft and reported. Never throws for an entry.\n */\nexport async function publishContentEntries(\n firestore: Firestore,\n request: { hostId: string; collectionId: string; uid: string; ids: readonly string[]; now: Date },\n): Promise<ContentEntriesPublish | ContentDraftRefusal> {\n const hostRef = firestore.collection('hosts').doc(request.hostId)\n const host = await hostRef.get()\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n if (!holdsSiteKey(host, request.uid, 'site.publish')) return { ok: false, status: 403, error: CONTENT_PUBLISH_ROLE_REFUSAL }\n const entries = hostRef.collection('collections').doc(request.collectionId).collection('entries')\n const result: ContentEntriesPublish = { published: [], kept: [] }\n const batch = firestore.batch()\n for (const id of new Set(request.ids)) {\n const entry = await entries.doc(id).get()\n if (!entry.exists || entry.get('deletedAt') != null) {\n result.kept.push({ id, reason: CONTENT_PUBLISH_GONE })\n continue\n }\n if (entry.get('status') === 'published') {\n result.published.push(id)\n continue\n }\n if (!entryHasByline({ authorId: entry.get('authorId'), authorName: entry.get('authorName') })) {\n result.kept.push({ id, reason: CONTENT_PUBLISH_NO_BYLINE })\n continue\n }\n batch.set(entries.doc(id), { status: 'published', publishedAt: request.now, updatedAt: request.now }, { merge: true })\n result.published.push(id)\n }\n await batch.commit()\n return result\n}\n"],"names":["hostCollectionKind","COLLECTIONS_MAX_PER_HOST","ENTRIES_MAX_PER_COLLECTION","entryHasByline","entryTitleSearchFields","holdsSiteKey","siteKeyRefusal","CONTENT_ENTRY_DRAFT_FIELDS","CONTENT_DRAFT_ROLE_REFUSAL","CONTENT_PUBLISH_ROLE_REFUSAL","CONTENT_COLLECTIONS_FULL_REFUSAL","CONTENT_ENTRIES_FULL_REFUSAL","SLUG","CONTENT_ENTRY_SLUG_MAX","contentEntrySlug","title","slug","normalize","replace","toLowerCase","slice","writeContentCollection","firestore","request","slugs","Set","map","trim","filter","test","length","ok","status","error","hostRef","collection","doc","hostId","collections","ref","id","runTransaction","tx","host","existing","Promise","all","get","exists","data","replayed","String","displayName","uid","held","where","taken","docs","find","candidate","has","count","create","kind","createdAt","now","writeContentEntryDraft","content","fields","key","value","undefined","base","parentRef","collectionId","entries","candidates","parent","Array","from","_","index","updatedAt","createdBy","CONTENT_PUBLISH_NO_BYLINE","CONTENT_PUBLISH_GONE","publishContentEntries","result","published","kept","batch","ids","entry","push","reason","authorId","authorName","set","publishedAt","merge","commit"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,yCAAwC;AAC3E,SACEC,wBAAwB,EACxBC,0BAA0B,QACrB,4CAA2C;AAClD,SAASC,cAAc,QAAQ,yCAAwC;AACvE,SAASC,sBAAsB,QAAQ,8CAA6C;AACpF,SAASC,YAAY,EAAEC,cAAc,QAAQ,0CAAyC;AAGtF;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GAED,yEAAyE,GACzE,OAAO,MAAMC,6BAA6B;IACxC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAS;AAEV,2EAA2E,GAC3E,qEAAqE,GACrE,OAAO,MAAMC,6BAA6BF,eAAe,aAAY;AACrE,qDAAqD,GACrD,2EAA2E,GAC3E,OAAO,MAAMG,+BAA+BH,eAAe,gBAAe;AAC1E,yDAAyD,GACzD,OAAO,MAAMI,mCACX,CAAC,+BAA+B,EAAET,yBAAyB,sCAAsC,CAAC,CAAA;AACpG,6DAA6D,GAC7D,OAAO,MAAMU,+BACX,CAAC,2BAA2B,EAAET,2BAA2B,mCAAmC,CAAC,CAAA;AAE/F,qDAAqD,GACrD,MAAMU,OAAO;AAEb,2DAA2D,GAC3D,OAAO,MAAMC,yBAAyB,GAAE;AAExC,gEAAgE,GAChE,OAAO,SAASC,iBAAiBC,KAAa;IAC5C,MAAMC,OAAOD,MACVE,SAAS,CAAC,QACVC,OAAO,CAAC,UAAU,IAClBC,WAAW,GACXD,OAAO,CAAC,eAAe,KACvBA,OAAO,CAAC,YAAY,IACpBE,KAAK,CAAC,GAAGP,wBACTK,OAAO,CAAC,QAAQ;IACnB,OAAOF,QAAQ;AACjB;AAaA;;;;;CAKC,GACD,OAAO,eAAeK,uBACpBC,SAAoB,EACpBC,OAA8G;IAE9G,MAAMC,QAAQ;WA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AACtB,QAAQvC,GAAG,CAACI,KAAK;YAAER,QAAQ;YAAakE,aAAa3E,QAAQ0C,GAAG;YAAEiB,WAAW3D,QAAQ0C,GAAG;QAAC,GAAG;YAAEkC,OAAO;QAAK;QACpHZ,OAAOC,SAAS,CAACK,IAAI,CAACrD;IACxB;IACA,MAAMkD,MAAMU,MAAM;IAClB,OAAOb;AACT"}
@@ -13,7 +13,7 @@
13
13
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
- */ import { hostRoleCanWrite, hostRoleFor, isOrgWideMember } from "@aglyn/aglyn/server";
16
+ */ import { holdsSiteKey, hostRoleFor, isOrgWideMember, resolveOrgPermissions, resolveSiteRolePresetPermissions, siteKeyRefusal } from "@aglyn/aglyn/server";
17
17
  import { lockdownRefusal } from "./lockdown.js";
18
18
  import { getOrgDoc } from "./organizations.js";
19
19
  import { isServerReleaseFlagOnForOrg } from "./release-flags.js";
@@ -70,7 +70,7 @@ import { isServerReleaseFlagOnForOrg } from "./release-flags.js";
70
70
  * drifts from the first. Callers that ARE the edit bar keep calling
71
71
  * {@link editAccessMintRefusal} and keep its flag.
72
72
  */ export async function hostContentEditRefusal(options) {
73
- var _membership_data, _host_get, _ref;
73
+ var _membership_data, _data, _ref;
74
74
  const { request, firestore, host, orgId, uid, staff = false } = options;
75
75
  const membership = await firestore.collection('orgs').doc(orgId).collection('members').doc(uid).get();
76
76
  if (!membership.exists) {
@@ -80,30 +80,26 @@ import { isServerReleaseFlagOnForOrg } from "./release-flags.js";
80
80
  status: 403
81
81
  });
82
82
  }
83
- // A roster row proves membership of the ORG, not reach to this host. The
84
- // roster holds site collaborators too, and one can carry the org role
85
- // `editor` with `allHosts: false` and a `hostAccess` map naming only their
86
- // own sites — so the org-role arm counts only when the member is org-wide,
87
- // exactly as the presence broker asks it (AGL-1881). Otherwise that
88
- // collaborator would be minted a token for every site in the org, and the
89
- // bar would show them another site's screens and today's traffic
90
- // (AGL-3062).
91
- //
92
- // `hostRoleFor` reads `hostAccess`/`allHosts` for this host, and
93
- // `isOrgWideMember` sits beside it for the one shape the two read
94
- // differently: a pre-`allHosts` row with no `hostAccess` is org-wide, and
95
- // `hostRoleFor` alone would lock that member out of their own sites.
83
+ // "Edit site content" (`site.edit`, AGL-4047) on THIS site decides, resolved
84
+ // fresh from the membership: its preset is the member's role on the site
85
+ // (`hostRoleFor`, so a collaborator scoped to other sites reaches nothing
86
+ // here, AGL-3062), then their custom role, their own permissions and the
87
+ // site's toggle for them. A workspace editor given Viewer access to this
88
+ // site is refused unless the site grants them the key; an author, whose
89
+ // whole purpose is to be in the editor, holds it. What they cannot do once
90
+ // inside is enforced by the rules on the publish fields.
96
91
  const member = (_membership_data = membership.data()) != null ? _membership_data : {};
97
- const orgRole = member.role;
98
- const hostRole = ((_host_get = host.get('memberRoles')) != null ? _host_get : {})[uid];
99
- // `author` (AGL-2334) — the edit-bar entry token. Same reasoning as the
100
- // presence broker: this buys entry to the editor, and an author's whole
101
- // purpose is to be in it. What they cannot do once inside is enforced by
102
- // the rules on the publish fields.
103
- const canEdit = hostRoleCanWrite(hostRole) || hostRoleCanWrite(hostRoleFor(member, host.id)) || isOrgWideMember(member) && (orgRole === 'owner' || orgRole === 'admin' || orgRole === 'editor');
92
+ const customRole = member.roleId ? (_data = (await firestore.collection('orgs').doc(orgId).collection('roles').doc(member.roleId).get()).data()) != null ? _data : null : null;
93
+ // Beside it, two arms that keep every member who reached the editor before
94
+ // in it, both on the key: the site's own stamp (a grant the host's
95
+ // `memberRoles` carries), and, for a workspace member the site role cannot
96
+ // place at all (the legacy row with neither `allHosts` nor `hostAccess`,
97
+ // which `isOrgWideMember` reads as workspace-wide so it is not locked out of
98
+ // its own workspace), their workspace verdict for the key.
99
+ const canEdit = holdsSiteKey(host, uid, 'site.edit') || resolveSiteRolePresetPermissions(member, host.id, customRole)['site.edit'] === true || isOrgWideMember(member) && !hostRoleFor(member, host.id) && resolveOrgPermissions(member, customRole)['site.edit'] === true;
104
100
  if (!canEdit) {
105
101
  return Response.json({
106
- error: 'No edit access'
102
+ error: siteKeyRefusal('site.edit')
107
103
  }, {
108
104
  status: 403
109
105
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/edit-access-authz.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type AglynOrgMember,\n hostRoleCanWrite,\n hostRoleFor,\n isOrgWideMember,\n} from '@aglyn/aglyn/server'\nimport type { DocumentSnapshot, Firestore } from 'firebase-admin/firestore'\nimport { lockdownRefusal } from './lockdown'\nimport { getOrgDoc } from './organizations'\nimport { isServerReleaseFlagOnForOrg } from './release-flags'\n\n/**\n * THE authorization gate for minting an edit-access token — extracted\n * verbatim from the console's `/api/edit-access/token` (AGL-1302 follow-on)\n * so the tenant's `/api/edit-access/exchange` (AGL-1842) evaluates the SAME\n * question the same way, rather than growing a second authorization path\n * that would drift from the first.\n *\n * The gate, in order:\n *\n * 1. `release_edit_bar` for the host's org — on for every site since its\n * release (AGL-3041), and the kill switch for the whole surface, for\n * everyone or for one org by staff override;\n * 2. org roster membership — proven against the host the CALLER was already\n * resolved to, never a caller-supplied orgId;\n * 3. the co-editing edit gate the presence broker applies, for THIS host: a\n * host role that may write content (admin, editor or author), from the\n * host's `memberRoles` or the member's own `hostAccess`, or an org role\n * above viewer held org-wide (AGL-3062). A viewer gets a plain 403 rather\n * than a read-only bar;\n * 4. the lockdown verdict (AGL-1506) at `intent: 'write'` — the reasoning\n * for `write` on a stateless mint is recorded at length where this code\n * came from and holds unchanged: the token buys entry to an editor whose\n * saves a read-only lock denies, and it outlives this check by its TTL.\n *\n * Returns the refusal Response to send, or `null` when the uid may edit the\n * host. Callers verify WHO the uid is first (a Firebase ID token at the\n * console, a signed hint at the tenant exchange) — identity is the caller's\n * business; permission is this function's.\n */\nexport async function editAccessMintRefusal(options: {\n request: Request\n firestore: Firestore\n /** The `hosts/{hostId}` snapshot, already confirmed to exist. */\n host: DocumentSnapshot\n orgId: string\n uid: string\n /** From verified ID-token claims; a hint carries none, so it stays false. */\n staff?: boolean\n}): Promise<Response | null> {\n if (!(await isServerReleaseFlagOnForOrg('release_edit_bar', options.orgId))) {\n return Response.json({ error: 'Not available' }, { status: 404 })\n }\n return hostContentEditRefusal(options)\n}\n\n/**\n * Steps 2–4 of the gate above, WITHOUT the edit-bar release flag (AGL-3205).\n *\n * \"May this uid edit this host's content?\" is a question more than one feature\n * asks. The live-site preview of an unpublished entry asks it — the link it\n * mints reveals a post the public cannot see, so the person asking for one has\n * to be someone who could have published it — and it is emphatically NOT the\n * edit bar: `release_edit_bar` is that surface's kill switch, and a preview\n * link has no business disappearing when somebody turns the bar off.\n *\n * Split rather than copied, for the reason this module exists at all: the\n * whole note above is about not growing a second authorization path that\n * drifts from the first. Callers that ARE the edit bar keep calling\n * {@link editAccessMintRefusal} and keep its flag.\n */\nexport async function hostContentEditRefusal(options: {\n request: Request\n firestore: Firestore\n /** The `hosts/{hostId}` snapshot, already confirmed to exist. */\n host: DocumentSnapshot\n orgId: string\n uid: string\n /** From verified ID-token claims; a hint carries none, so it stays false. */\n staff?: boolean\n}): Promise<Response | null> {\n const { request, firestore, host, orgId, uid, staff = false } = options\n\n const membership = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .doc(uid)\n .get()\n if (!membership.exists) {\n return Response.json({ error: 'Not a member of this site' }, { status: 403 })\n }\n\n // A roster row proves membership of the ORG, not reach to this host. The\n // roster holds site collaborators too, and one can carry the org role\n // `editor` with `allHosts: false` and a `hostAccess` map naming only their\n // own sites — so the org-role arm counts only when the member is org-wide,\n // exactly as the presence broker asks it (AGL-1881). Otherwise that\n // collaborator would be minted a token for every site in the org, and the\n // bar would show them another site's screens and today's traffic\n // (AGL-3062).\n //\n // `hostRoleFor` reads `hostAccess`/`allHosts` for this host, and\n // `isOrgWideMember` sits beside it for the one shape the two read\n // differently: a pre-`allHosts` row with no `hostAccess` is org-wide, and\n // `hostRoleFor` alone would lock that member out of their own sites.\n const member = (membership.data() ?? {}) as Partial<AglynOrgMember>\n const orgRole = member.role\n const hostRole = ((host.get('memberRoles') ?? {}) as Record<string, string>)[\n uid\n ]\n // `author` (AGL-2334) — the edit-bar entry token. Same reasoning as the\n // presence broker: this buys entry to the editor, and an author's whole\n // purpose is to be in it. What they cannot do once inside is enforced by\n // the rules on the publish fields.\n const canEdit =\n hostRoleCanWrite(hostRole) ||\n hostRoleCanWrite(hostRoleFor(member, host.id)) ||\n (isOrgWideMember(member) &&\n (orgRole === 'owner' || orgRole === 'admin' || orgRole === 'editor'))\n if (!canEdit) {\n return Response.json({ error: 'No edit access' }, { status: 403 })\n }\n\n // Host doc already in hand; the org scope rides the member doc's\n // `orgSuspended` projection (also already read) — the org doc is fetched\n // only when the projection trips, so the happy path adds no org read.\n return lockdownRefusal({\n request,\n intent: 'write',\n staff,\n uid,\n org:\n membership.get('orgSuspended') === true\n ? ((await getOrgDoc(orgId)) ?? {})\n : undefined,\n host: host.data(),\n })\n}\n"],"names":["hostRoleCanWrite","hostRoleFor","isOrgWideMember","lockdownRefusal","getOrgDoc","isServerReleaseFlagOnForOrg","editAccessMintRefusal","options","orgId","Response","json","error","status","hostContentEditRefusal","membership","host","request","firestore","uid","staff","collection","doc","get","exists","member","data","orgRole","role","hostRole","canEdit","id","intent","org","undefined"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,gBAAgB,EAChBC,WAAW,EACXC,eAAe,QACV,sBAAqB;AAE5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,MAAMW,UACJ7B,iBAAiB4B,aACjB5B,iBAAiBC,YAAYuB,QAAQT,KAAKe,EAAE,MAC3C5B,gBAAgBsB,WACdE,CAAAA,YAAY,WAAWA,YAAY,WAAWA,YAAY,QAAO;IACtE,IAAI,CAACG,SAAS;QACZ,OAAOpB,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAiB,GAAG;YAAEC,QAAQ;QAAI;IAClE;IAEA,iEAAiE;IACjE,yEAAyE;IACzE,sEAAsE;IACtE,OAAOT,gBAAgB;QACrBa;QACAe,QAAQ;QACRZ;QACAD;QACAc,KACElB,WAAWQ,GAAG,CAAC,oBAAoB,QAC7B,OAAA,MAAMlB,UAAUI,kBAAhB,OAA2B,CAAC,IAC9ByB;QACNlB,MAAMA,KAAKU,IAAI;IACjB;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/edit-access-authz.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type AglynOrgMember,\n holdsSiteKey,\n hostRoleFor,\n isOrgWideMember,\n resolveOrgPermissions,\n resolveSiteRolePresetPermissions,\n siteKeyRefusal,\n} from '@aglyn/aglyn/server'\nimport type { DocumentSnapshot, Firestore } from 'firebase-admin/firestore'\nimport { lockdownRefusal } from './lockdown'\nimport { getOrgDoc } from './organizations'\nimport { isServerReleaseFlagOnForOrg } from './release-flags'\n\n/**\n * THE authorization gate for minting an edit-access token — extracted\n * verbatim from the console's `/api/edit-access/token` (AGL-1302 follow-on)\n * so the tenant's `/api/edit-access/exchange` (AGL-1842) evaluates the SAME\n * question the same way, rather than growing a second authorization path\n * that would drift from the first.\n *\n * The gate, in order:\n *\n * 1. `release_edit_bar` for the host's org — on for every site since its\n * release (AGL-3041), and the kill switch for the whole surface, for\n * everyone or for one org by staff override;\n * 2. org roster membership — proven against the host the CALLER was already\n * resolved to, never a caller-supplied orgId;\n * 3. the co-editing edit gate the presence broker applies, for THIS host: a\n * host role that may write content (admin, editor or author), from the\n * host's `memberRoles` or the member's own `hostAccess`, or an org role\n * above viewer held org-wide (AGL-3062). A viewer gets a plain 403 rather\n * than a read-only bar;\n * 4. the lockdown verdict (AGL-1506) at `intent: 'write'` — the reasoning\n * for `write` on a stateless mint is recorded at length where this code\n * came from and holds unchanged: the token buys entry to an editor whose\n * saves a read-only lock denies, and it outlives this check by its TTL.\n *\n * Returns the refusal Response to send, or `null` when the uid may edit the\n * host. Callers verify WHO the uid is first (a Firebase ID token at the\n * console, a signed hint at the tenant exchange) — identity is the caller's\n * business; permission is this function's.\n */\nexport async function editAccessMintRefusal(options: {\n request: Request\n firestore: Firestore\n /** The `hosts/{hostId}` snapshot, already confirmed to exist. */\n host: DocumentSnapshot\n orgId: string\n uid: string\n /** From verified ID-token claims; a hint carries none, so it stays false. */\n staff?: boolean\n}): Promise<Response | null> {\n if (!(await isServerReleaseFlagOnForOrg('release_edit_bar', options.orgId))) {\n return Response.json({ error: 'Not available' }, { status: 404 })\n }\n return hostContentEditRefusal(options)\n}\n\n/**\n * Steps 2–4 of the gate above, WITHOUT the edit-bar release flag (AGL-3205).\n *\n * \"May this uid edit this host's content?\" is a question more than one feature\n * asks. The live-site preview of an unpublished entry asks it — the link it\n * mints reveals a post the public cannot see, so the person asking for one has\n * to be someone who could have published it — and it is emphatically NOT the\n * edit bar: `release_edit_bar` is that surface's kill switch, and a preview\n * link has no business disappearing when somebody turns the bar off.\n *\n * Split rather than copied, for the reason this module exists at all: the\n * whole note above is about not growing a second authorization path that\n * drifts from the first. Callers that ARE the edit bar keep calling\n * {@link editAccessMintRefusal} and keep its flag.\n */\nexport async function hostContentEditRefusal(options: {\n request: Request\n firestore: Firestore\n /** The `hosts/{hostId}` snapshot, already confirmed to exist. */\n host: DocumentSnapshot\n orgId: string\n uid: string\n /** From verified ID-token claims; a hint carries none, so it stays false. */\n staff?: boolean\n}): Promise<Response | null> {\n const { request, firestore, host, orgId, uid, staff = false } = options\n\n const membership = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .doc(uid)\n .get()\n if (!membership.exists) {\n return Response.json({ error: 'Not a member of this site' }, { status: 403 })\n }\n\n // \"Edit site content\" (`site.edit`, AGL-4047) on THIS site decides, resolved\n // fresh from the membership: its preset is the member's role on the site\n // (`hostRoleFor`, so a collaborator scoped to other sites reaches nothing\n // here, AGL-3062), then their custom role, their own permissions and the\n // site's toggle for them. A workspace editor given Viewer access to this\n // site is refused unless the site grants them the key; an author, whose\n // whole purpose is to be in the editor, holds it. What they cannot do once\n // inside is enforced by the rules on the publish fields.\n const member = (membership.data() ?? {}) as Partial<AglynOrgMember> & { roleId?: string }\n const customRole = member.roleId\n ? ((await firestore.collection('orgs').doc(orgId).collection('roles').doc(member.roleId).get()).data() ?? null)\n : null\n // Beside it, two arms that keep every member who reached the editor before\n // in it, both on the key: the site's own stamp (a grant the host's\n // `memberRoles` carries), and, for a workspace member the site role cannot\n // place at all (the legacy row with neither `allHosts` nor `hostAccess`,\n // which `isOrgWideMember` reads as workspace-wide so it is not locked out of\n // its own workspace), their workspace verdict for the key.\n const canEdit =\n holdsSiteKey(host, uid, 'site.edit') ||\n resolveSiteRolePresetPermissions(member, host.id, customRole)['site.edit'] === true ||\n (isOrgWideMember(member) && !hostRoleFor(member, host.id) && resolveOrgPermissions(member, customRole)['site.edit'] === true)\n if (!canEdit) {\n return Response.json({ error: siteKeyRefusal('site.edit') }, { status: 403 })\n }\n\n // Host doc already in hand; the org scope rides the member doc's\n // `orgSuspended` projection (also already read) — the org doc is fetched\n // only when the projection trips, so the happy path adds no org read.\n return lockdownRefusal({\n request,\n intent: 'write',\n staff,\n uid,\n org:\n membership.get('orgSuspended') === true\n ? ((await getOrgDoc(orgId)) ?? {})\n : undefined,\n host: host.data(),\n })\n}\n"],"names":["holdsSiteKey","hostRoleFor","isOrgWideMember","resolveOrgPermissions","resolveSiteRolePresetPermissions","siteKeyRefusal","lockdownRefusal","getOrgDoc","isServerReleaseFlagOnForOrg","editAccessMintRefusal","options","orgId","Response","json","error","status","hostContentEditRefusal","membership","request","firestore","host","uid","staff","collection","doc","get","exists","member","data","customRole","roleId","canEdit","id","intent","org","undefined"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,YAAY,EACZC,WAAW,EACXC,eAAe,EACfC,qBAAqB,EACrBC,gCAAgC,EAChCC,cAAc,QACT,sBAAqB;AAE5B,SAASC,eAAe,QAAQ,gBAAY;AAC5C,SAASC,SAAS,QAAQ,qBAAiB;AAC3C,SAASC,2BAA2B,QAAQ,qBAAiB;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC,GACD,OAAO,eAAeC,sBAAsBC,OAS3C;IACC,IAAI,CAAE,MAAMF,4BAA4B,oBAAoBE,QAAQC,KAAK,GAAI;QAC3E,OAAOC,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAgB,GAAG;YAAEC,QAAQ;QAAI;IACjE;IACA,OAAOC,uBAAuBN;AAChC;AAEA;;;;;;;;;;;;;;CAcC,GACD,OAAO,eAAeM,uBAAuBN,OAS5C;QAqBiBO,kBAEX,OA0BK;IAhDV,MAAM,EAAEC,OAAO,EAAEC,SAAS,EAAEC,IAAI,EAAET,KAAK,EAAEU,GAAG,EAAEC,QAAQ,KAAK,EAAE,GAAGZ;IAEhE,MAAMO,aAAa,MAAME,UACtBI,UAAU,CAAC,QACXC,GAAG,CAACb,OACJY,UAAU,CAAC,WACXC,GAAG,CAACH,KACJI,GAAG;IACN,IAAI,CAACR,WAAWS,MAAM,EAAE;QACtB,OAAOd,SAASC,IAAI,CAAC;YAA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you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * Per-member permission overrides (AGL-4047): the writes behind the member
19
+ * Permissions section and the per-site collaborator toggles.
20
+ *
21
+ * Two places a member's own decisions live, and each write may set a key
22
+ * (`true` / `false`) or CLEAR it (`null`, back to inherit):
23
+ *
24
+ * - `permissions[key]` on `orgs/{orgId}/members/{uid}` for an org catalog
25
+ * key, layered over the org role and the custom role by
26
+ * `resolveOrgPermissions`;
27
+ * - `hostPermissions[hostId][key]` for a key a site collaborator holds per
28
+ * site, layered over their host role by `resolveCollaboratorHostPermissions`,
29
+ * and for a key that follows the site role, for a workspace-wide member
30
+ * that site narrows (AGL-4047, `narrowPermissionsToSite`);
31
+ * - `siteNarrowing[key]` on the member for a key a site can narrow: whether
32
+ * it follows a narrower site role for them (`true`) or they keep it
33
+ * (`false`), over their custom role's choice and the built-in default.
34
+ *
35
+ * Catalog keys are dotted (`billing.view`), so every write addresses the
36
+ * field through a `FieldPath` — a dotted string would be read as nesting.
37
+ * Both writes re-project before they answer: `resolvedPermissions` on the
38
+ * member and `memberPermissions` on the hosts are what the rules read, and
39
+ * a narrowing that answers 200 before it is stamped is a window in which
40
+ * the rules still grant.
41
+ */
42
+ import { type AglynOrgMember } from '@aglyn/aglyn/server';
43
+ /** A key to `true` / `false`, or to `null` to clear it. */
44
+ export type PermissionOverrideWrite = Record<string, boolean | null>;
45
+ /** A member's verdicts on either side of an override write. */
46
+ export interface PermissionOverridesResult {
47
+ before: Record<string, boolean>;
48
+ after: Record<string, boolean>;
49
+ /** The member document as it stands after the write. */
50
+ member: AglynOrgMember;
51
+ }
52
+ /**
53
+ * Sets or clears a member's org-level overrides, and their narrowing
54
+ * choices (`siteNarrowing`, AGL-4047), in one write. Keys outside the
55
+ * catalog, and narrowing for a key no site can narrow, are refused before
56
+ * anything is written (the route validates first; this is the floor). The
57
+ * member must exist. Every host is re-projected, because a narrowing choice
58
+ * moves the member's verdict on each site that narrows them.
59
+ */
60
+ export declare function setMemberPermissionOverrides(options: {
61
+ orgId: string;
62
+ uid: string;
63
+ changes: PermissionOverrideWrite;
64
+ narrowing?: PermissionOverrideWrite;
65
+ }): Promise<PermissionOverridesResult & {
66
+ siteNarrowing: Record<string, boolean>;
67
+ }>;
68
+ /**
69
+ * Sets or clears a member's per-site toggles on one site. For a site
70
+ * collaborator, only the keys a plugin declared per-site
71
+ * (`hostPermissionKeys`) are stored. For a member who works across the
72
+ * workspace, only on a site that narrows them and only the keys that follow
73
+ * the site role for them (`narrowedPermissionKeysOf`, AGL-4047): the site's
74
+ * way to give back, or keep refused, what their narrower access there took.
75
+ * The member must reach the site.
76
+ */
77
+ export declare function setHostPermissionOverrides(options: {
78
+ orgId: string;
79
+ uid: string;
80
+ hostId: string;
81
+ changes: PermissionOverrideWrite;
82
+ }): Promise<PermissionOverridesResult>;