const SHARED_DRIVE_GOVERNANCE_SCOPE = 'https://www.googleapis.com/auth/drive'; const SHARED_DRIVE_FOLDER_MIME = 'application/vnd.google-apps.folder'; const SHARED_DRIVE_SHORTCUT_MIME = 'application/vnd.google-apps.shortcut'; const AUDIT_FILE_PAGE_SIZE = 25; const AUDIT_MAX_FILE_PAGES = 2; const PERMISSION_PAGE_SIZE = 100; const MAX_PERMISSION_PAGES = 2; const TEMP_GRANT_PROPERTY_KEY = 'SHARED_DRIVE_TEMP_READER_GRANT'; const PROP_SHARED_DRIVE_ID = 'PRACTICE_SHARED_DRIVE_ID'; const PROP_FOLDER_ID = 'PRACTICE_FOLDER_ID'; const PROP_FILE_ID = 'PRACTICE_FILE_ID'; const PROP_REVIEWER_EMAIL = 'PRACTICE_REVIEWER_EMAIL'; const PROP_ORGANIZATION_DOMAIN = 'PRACTICE_ORGANIZATION_DOMAIN'; /** * @typedef {{ * sharedDriveId: string, * folderId: string | null, * fileId: string | null, * reviewerEmail: string | null, * organizationDomain: string | null * }} GovernanceConfig_ */ /** * @typedef {{ * id: string, * type: string, * role: string, * emailAddress: string | null, * domain: string | null, * origin: 'direct' | 'inherited' | 'direct_and_inherited', * hasDirectGrant: boolean, * hasInheritedGrant: boolean, * inheritedFromIds: string[], * isAnyone: boolean, * isDomain: boolean, * isExternalPrincipal: boolean * }} ClassifiedPermission_ */ /** * @typedef {{ * organizationDomain: string | null, * totalCount: number, * directOnlyCount: number, * inheritedOnlyCount: number, * directAndInheritedCount: number, * anyoneCount: number, * domainCount: number, * externalPrincipals: string[], * entries: ClassifiedPermission_[] * }} PermissionAuditSummary_ */ /** * @typedef {{ * sharedDriveId: string, * fileId: string, * reviewerEmail: string, * permissionId: string, * grantedAt: string * }} TemporaryReaderGrantRecord_ */ /** * Verifies direct vs inherited and external/anyone permission classification * on in-memory sample Permission objects without calling Drive or Properties. */ function runLocalPermissionClassifierCheck() { /** @type {Drive.Schema.Permission[]} */ const samplePermissions = [ { id: 'perm-inherited-organizer', type: 'user', role: 'organizer', emailAddress: 'dana@acme.test', permissionDetails: [ { permissionType: 'member', role: 'organizer', inherited: true, inheritedFrom: '0ASharedDriveRootTest', }, ], }, { id: 'perm-upgraded-writer', type: 'user', role: 'writer', emailAddress: 'alex@acme.test', permissionDetails: [ { permissionType: 'member', role: 'reader', inherited: true, inheritedFrom: '0ASharedDriveRootTest', }, { permissionType: 'file', role: 'writer', inherited: false, }, ], }, { id: 'perm-direct-external', type: 'user', role: 'reader', emailAddress: 'auditor@vendor.test', permissionDetails: [ { permissionType: 'file', role: 'reader', inherited: false, }, ], }, { id: 'perm-inherited-domain', type: 'domain', role: 'reader', domain: 'acme.test', allowFileDiscovery: false, permissionDetails: [ { permissionType: 'file', role: 'reader', inherited: true, inheritedFrom: '1ParentFolderTest', }, ], }, { id: 'perm-direct-anyone', type: 'anyone', role: 'reader', allowFileDiscovery: false, permissionDetails: [ { permissionType: 'file', role: 'reader', inherited: false, }, ], }, ]; const summary = classifyPermissions_(samplePermissions, 'acme.test'); if ( summary.totalCount !== 5 || summary.directOnlyCount !== 2 || summary.inheritedOnlyCount !== 2 || summary.directAndInheritedCount !== 1 || summary.anyoneCount !== 1 || summary.domainCount !== 1 || summary.externalPrincipals.length !== 1 || summary.externalPrincipals[0] !== 'auditor@vendor.test' ) { throw new Error('Local permission classifier check failed: ' + JSON.stringify(summary)); } console.log(JSON.stringify(summary, null, 2)); return summary; } /** * Audits one Shared Drive folder (and optional PRACTICE_FILE_ID) without * creating, updating, or deleting files or permissions. */ function auditSharedDriveFolderPermissions() { const config = readGovernanceProperties_(); if (!config.folderId) { throw new Error('Set Script Property ' + PROP_FOLDER_ID + ' before running the folder audit.'); } ScriptApp.requireScopes(ScriptApp.AuthMode.FULL, [SHARED_DRIVE_GOVERNANCE_SCOPE]); const folder = getVerifiedSharedDriveFolder_(config.folderId, config.sharedDriveId); const childListing = listSharedDriveFolderChildren_(config.sharedDriveId, config.folderId); const folderPermissions = listResourcePermissions_(config.folderId); const effectiveDomain = config.organizationDomain || inferSingleDomainPermission_(folderPermissions.permissions); const folderPermissionSummary = classifyPermissions_( folderPermissions.permissions, effectiveDomain, ); let targetFileAudit = null; if (config.fileId) { const file = getVerifiedSharedDriveFile_(config.fileId, config.sharedDriveId); const filePermissions = listResourcePermissions_(config.fileId); targetFileAudit = { id: String(file.id), name: String(file.name), mimeType: String(file.mimeType), canShare: Boolean(file.capabilities && file.capabilities.canShare), hasAugmentedPermissions: Boolean(file.hasAugmentedPermissions), inheritedPermissionsDisabled: Boolean(file.inheritedPermissionsDisabled), permissionPagesTruncated: filePermissions.nextPageAvailable, permissionSummary: classifyPermissions_(filePermissions.permissions, effectiveDomain), }; } const report = { sharedDriveId: config.sharedDriveId, folder: { id: String(folder.id), name: String(folder.name), canShare: Boolean(folder.capabilities && folder.capabilities.canShare), inheritedPermissionsDisabled: Boolean(folder.inheritedPermissionsDisabled), permissionPagesTruncated: folderPermissions.nextPageAvailable, permissionSummary: folderPermissionSummary, }, children: { inspectedCount: childListing.items.length, augmentedItemCount: childListing.items.filter((item) => item.hasAugmentedPermissions).length, nextPageAvailable: childListing.nextPageAvailable, items: childListing.items, }, targetFile: targetFileAudit, }; console.log(JSON.stringify(report, null, 2)); return report; } /** * Grants temporary reader access on PRACTICE_FILE_ID to PRACTICE_REVIEWER_EMAIL * without sending an email notification, and stores the permissionId under a lock. */ function grantTemporaryFileReader() { const config = readGovernanceProperties_(); if (!config.fileId) { throw new Error('Set Script Property ' + PROP_FILE_ID + ' to a disposable Shared Drive file ID.'); } if (!config.reviewerEmail) { throw new Error('Set Script Property ' + PROP_REVIEWER_EMAIL + ' to the test reviewer email address.'); } if (config.fileId === config.sharedDriveId || config.fileId === config.folderId) { throw new Error(PROP_FILE_ID + ' must identify a disposable file, not the Shared Drive or folder.'); } ScriptApp.requireScopes(ScriptApp.AuthMode.FULL, [SHARED_DRIVE_GOVERNANCE_SCOPE]); const lock = LockService.getScriptLock(); if (!lock.tryLock(5000)) { throw new Error('Another permission operation holds the script lock. Wait for it to finish.'); } try { const properties = PropertiesService.getScriptProperties(); const existingRecord = readTemporaryGrantRecord_(properties); const file = getVerifiedSharedDriveFile_(config.fileId, config.sharedDriveId); if (!file.capabilities || file.capabilities.canShare !== true) { throw new Error('The executing account cannot change permissions on PRACTICE_FILE_ID.'); } const permissionListing = listResourcePermissions_(config.fileId); if (permissionListing.nextPageAvailable) { throw new Error('PRACTICE_FILE_ID has more than ' + (PERMISSION_PAGE_SIZE * MAX_PERMISSION_PAGES) + ' permissions; use a dedicated practice file.'); } if (existingRecord !== null) { if ( existingRecord.sharedDriveId !== config.sharedDriveId || existingRecord.fileId !== config.fileId || existingRecord.reviewerEmail !== config.reviewerEmail ) { throw new Error( 'An active temporary grant is already recorded for a different file or reviewer. Run revokeTemporaryFileReader before changing Script Properties.', ); } const matching = permissionListing.permissions.find( (permission) => permission.id === existingRecord.permissionId, ); if (!matching) { throw new Error( 'Recorded permissionId ' + existingRecord.permissionId + ' is no longer present on PRACTICE_FILE_ID. Run revokeTemporaryFileReader to clear the stale record.', ); } const alreadyGranted = { status: 'already_granted', fileId: config.fileId, fileName: String(file.name), reviewerEmail: config.reviewerEmail, permissionId: existingRecord.permissionId, }; console.log(JSON.stringify(alreadyGranted, null, 2)); return alreadyGranted; } const preExisting = permissionListing.permissions.find( (permission) => typeof permission.emailAddress === 'string' && permission.emailAddress.toLowerCase() === config.reviewerEmail, ); if (preExisting) { const classified = classifySinglePermission_(preExisting, config.organizationDomain); throw new Error( 'Reviewer already holds ' + classified.origin + ' access (' + classified.role + ') on PRACTICE_FILE_ID. Choose an account without existing access so revocation cannot disturb pre-existing permissions.', ); } const created = Drive.Permissions.create( { type: 'user', role: 'reader', emailAddress: config.reviewerEmail, }, config.fileId, { supportsAllDrives: true, sendNotificationEmail: false, fields: 'id,type,role,emailAddress,permissionDetails(permissionType,role,inherited,inheritedFrom)', }, ); if (!created || typeof created.id !== 'string' || created.id.length === 0) { throw new Error('Drive.Permissions.create did not return a permission ID.'); } /** @type {TemporaryReaderGrantRecord_} */ const record = { sharedDriveId: config.sharedDriveId, fileId: config.fileId, reviewerEmail: config.reviewerEmail, permissionId: created.id, grantedAt: new Date().toISOString(), }; properties.setProperty(TEMP_GRANT_PROPERTY_KEY, JSON.stringify(record)); const result = { status: 'granted', fileId: config.fileId, fileName: String(file.name), reviewerEmail: config.reviewerEmail, permissionId: created.id, sendNotificationEmail: false, }; console.log(JSON.stringify(result, null, 2)); return result; } finally { lock.releaseLock(); } } /** * Revokes the exact permissionId recorded by grantTemporaryFileReader on * PRACTICE_FILE_ID and clears SHARED_DRIVE_TEMP_READER_GRANT. */ function revokeTemporaryFileReader() { const config = readGovernanceProperties_(); if (!config.fileId) { throw new Error('Set Script Property ' + PROP_FILE_ID + ' before revoking the temporary reader.'); } ScriptApp.requireScopes(ScriptApp.AuthMode.FULL, [SHARED_DRIVE_GOVERNANCE_SCOPE]); const lock = LockService.getScriptLock(); if (!lock.tryLock(5000)) { throw new Error('Another permission operation holds the script lock. Wait for it to finish.'); } try { const properties = PropertiesService.getScriptProperties(); const record = readTemporaryGrantRecord_(properties); if (record === null) { throw new Error( 'No temporary reader grant is recorded under ' + TEMP_GRANT_PROPERTY_KEY + '.', ); } if (record.sharedDriveId !== config.sharedDriveId || record.fileId !== config.fileId) { throw new Error( 'Current Script Properties do not match the recorded grant target (' + record.fileId + '). Restore ' + PROP_SHARED_DRIVE_ID + ' and ' + PROP_FILE_ID + ' before revoking.', ); } const file = getVerifiedSharedDriveFile_(record.fileId, record.sharedDriveId); if (!file.capabilities || file.capabilities.canShare !== true) { throw new Error('The executing account cannot change permissions on PRACTICE_FILE_ID.'); } const permissionListing = listResourcePermissions_(record.fileId); const matching = permissionListing.permissions.find( (permission) => permission.id === record.permissionId, ); if (!matching) { if (permissionListing.nextPageAvailable) { throw new Error( 'PRACTICE_FILE_ID has more than ' + PERMISSION_PAGE_SIZE * MAX_PERMISSION_PAGES + ' permissions. Revoke permissionId ' + record.permissionId + ' manually before clearing ' + TEMP_GRANT_PROPERTY_KEY + '.', ); } properties.deleteProperty(TEMP_GRANT_PROPERTY_KEY); const absentResult = { status: 'already_absent', fileId: record.fileId, fileName: String(file.name), reviewerEmail: record.reviewerEmail, permissionId: record.permissionId, }; console.log(JSON.stringify(absentResult, null, 2)); return absentResult; } const classified = classifySinglePermission_(matching, config.organizationDomain); if (classified.hasInheritedGrant) { throw new Error( 'Permission ' + record.permissionId + ' includes inherited access from ' + classified.inheritedFromIds.join(', ') + ' and cannot be deleted at the child file level.', ); } Drive.Permissions.remove(record.fileId, record.permissionId, { supportsAllDrives: true, }); properties.deleteProperty(TEMP_GRANT_PROPERTY_KEY); const revokedResult = { status: 'revoked', fileId: record.fileId, fileName: String(file.name), reviewerEmail: record.reviewerEmail, permissionId: record.permissionId, }; console.log(JSON.stringify(revokedResult, null, 2)); return revokedResult; } finally { lock.releaseLock(); } } /** * @param {string} folderId * @param {string} sharedDriveId * @returns {Drive.Schema.File} */ function getVerifiedSharedDriveFolder_(folderId, sharedDriveId) { const folder = Drive.Files.get(folderId, { supportsAllDrives: true, fields: 'kind,id,name,mimeType,trashed,driveId,inheritedPermissionsDisabled,capabilities(canListChildren,canShare)', }); if (!folder || folder.kind !== 'drive#file' || folder.id !== folderId) { throw new Error('Drive returned unexpected metadata for PRACTICE_FOLDER_ID.'); } if (folder.mimeType !== SHARED_DRIVE_FOLDER_MIME || folder.trashed !== false) { throw new Error('PRACTICE_FOLDER_ID must identify a non-trashed folder.'); } if (folder.driveId !== sharedDriveId) { throw new Error( 'PRACTICE_FOLDER_ID does not belong to PRACTICE_SHARED_DRIVE_ID. Check both IDs.', ); } if (!folder.capabilities || folder.capabilities.canListChildren !== true) { throw new Error('The executing account cannot list children of PRACTICE_FOLDER_ID.'); } return folder; } /** * @param {string} fileId * @param {string} sharedDriveId * @returns {Drive.Schema.File} */ function getVerifiedSharedDriveFile_(fileId, sharedDriveId) { const file = Drive.Files.get(fileId, { supportsAllDrives: true, fields: 'kind,id,name,mimeType,trashed,driveId,hasAugmentedPermissions,inheritedPermissionsDisabled,capabilities(canShare)', }); if (!file || file.kind !== 'drive#file' || file.id !== fileId) { throw new Error('Drive returned unexpected metadata for PRACTICE_FILE_ID.'); } if (file.trashed !== false) { throw new Error('PRACTICE_FILE_ID is in Trash. Choose an active disposable test file.'); } if (file.mimeType === SHARED_DRIVE_FOLDER_MIME || file.mimeType === SHARED_DRIVE_SHORTCUT_MIME) { throw new Error('PRACTICE_FILE_ID must identify a file, not a folder or shortcut.'); } if (file.driveId !== sharedDriveId) { throw new Error('PRACTICE_FILE_ID does not reside in PRACTICE_SHARED_DRIVE_ID.'); } return file; } /** * @param {string} sharedDriveId * @param {string} folderId */ function listSharedDriveFolderChildren_(sharedDriveId, folderId) { /** * @type {Array<{ * id: string, * name: string, * mimeType: string, * canShare: boolean, * hasAugmentedPermissions: boolean, * inheritedPermissionsDisabled: boolean * }>} */ const items = []; const seenIds = new Set(); /** @type {string | undefined} */ let pageToken; for (let pageNumber = 1; pageNumber <= AUDIT_MAX_FILE_PAGES; pageNumber += 1) { /** * @type {{ * corpora: string, * driveId: string, * includeItemsFromAllDrives: boolean, * supportsAllDrives: boolean, * spaces: string, * q: string, * orderBy: string, * pageSize: number, * fields: string, * pageToken?: string * }} */ const request = { corpora: 'drive', driveId: sharedDriveId, includeItemsFromAllDrives: true, supportsAllDrives: true, spaces: 'drive', q: "'" + folderId + "' in parents and trashed = false", orderBy: 'name_natural', pageSize: AUDIT_FILE_PAGE_SIZE, fields: 'nextPageToken,incompleteSearch,files(id,name,mimeType,hasAugmentedPermissions,inheritedPermissionsDisabled,capabilities(canShare))', }; if (pageToken) { request.pageToken = pageToken; } const response = Drive.Files.list(request); if (!response || response.incompleteSearch === true) { throw new Error('Drive reported an incomplete search while listing PRACTICE_FOLDER_ID.'); } const files = Array.isArray(response.files) ? response.files : []; files.forEach((file) => { if (!file || typeof file.id !== 'string' || typeof file.name !== 'string') { throw new Error('Drive returned a child entry without id or name.'); } if (seenIds.has(file.id)) return; seenIds.add(file.id); items.push({ id: file.id, name: file.name, mimeType: typeof file.mimeType === 'string' ? file.mimeType : 'application/octet-stream', canShare: Boolean(file.capabilities && file.capabilities.canShare), hasAugmentedPermissions: Boolean(file.hasAugmentedPermissions), inheritedPermissionsDisabled: Boolean(file.inheritedPermissionsDisabled), }); }); pageToken = typeof response.nextPageToken === 'string' && response.nextPageToken.length > 0 ? response.nextPageToken : undefined; if (!pageToken) break; } return { items: items, nextPageAvailable: Boolean(pageToken), }; } /** * @param {string} resourceId * @returns {{permissions: Drive.Schema.Permission[], nextPageAvailable: boolean}} */ function listResourcePermissions_(resourceId) { /** @type {Drive.Schema.Permission[]} */ const permissions = []; /** @type {string | undefined} */ let pageToken; for (let pageNumber = 1; pageNumber <= MAX_PERMISSION_PAGES; pageNumber += 1) { /** * @type {{ * supportsAllDrives: boolean, * pageSize: number, * fields: string, * pageToken?: string * }} */ const request = { supportsAllDrives: true, pageSize: PERMISSION_PAGE_SIZE, fields: 'nextPageToken,permissions(id,type,role,emailAddress,domain,displayName,deleted,expirationTime,permissionDetails(permissionType,role,inherited,inheritedFrom))', }; if (pageToken) { request.pageToken = pageToken; } const response = Drive.Permissions.list(resourceId, request); const pageItems = response && Array.isArray(response.permissions) ? response.permissions : []; pageItems.forEach((permission) => { if (permission && permission.deleted !== true) { permissions.push(permission); } }); pageToken = response && typeof response.nextPageToken === 'string' && response.nextPageToken.length > 0 ? response.nextPageToken : undefined; if (!pageToken) break; } return { permissions: permissions, nextPageAvailable: Boolean(pageToken), }; } /** * @param {Drive.Schema.Permission[]} permissions * @param {string | null} organizationDomain * @returns {PermissionAuditSummary_} */ function classifyPermissions_(permissions, organizationDomain) { const normalizedOrgDomain = organizationDomain ? organizationDomain.toLowerCase() : null; const entries = permissions.map((permission) => classifySinglePermission_(permission, normalizedOrgDomain), ); let directOnlyCount = 0; let inheritedOnlyCount = 0; let directAndInheritedCount = 0; let anyoneCount = 0; let domainCount = 0; /** @type {string[]} */ const externalPrincipals = []; entries.forEach((entry) => { if (entry.origin === 'direct') directOnlyCount += 1; else if (entry.origin === 'inherited') inheritedOnlyCount += 1; else directAndInheritedCount += 1; if (entry.isAnyone) anyoneCount += 1; if (entry.isDomain) domainCount += 1; if (entry.isExternalPrincipal && entry.emailAddress) { externalPrincipals.push(entry.emailAddress); } }); return { organizationDomain: normalizedOrgDomain, totalCount: entries.length, directOnlyCount: directOnlyCount, inheritedOnlyCount: inheritedOnlyCount, directAndInheritedCount: directAndInheritedCount, anyoneCount: anyoneCount, domainCount: domainCount, externalPrincipals: externalPrincipals, entries: entries, }; } /** * @param {Drive.Schema.Permission} permission * @param {string | null} normalizedOrgDomain * @returns {ClassifiedPermission_} */ function classifySinglePermission_(permission, normalizedOrgDomain) { const details = Array.isArray(permission.permissionDetails) ? permission.permissionDetails : []; let hasDirectGrant = false; let hasInheritedGrant = false; /** @type {string[]} */ const inheritedFromIds = []; if (details.length === 0) { hasDirectGrant = true; } else { details.forEach((detail) => { if (detail.inherited === true) { hasInheritedGrant = true; if (typeof detail.inheritedFrom === 'string' && detail.inheritedFrom.length > 0) { inheritedFromIds.push(detail.inheritedFrom); } } else { hasDirectGrant = true; } }); } /** @type {'direct' | 'inherited' | 'direct_and_inherited'} */ let origin = 'direct'; if (hasDirectGrant && hasInheritedGrant) { origin = 'direct_and_inherited'; } else if (hasInheritedGrant) { origin = 'inherited'; } const type = typeof permission.type === 'string' ? permission.type : 'unknown'; const role = typeof permission.role === 'string' ? permission.role : 'unknown'; const emailAddress = typeof permission.emailAddress === 'string' && permission.emailAddress.length > 0 ? permission.emailAddress.toLowerCase() : null; const domain = typeof permission.domain === 'string' && permission.domain.length > 0 ? permission.domain.toLowerCase() : null; let isExternalPrincipal = false; if (normalizedOrgDomain && emailAddress && (type === 'user' || type === 'group')) { const atIndex = emailAddress.lastIndexOf('@'); const emailDomain = atIndex > 0 ? emailAddress.slice(atIndex + 1) : ''; isExternalPrincipal = emailDomain.length > 0 && emailDomain !== normalizedOrgDomain; } return { id: typeof permission.id === 'string' ? permission.id : '', type: type, role: role, emailAddress: emailAddress, domain: domain, origin: origin, hasDirectGrant: hasDirectGrant, hasInheritedGrant: hasInheritedGrant, inheritedFromIds: inheritedFromIds, isAnyone: type === 'anyone', isDomain: type === 'domain', isExternalPrincipal: isExternalPrincipal, }; } /** * @param {Drive.Schema.Permission[]} permissions * @returns {string | null} */ function inferSingleDomainPermission_(permissions) { /** @type {Set} */ const domains = new Set(); permissions.forEach((permission) => { if ( permission.type === 'domain' && typeof permission.domain === 'string' && permission.domain.length > 0 ) { domains.add(permission.domain.toLowerCase()); } }); if (domains.size !== 1) return null; return Array.from(domains)[0] || null; } /** * Reads all governance settings in one PropertiesService call. * @returns {GovernanceConfig_} */ function readGovernanceProperties_() { const raw = PropertiesService.getScriptProperties().getProperties(); const sharedDriveId = requireDriveResourceId_(raw[PROP_SHARED_DRIVE_ID], PROP_SHARED_DRIVE_ID); const folderId = optionalDriveResourceId_(raw[PROP_FOLDER_ID], PROP_FOLDER_ID); const fileId = optionalDriveResourceId_(raw[PROP_FILE_ID], PROP_FILE_ID); const reviewerEmail = optionalEmailAddress_(raw[PROP_REVIEWER_EMAIL], PROP_REVIEWER_EMAIL); const organizationDomain = optionalDomainName_( raw[PROP_ORGANIZATION_DOMAIN], PROP_ORGANIZATION_DOMAIN, ); return { sharedDriveId: sharedDriveId, folderId: folderId, fileId: fileId, reviewerEmail: reviewerEmail, organizationDomain: organizationDomain, }; } /** * @param {PropertiesService.Properties} properties * @returns {TemporaryReaderGrantRecord_ | null} */ function readTemporaryGrantRecord_(properties) { const raw = properties.getProperty(TEMP_GRANT_PROPERTY_KEY); if (raw === null) return null; let parsed; try { parsed = JSON.parse(raw); } catch (error) { throw new Error( TEMP_GRANT_PROPERTY_KEY + ' contains invalid JSON. Inspect Script Properties before retrying.', ); } if ( !parsed || typeof parsed !== 'object' || Array.isArray(parsed) || typeof parsed.sharedDriveId !== 'string' || typeof parsed.fileId !== 'string' || typeof parsed.reviewerEmail !== 'string' || typeof parsed.permissionId !== 'string' || typeof parsed.grantedAt !== 'string' || parsed.permissionId.length === 0 ) { throw new Error( TEMP_GRANT_PROPERTY_KEY + ' has an unexpected shape. Inspect Script Properties before retrying.', ); } return { sharedDriveId: requireDriveResourceId_(parsed.sharedDriveId, 'record.sharedDriveId'), fileId: requireDriveResourceId_(parsed.fileId, 'record.fileId'), reviewerEmail: parsed.reviewerEmail.toLowerCase(), permissionId: parsed.permissionId, grantedAt: parsed.grantedAt, }; } /** * @param {string | undefined} value * @param {string} propertyName * @returns {string} */ function requireDriveResourceId_(value, propertyName) { const trimmed = typeof value === 'string' ? value.trim() : ''; if (!trimmed || trimmed.includes('/') || !/^[A-Za-z0-9_-]{10,}$/.test(trimmed)) { throw new Error( 'Set Script Property ' + propertyName + ' to a Drive resource ID (not a full URL or placeholder).', ); } return trimmed; } /** * @param {string | undefined} value * @param {string} propertyName * @returns {string | null} */ function optionalDriveResourceId_(value, propertyName) { const trimmed = typeof value === 'string' ? value.trim() : ''; if (!trimmed) return null; return requireDriveResourceId_(trimmed, propertyName); } /** * @param {string | undefined} value * @param {string} propertyName * @returns {string | null} */ function optionalEmailAddress_(value, propertyName) { const trimmed = typeof value === 'string' ? value.trim().toLowerCase() : ''; if (!trimmed) return null; if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmed) || /@example\.(?:com|org|net)$/.test(trimmed)) { throw new Error( 'Set Script Property ' + propertyName + ' to a real test account email address, not an example placeholder.', ); } return trimmed; } /** * @param {string | undefined} value * @param {string} propertyName * @returns {string | null} */ function optionalDomainName_(value, propertyName) { const trimmed = typeof value === 'string' ? value.trim().toLowerCase() : ''; if (!trimmed) return null; if (!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(trimmed)) { throw new Error('Set Script Property ' + propertyName + ' to a bare domain such as acme.org.'); } return trimmed; }