Skip to content
Skip to chapter

Chapter 27

Workspace services

9 min read

Manage Shared Drives and Drive v3 permissions

Audit a Shared Drive folder with Drive API v3, distinguish inherited roles from direct grants, and add or revoke a temporary file reader.

By the end

Query one Shared Drive folder with corpora 'drive' and supportsAllDrives, separate inherited Shared Drive permissions from direct file grants, and grant and revoke a temporary file reader under a script lock.

Chapter navigation

Audit the child items and permission grants of one Google Workspace Shared Drive folder without changing any Drive data. Then grant temporary reader access on one disposable test file, record the returned permissionId in Script Properties under a script lock, and revoke that exact grant when the review ends.

Complete DriveApp files, folders, and scopes and Inspect a folder with Advanced Drive v3 before starting this chapter.

Why My Drive assumptions break on Shared Drives

Scripts written for personal My Drive folders fail or miss items when pointed at a Shared Drive because ownership, query defaults, and permission fields work differently (see Implement shared drive support and the File resource reference).

BehaviorMy DriveShared Drives
OwnershipOwned by a user account (owners, ownedByMe, and DriveApp.File.getOwner() are populated).Owned by the Google Workspace organization. owners, ownedByMe, and shared are omitted on File resources, and getOwner() returns null.
Folder hierarchyItems live under a user's root or shared folders.Every item has a single parent folder in one tree rooted at the Shared Drive ID (file.driveId).
Item calls (files.get, files.update, permissions.*)Succeed with default parameters when the caller has access.Return 404 File not found unless the call passes supportsAllDrives: true.
Search and folder listing (files.list)Defaults to corpora: 'user'.Omits Shared Drive items unless supportsAllDrives: true and includeItemsFromAllDrives: true are set. Scope to one drive with corpora: 'drive' and driveId.
Permission list on Filefile.permissions is populated when the caller can share the item.file.permissions is never populated. Check file.hasAugmentedPermissions for direct overrides and call Drive.Permissions.list to read grants.
note

Built-in DriveApp wraps legacy Drive v2 concepts designed around personal ownership. Even when DriveApp.getFileById(id) opens an accessible Shared Drive file, DriveApp.File returns null from getOwner(), cannot inspect organizer or fileOrganizer roles, exposes no permissionDetails inheritance array, and provides no corpora: 'drive' search boundary. Use the Advanced Drive v3 service (Drive.Files, Drive.Permissions, Drive.Drives) for Shared Drive governance, and avoid deprecated v2 and early v3 names such as Teamdrives, supportsTeamDrives, includeTeamDriveItems, teamDriveId, and teamDrivePermissionDetails.

Map the five Shared Drive roles and permission inheritance

Shared Drives never assign the owner role to a user. Instead, Drive API v3 uses five roles across Shared Drive membership and item-level sharing (see Roles and permissions in Google Drive and Manage shared drives).

Drive v3 roleGoogle Drive UI labelPermitted actions
organizerManagerManage members and Shared Drive settings, move folders, trash items, and permanently delete trashed items.
fileOrganizerContent managerCreate, edit, move, and trash files and folders inside the Shared Drive without changing drive settings or membership.
writerContributorCreate new files and edit existing files, without moving items or moving them to Trash.
commenterCommenterView files and add comments or suggestions.
readerViewerView and download files, subject to item download restrictions.

The organizer and fileOrganizer roles exist only on Shared Drives. Passing either role on a My Drive item, or omitting supportsAllDrives: true on a Shared Drive item, fails with a 400 validation error.

When you list permissions on a Shared Drive folder or file with permissions.list and include permissionDetails in fields, each Permission object contains a permissionDetails array describing where the grantee's access comes from:

  • inherited: true means the role flows down from the Shared Drive root (permissionType: 'member') or an ancestor folder (permissionType: 'file'), with inheritedFrom holding that ancestor's Drive ID.

  • inherited: false means a user with capabilities.canShare added a direct grant on the inspected folder or file itself.

  • A grantee can have both entries at once. For example, a Shared Drive reader who is granted writer on one document has effective role: 'writer' with two permissionDetails entries: one inherited reader entry and one direct writer entry.

By default, Shared Drive access is additive down the tree. You can grant a collaborator a higher role on a subfolder or child file, but you cannot downgrade or delete an inherited Shared Drive role on a child file unless a Manager configures limited access (inheritedPermissionsDisabled: true) on that item.

Set up a practice Shared Drive and Script Properties

Use a dedicated non-production Google Workspace Shared Drive for this project. Never run permission tests against an active team drive.

  1. In Google Drive, create a practice Shared Drive (or ask a Workspace administrator for an isolated sandbox Shared Drive). Keep external sharing allowed only if you plan to test an external reviewer address.

  2. Open the practice Shared Drive and copy its root ID from https://drive.google.com/drive/folders/SHARED_DRIVE_ID (the segment after /folders/, before any ? query string).

  3. Inside that Shared Drive, create a folder named Governance audit practice and copy its folder ID from the URL.

  4. Inside Governance audit practice, create a Google Doc named Review packet sample, type one fictional test sentence into it, and copy its document ID between /d/ and /edit.

  5. At script.google.com, create a standalone project named Shared Drive permission governance and replace Code.gs with the project code below.

  6. Enable Show "appsscript.json" manifest file in editor under Project Settings, replace appsscript.json with the manifest below, and save both files.

Code.gs
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<string>} */
  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;
}

Download Code.gs
appsscript.json
{
  "timeZone": "Etc/UTC",
  "dependencies": {
    "enabledAdvancedServices": [
      {
        "userSymbol": "Drive",
        "serviceId": "drive",
        "version": "v3"
      }
    ]
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "oauthScopes": [
    "https://www.googleapis.com/auth/drive"
  ]
}

Download appsscript.json

Before configuring live Drive IDs, select runLocalPermissionClassifierCheck in the editor toolbar and click Run. This smoke test runs in V8 memory without calling Drive or Properties and logs a verified summary of five synthetic Permission objects (totalCount: 5, directOnlyCount: 2, inheritedOnlyCount: 2, directAndInheritedCount: 1, anyoneCount: 1, domainCount: 1, and externalPrincipals: ["auditor@vendor.test"]).

Next, store your practice identifiers in Project Settings > Script Properties (see the Properties service guide) so zero resource IDs or email addresses appear in Code.gs:

Script Property keyRequired byValue to enter
PRACTICE_SHARED_DRIVE_IDAudit, grant, revokeRoot ID of your dedicated practice Shared Drive
PRACTICE_FOLDER_IDAudit (optional guard for grant)Folder ID of Governance audit practice
PRACTICE_ORGANIZATION_DOMAINOptional for auditYour bare Google Workspace domain, such as yourcompany.org, used to flag external user and group emails
PRACTICE_FILE_IDGrant, revoke, optional single-file auditDocument ID of Review packet sample
PRACTICE_REVIEWER_EMAILGrantEmail address of a secondary test Google account that holds no current access to the practice Shared Drive

readGovernanceProperties_() opens PropertiesService.getScriptProperties(), reads every key in one Properties.getProperties() call, and validates each value before any Drive API request runs.

Choose between audit-only and permission-management scopes

The manifest declares https://www.googleapis.com/auth/drive because this project both audits permissions and runs the temporary grant and revoke lifecycle. In Drive API v3, permissions.create and permissions.delete (Drive.Permissions.remove in Apps Script) accept only two OAuth scopes:

  • https://www.googleapis.com/auth/drive.file, which covers only files created by the Apps Script project or opened by the user through Google Picker.

  • https://www.googleapis.com/auth/drive, which covers all Drive files and Shared Drive items the executing user can access.

Because PRACTICE_FILE_ID is an existing Shared Drive document supplied through Script Properties rather than created by this script or selected in Picker, drive.file cannot authorize permission changes on it. Full drive is required whenever a standalone governance script adds or removes permissions on existing Shared Drive files (see Choose Google Drive API scopes and Authorization for Google services).

If you deploy an audit-only script that keeps auditSharedDriveFolderPermissions and removes grantTemporaryFileReader and revokeTemporaryFileReader, narrow both appsscript.json and SHARED_DRIVE_GOVERNANCE_SCOPE to https://www.googleapis.com/auth/drive.metadata.readonly. Drive.Files.get, Drive.Files.list, and Drive.Permissions.list all accept drive.metadata.readonly, which prevents the script from downloading file content or mutating permissions. auditSharedDriveFolderPermissions confirms Shared Drive membership by checking folder.driveId === config.sharedDriveId on Drive.Files.get rather than calling Drive.Drives.get, because drives.get requires at least drive.readonly.

Audit folder items and permissions without mutating Drive

warning

Avoid corpora: 'allDrives' in automated folder audits. Setting corpora: 'allDrives' instructs files.list to scan My Drive plus every Shared Drive the running account can view across the organization. Broad q filters then match unintended drives, queries run slower, and Drive can return incompleteSearch: true when it cannot search every corpus in time. Always pair corpora: 'drive' with an explicit driveId, includeItemsFromAllDrives: true, and supportsAllDrives: true.

auditSharedDriveFolderPermissions inspects the folder in three bounded steps without modifying any resource:

  1. getVerifiedSharedDriveFolder_ calls Drive.Files.get with supportsAllDrives: true and checks that PRACTICE_FOLDER_ID is an active folder whose driveId matches PRACTICE_SHARED_DRIVE_ID and whose capabilities.canListChildren is true.

  2. listSharedDriveFolderChildren_ pages Drive.Files.list up to AUDIT_MAX_FILE_PAGES (2 pages of 25 items) using corpora: 'drive', driveId, includeItemsFromAllDrives: true, supportsAllDrives: true, pageToken, and the explicit partial-response mask nextPageToken,incompleteSearch,files(id,name,mimeType,hasAugmentedPermissions,inheritedPermissionsDisabled,capabilities(canShare)).

  3. listResourcePermissions_ pages Drive.Permissions.list (pageSize: 100, supportsAllDrives: true) on PRACTICE_FOLDER_ID and any configured PRACTICE_FILE_ID, because Shared Drives paginate permissions.list at up to 100 grants per page.

Notice why auditSharedDriveFolderPermissions does not call Drive.Permissions.list inside a loop over every child file. On Shared Drives, File.permissions is omitted, so per-file permission lookups cost one HTTP call per child item. Instead, Drive.Files.list reads hasAugmentedPermissions and inheritedPermissionsDisabled on every child in a single list response. Any child with hasAugmentedPermissions: false and inheritedPermissionsDisabled: false carries the exact grants already audited on its parent folder. Only items where children.augmentedItemCount reveals direct overrides need individual inspection through PRACTICE_FILE_ID.

For each audited permission list, classifyPermissions_ counts origin (direct, inherited, or direct_and_inherited), flags public links (type === 'anyone') and domain-wide links (type === 'domain'), and lists any user or group emailAddress outside PRACTICE_ORGANIZATION_DOMAIN (or outside a single inferred domain grant when PRACTICE_ORGANIZATION_DOMAIN is unset).

Grant and revoke a temporary file reader under a script lock

tip

In permissions.create, sendNotificationEmail defaults to true whenever type is 'user' or 'group', sending an email for every API call. Pass sendNotificationEmail: false in the optional query parameters object during automated provisioning and testing so scripts do not send unwanted share notifications. Keep sendNotificationEmail off 'domain' and 'anyone' grants (where Drive rejects the parameter with 400) and off ownership transfers (transferOwnership: true).

warning

Drive API v3 does not support concurrent permission mutations on the same file. When two requests overlap, only the last update is applied (see Share files, folders, and drives). In addition, calling Drive.Permissions.remove on a child file fails whenever the target permission includes an inherited Shared Drive or parent-folder role (permissionDetails[].inherited === true). Serialize permission writes with LockService.getScriptLock(), record the exact permissionId your script created, and verify hasInheritedGrant === false before revoking.

grantTemporaryFileReader and revokeTemporaryFileReader manage one temporary reader grant on PRACTICE_FILE_ID:

  1. Both functions acquire LockService.getScriptLock() with tryLock(5000) and release it in finally so overlapping executions cannot race on Drive or Script Properties.

  2. grantTemporaryFileReader verifies that PRACTICE_FILE_ID is a non-trashed file (never a folder or shortcut) inside PRACTICE_SHARED_DRIVE_ID with capabilities.canShare === true.

  3. grantTemporaryFileReader checks SHARED_DRIVE_TEMP_READER_GRANT in ScriptProperties (logging status: "already_granted" if still active) and stops if PRACTICE_REVIEWER_EMAIL already holds inherited or direct access on the file.

  4. grantTemporaryFileReader calls Drive.Permissions.create({ type: 'user', role: 'reader', emailAddress: config.reviewerEmail }, config.fileId, { supportsAllDrives: true, sendNotificationEmail: false, fields: '...' }) and writes the returned permissionId to SHARED_DRIVE_TEMP_READER_GRANT.

  5. revokeTemporaryFileReader verifies record.fileId, record.sharedDriveId, and hasInheritedGrant === false, calls Drive.Permissions.remove(record.fileId, record.permissionId, { supportsAllDrives: true }), and deletes SHARED_DRIVE_TEMP_READER_GRANT (or reports status: "already_absent" if manually removed).

If your Google Workspace organization supports expiring permissions on eligible editions, you can also set an RFC 3339 expirationTime (up to one year in the future) on user and group grants when calling Permissions.create or Permissions.update (see the Permission resource reference). Explicit revocation with revokeTemporaryFileReader works across all Workspace editions that support Shared Drives and removes access immediately.

Exercise

Run the full read-only audit and temporary reader lifecycle against your disposable Shared Drive fixture:

  1. Select runLocalPermissionClassifierCheck and click Run. Confirm Execution log reports totalCount: 5, directOnlyCount: 2, inheritedOnlyCount: 2, directAndInheritedCount: 1, and externalPrincipals: ["auditor@vendor.test"].

  2. In Project Settings > Script Properties, set PRACTICE_SHARED_DRIVE_ID, PRACTICE_FOLDER_ID, PRACTICE_FILE_ID, PRACTICE_REVIEWER_EMAIL, and PRACTICE_ORGANIZATION_DOMAIN.

  3. Run auditSharedDriveFolderPermissions and approve the OAuth prompt. Confirm children.augmentedItemCount is 0, targetFile.permissionSummary.directOnlyCount is 0, and inheritedOnlyCount reflects your Shared Drive's members.

  4. Select grantTemporaryFileReader and click Run once to record status: "granted" and permissionId. Run it a second time and confirm status: "already_granted" with the same permissionId.

  5. Run auditSharedDriveFolderPermissions again. Confirm children.augmentedItemCount is 1, targetFile.hasAugmentedPermissions is true, and targetFile.permissionSummary.directOnlyCount is 1, while folder.permissionSummary is unchanged.

  6. Run revokeTemporaryFileReader to confirm status: "revoked", rerun auditSharedDriveFolderPermissions to confirm directOnlyCount is 0, and delete the practice keys from Script Properties.

Next, read Google Tasks and Contacts APIs.

Project files

Complete source files for this chapter's examples.

Audit a Shared Drive folder and govern temporary file permissions

Code.gs
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<string>} */
  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;
}

appsscript.json

Download file
appsscript.json
{
  "timeZone": "Etc/UTC",
  "dependencies": {
    "enabledAdvancedServices": [
      {
        "userSymbol": "Drive",
        "serviceId": "drive",
        "version": "v3"
      }
    ]
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "oauthScopes": [
    "https://www.googleapis.com/auth/drive"
  ]
}