feat: protect a document from changes in Word, with a password and editable ranges (#2271) (#3810)

This commit is contained in:
Dolan
2026-10-21 14:09:06 +01:00
committed by GitHub
parent b9a762ea28
commit ba2b4e26a0
18 changed files with 796 additions and 0 deletions
@@ -0,0 +1,44 @@
// Protect a document so that it is read-only in Word, except for the parts anyone can still change
// See docs/usage/document-protection.md for full documentation.
import * as fs from "fs";
import { Document, DocumentProtectionType, EditableRangeEnd, EditableRangeStart, HeadingLevel, Packer, Paragraph, TextRun } from "docx";
const doc = new Document({
protection: {
type: DocumentProtectionType.READ_ONLY,
password: "docx",
},
sections: [
{
children: [
new Paragraph({ text: "Leave request", heading: HeadingLevel.HEADING_1 }),
new Paragraph("This form is protected: only the highlighted parts can be changed. The password is docx."),
new Paragraph({
children: [
new TextRun({ text: "Name: ", bold: true }),
new EditableRangeStart(1),
new TextRun("Type your name"),
new EditableRangeEnd(1),
],
}),
new Paragraph({
children: [
new TextRun({ text: "Dates: ", bold: true }),
new EditableRangeStart(2),
new TextRun("From and to"),
new EditableRangeEnd(2),
],
}),
new Paragraph({ children: [new TextRun({ text: "Reason", bold: true })] }),
new Paragraph({ children: [new EditableRangeStart(3), new TextRun("Anything you write here,")] }),
new Paragraph({ children: [new TextRun("over as many paragraphs as you need."), new EditableRangeEnd(3)] }),
new Paragraph("Requests are answered within five working days."),
],
},
],
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer);
});
+1
View File
@@ -65,6 +65,7 @@
- [Layout](usage/layout.md)
- [Tabs](usage/tabs.md)
- [Change Tracking](usage/change-tracking.md)
- [Document Protection](usage/document-protection.md)
- [Math](usage/math.md)
- [Math from LaTeX](usage/math-latex.md)
- [HTML](usage/html.md)
+123
View File
@@ -0,0 +1,123 @@
# Document Protection
Protect a document so that people can't change it in Word, or can only add comments, make tracked changes or fill in forms. This is what Word's **Review > Restrict Editing** does. Parts of a protected document can stay editable for everyone, so the rest of it is read-only.
!> Protection stops changes in Word. The document isn't encrypted: anyone can still read it, and someone who edits the file's XML can take the protection out.
## Read-only Documents
Set the document's `protection` option:
```ts live
import { Document, DocumentProtectionType, Paragraph } from "docx";
const doc = new Document({
protection: {
type: DocumentProtectionType.READ_ONLY,
},
sections: [
{
children: [new Paragraph("This document is read-only in Word.")],
},
],
});
```
Without a password, anyone can turn the protection off in Word, with **Stop Protection** in the Restrict Editing pane.
## Passwords
Give a `password` so that only people who know it can turn the protection off:
```ts live
import { Document, DocumentProtectionType, Paragraph } from "docx";
const doc = new Document({
protection: {
type: DocumentProtectionType.READ_ONLY,
password: "secret",
},
sections: [
{
children: [new Paragraph("Only people who know the password can change this document.")],
},
],
});
```
The document keeps a hash of the password, never the password. It is hashed as Word hashes it, 100,000 times with a random salt, though with SHA-256 rather than the SHA-512 Word uses, as SHA-256 is much faster in JavaScript. Word reads either. Word only reads the first 15 characters of a password, and an empty password is no password.
## Protection Options
| Property | Type | Notes | Description |
| -------- | ------------------------ | -------- | -------------------------------------------------- |
| type | `DocumentProtectionType` | Required | What people can change in the document |
| password | `string` | Optional | The password that turns the protection off in Word |
## Protection Types
| Type | Word's name | What people can change |
| ---------------------------------------- | ---------------- | ----------------------------------------------------------------- |
| `DocumentProtectionType.READ_ONLY` | No changes | Nothing, except the [editable ranges](#editable-ranges) |
| `DocumentProtectionType.COMMENTS` | Comments | They can only add comments, and change the editable ranges |
| `DocumentProtectionType.TRACKED_CHANGES` | Tracked changes | Anything, but every change is [tracked](usage/change-tracking.md) |
| `DocumentProtectionType.FORMS` | Filling in forms | They can only fill in the form fields |
```ts live
import { Document, DocumentProtectionType, Paragraph } from "docx";
const doc = new Document({
protection: {
type: DocumentProtectionType.TRACKED_CHANGES,
},
sections: [
{
children: [new Paragraph("Every change made to this document in Word is tracked.")],
},
],
});
```
## Editable Ranges
To keep parts of a protected document editable, put them between an `EditableRangeStart` and an `EditableRangeEnd` with the same id. Anyone can change what is between them, and Word highlights it. The ids only have to be different from each other's.
A range can be part of a paragraph, or start in one paragraph and end in a later one:
```ts live
import { Document, DocumentProtectionType, EditableRangeEnd, EditableRangeStart, Paragraph, TextRun } from "docx";
const doc = new Document({
protection: {
type: DocumentProtectionType.READ_ONLY,
password: "secret",
},
sections: [
{
children: [
new Paragraph("Only the highlighted parts of this document can be changed."),
new Paragraph({
children: [
new TextRun({ text: "Name: ", bold: true }),
new EditableRangeStart(1),
new TextRun("Type your name"),
new EditableRangeEnd(1),
],
}),
new Paragraph({ children: [new EditableRangeStart(2), new TextRun("Anything you write here,")] }),
new Paragraph({ children: [new TextRun("over as many paragraphs as you need."), new EditableRangeEnd(2)] }),
],
},
],
});
```
Editable ranges are for read-only and comments protection: with tracked changes everything can be changed, and with forms only the form fields can.
## Demos
### Read-only Form
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/document-settings/document-protection.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/document-settings/document-protection.ts_
+2
View File
@@ -80,6 +80,7 @@ These properties appear in Word's File > Info panel and in file properties. Word
| features | `{ trackRevisions?: boolean; updateFields?: boolean }` | Feature flags |
| evenAndOddHeaderAndFooters | `boolean` | Different odd/even headers |
| hyphenation | `IHyphenationOptions` | Hyphenation settings |
| protection | `IDocumentProtectionOptions` | What people can change in Word, and the password that turns that [protection](usage/document-protection.md) off |
| pageNumbers | `PageNumberEstimator` | Writes the page numbers of tables of contents and page references, and the numbers of pages, with `estimatePageNumbers` from [`docx/layout`](usage/layout.md) |
### Compatibility
@@ -117,6 +118,7 @@ These properties appear in Word's File > Info panel and in file properties. Word
| hyphenation | `IHyphenationOptions` | Optional |
| theme | `IThemeOptions` | Optional |
| pageNumbers | `PageNumberEstimator` | Optional |
| protection | `IDocumentProtectionOptions` | Optional |
### Change background color of Document
+8
View File
@@ -11,6 +11,7 @@ import type { FontOptions } from "@file/fonts/font-table";
import type { ICommentsOptions } from "@file/paragraph/run/comment-run";
import type { IHyphenationOptions } from "@file/settings";
import type { ICompatibilityOptions } from "@file/settings/compatibility";
import type { IDocumentProtectionOptions } from "@file/settings/document-protection";
import { StringContainer, XmlAttributeComponent, XmlComponent } from "@file/xml-components";
import { dateTimeValue } from "@util/values";
@@ -52,6 +53,7 @@ import type { IThemeOptions } from "../theme";
* @property theme - The document's theme: its colors, and its fonts for headings and body text
* @property pageNumbers - Works out the page each bookmark is on, so the page numbers of tables of contents and page references are written with the document
* @property macros - The document's VBA macros, which make it a macro-enabled document (.docm)
* @property protection - What people can change in the document in Word, and the password that turns that protection off
*/
export type IPropertiesOptions = {
readonly sections: readonly ISectionOptions[];
@@ -110,6 +112,12 @@ export type IPropertiesOptions = {
* macro-enabled document, which Word only opens from a .docm file
*/
readonly macros?: DocumentMacros;
/**
* What people can change in the document in Word: nothing, or only comments, tracked changes or forms, as Word's
* Restrict Editing does. A password stops anyone without it turning the protection off. Parts of the document
* between `EditableRangeStart` and `EditableRangeEnd` can still be changed by anyone
*/
readonly protection?: IDocumentProtectionOptions;
};
/**
+13
View File
@@ -462,6 +462,19 @@ describe("File", () => {
expect(tree["w:settings"]).to.deep.include({ "w:embedTrueTypeFonts": {} });
});
it("should protect the document with its protection option", () => {
const doc = new File({
sections: [],
protection: { type: "trackedChanges" },
});
const tree = new Formatter().format(doc.Settings);
expect(tree["w:settings"]).to.deep.include({
"w:documentProtection": { _attr: { "w:edit": "trackedChanges", "w:enforcement": true } },
});
});
it("should not write embedTrueTypeFonts when no fonts are embedded", () => {
for (const fonts of [undefined, []]) {
const doc = new File({ sections: [], fonts });
+1
View File
@@ -249,6 +249,7 @@ export class File {
updateFields: options.features?.updateFields,
embedFonts: options.fonts?.length ? true : undefined,
defaultTabStop: options.defaultTabStop,
protection: options.protection,
hyphenation: {
autoHyphenation: options.hyphenation?.autoHyphenation,
hyphenationZone: options.hyphenation?.hyphenationZone,
+1
View File
@@ -42,3 +42,4 @@ export { type OleObjectRelationshipType, type RelationshipType } from "./relatio
// The VML shape that text boxes are drawn with, which docx/watermarks uses too
export { type IVmlShapeOptions, type LengthUnit, type VmlShapeStyle, createVmlShape } from "./vml";
export { type IPropertiesOptions } from "./core-properties";
export { DocumentProtectionType, type IDocumentProtectionOptions } from "./settings/document-protection";
+3
View File
@@ -30,6 +30,7 @@ import {
TextRun,
} from "./run";
import type { Comment, CommentRangeEnd, CommentRangeStart, CommentReference, Comments } from "./run/comment-run";
import type { EditableRangeEnd, EditableRangeStart } from "./run/editable-range";
/**
* The types of children that can be contained within a Paragraph element.
@@ -57,6 +58,8 @@ export type ParagraphChild =
| CommentRangeStart
| CommentRangeEnd
| CommentReference
| EditableRangeStart
| EditableRangeEnd
| CheckBox
| Textbox;
@@ -0,0 +1,46 @@
import { describe, expect, it } from "vitest";
import { Formatter } from "@export/formatter";
import { Paragraph } from "../paragraph";
import { EditableRangeEnd, EditableRangeStart } from "./editable-range";
import { TextRun } from "./text-run";
describe("EditableRangeStart", () => {
it("should start a range everyone can edit", () => {
const tree = new Formatter().format(new EditableRangeStart(1));
expect(tree).to.deep.equal({
"w:permStart": { _attr: { "w:id": 1, "w:edGrp": "everyone" } },
});
});
});
describe("EditableRangeEnd", () => {
it("should end the range with the same id", () => {
const tree = new Formatter().format(new EditableRangeEnd(1));
expect(tree).to.deep.equal({
"w:permEnd": { _attr: { "w:id": 1 } },
});
});
});
describe("Paragraph with an editable range", () => {
it("should write the range's start and end around the runs in it", () => {
const paragraph = new Paragraph({
children: [new TextRun("Name: "), new EditableRangeStart(2), new TextRun("Type here"), new EditableRangeEnd(2)],
});
const tree = new Formatter().format(paragraph);
expect(tree).to.deep.equal({
"w:p": [
{ "w:r": [{ "w:t": [{ _attr: { "xml:space": "preserve" } }, "Name: "] }] },
{ "w:permStart": { _attr: { "w:id": 2, "w:edGrp": "everyone" } } },
{ "w:r": [{ "w:t": [{ _attr: { "xml:space": "preserve" } }, "Type here"] }] },
{ "w:permEnd": { _attr: { "w:id": 2 } } },
],
});
});
});
+99
View File
@@ -0,0 +1,99 @@
/**
* Editable range module for WordprocessingML documents.
*
* An editable range is a part of a protected document that anyone can still change, as Word's Restrict Editing
* exceptions for "Everyone" are. It runs from an `EditableRangeStart` to the `EditableRangeEnd` with the same id,
* which can be in a later paragraph.
*
* Reference: ISO/IEC 29500-1 17.13.7 (permStart and permEnd)
*
* @module
*/
import { XmlAttributeComponent, XmlComponent } from "@file/xml-components";
/**
* @internal
*/
class EditableRangeStartAttributes extends XmlAttributeComponent<{ readonly id: number; readonly editorGroup: string }> {
protected readonly xmlKeys = { id: "w:id", editorGroup: "w:edGrp" };
}
/**
* @internal
*/
class EditableRangeEndAttributes extends XmlAttributeComponent<{ readonly id: number }> {
protected readonly xmlKeys = { id: "w:id" };
}
/**
* Represents the start of an editable range: where a part of a protected document that anyone can change begins.
*
* It must be paired with an `EditableRangeEnd` with the same id, which can be in the same paragraph or a later one.
* The id must be different from every other editable range's. The document's `protection` option protects the rest.
*
* Reference: ISO/IEC 29500-1 17.13.7.3 (permStart)
*
* @publicApi
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_PermStart">
* <xsd:complexContent>
* <xsd:extension base="CT_Perm">
* <xsd:attribute name="edGrp" type="ST_EdGrp" use="optional"/>
* <xsd:attribute name="ed" type="s:ST_String" use="optional"/>
* <xsd:attribute name="colFirst" type="ST_DecimalNumber" use="optional"/>
* <xsd:attribute name="colLast" type="ST_DecimalNumber" use="optional"/>
* </xsd:extension>
* </xsd:complexContent>
* </xsd:complexType>
* ```
*
* @example
* ```typescript
* new Paragraph({
* children: [new TextRun("Name: "), new EditableRangeStart(1), new TextRun("type your name"), new EditableRangeEnd(1)],
* });
* ```
*/
export class EditableRangeStart extends XmlComponent {
// Only in the type: with no members of its own, any component, such as a Paragraph, would type check as one
declare private readonly brand: "EditableRangeStart";
public constructor(id: number) {
super("w:permStart");
this.root.push(new EditableRangeStartAttributes({ id, editorGroup: "everyone" }));
}
}
/**
* Represents the end of an editable range, which `EditableRangeStart` with the same id begins.
*
* Reference: ISO/IEC 29500-1 17.13.7.2 (permEnd)
*
* @publicApi
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_Perm">
* <xsd:attribute name="id" type="s:ST_String" use="required"/>
* <xsd:attribute name="displacedByCustomXml" type="ST_DisplacedByCustomXml" use="optional"/>
* </xsd:complexType>
* ```
*
* @example
* ```typescript
* new EditableRangeEnd(1);
* ```
*/
export class EditableRangeEnd extends XmlComponent {
// Only in the type: with no members of its own, any component, such as a Paragraph, would type check as one
declare private readonly brand: "EditableRangeEnd";
public constructor(id: number) {
super("w:permEnd");
this.root.push(new EditableRangeEndAttributes({ id }));
}
}
+1
View File
@@ -18,6 +18,7 @@ export * from "./east-asian-layout";
export * from "./fit-text";
export * from "./simple-field";
export * from "./comment-run";
export * from "./editable-range";
export * from "./comments-extended";
export * from "./empty-children";
export * from "./positional-tab";
@@ -0,0 +1,59 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { Formatter } from "@export/formatter";
import { DocumentProtection, DocumentProtectionType } from "./document-protection";
describe("DocumentProtection", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it.each([
[DocumentProtectionType.READ_ONLY, "readOnly"],
[DocumentProtectionType.COMMENTS, "comments"],
[DocumentProtectionType.TRACKED_CHANGES, "trackedChanges"],
[DocumentProtectionType.FORMS, "forms"],
])("should enforce %s protection without a password", (type, edit) => {
const tree = new Formatter().format(new DocumentProtection({ type }));
expect(tree).to.deep.equal({
"w:documentProtection": { _attr: { "w:edit": edit, "w:enforcement": true } },
});
});
it("should write no password for an empty one, as Word does", () => {
const tree = new Formatter().format(new DocumentProtection({ type: DocumentProtectionType.READ_ONLY, password: "" }));
expect(tree).to.deep.equal({
"w:documentProtection": { _attr: { "w:edit": "readOnly", "w:enforcement": true } },
});
});
it("should write a password's hash and salt so that Word accepts the password", () => {
// A salt and hash Word for Mac 16 accepted the password "Example" for
const salt = [...atob("E7Z4pK9vZJtgEIUrL2UL3w==")].map((character) => character.charCodeAt(0));
vi.spyOn(globalThis.crypto, "getRandomValues").mockImplementation((array) => {
(array as Uint8Array).set(salt);
return array;
});
const tree = new Formatter().format(new DocumentProtection({ type: DocumentProtectionType.READ_ONLY, password: "Example" }));
expect(tree).to.deep.equal({
"w:documentProtection": {
_attr: {
"w:edit": "readOnly",
"w:enforcement": true,
"w:cryptProviderType": "rsaAES",
"w:cryptAlgorithmClass": "hash",
"w:cryptAlgorithmType": "typeAny",
"w:cryptAlgorithmSid": 12,
"w:cryptSpinCount": 100000,
"w:hash": "MZHm/PwSL2XqNHWnrQFREO8SwF9ZeosDyD3uS3/jbiU=",
"w:salt": "E7Z4pK9vZJtgEIUrL2UL3w==",
},
},
});
});
});
+160
View File
@@ -0,0 +1,160 @@
/**
* Document protection module for WordprocessingML documents.
*
* Protection limits what people can change in a document when they open it in Word, as Word's Restrict Editing
* does: nothing, or only comments, tracked changes or forms. A password stops anyone without it turning the
* protection off.
*
* Reference: ISO/IEC 29500-1 17.15.1.29 (documentProtection)
*
* @module
*/
import { XmlAttributeComponent, XmlComponent } from "@file/xml-components";
import { PROTECTION_PASSWORD_SPIN_COUNT, hashProtectionPassword, randomSalt } from "./protection-password";
/**
* What people can change in a protected document, as Word's Restrict Editing offers it.
*
* ## XSD Schema
*
* ```xml
* <xsd:simpleType name="ST_DocProtect">
* <xsd:restriction base="xsd:string">
* <xsd:enumeration value="none"/>
* <xsd:enumeration value="readOnly"/>
* <xsd:enumeration value="comments"/>
* <xsd:enumeration value="trackedChanges"/>
* <xsd:enumeration value="forms"/>
* </xsd:restriction>
* </xsd:simpleType>
* ```
*
* @publicApi
*/
export const DocumentProtectionType = {
/**
* ## No Changes (Read Only)
*
* Nothing can be changed, except in the document's editable ranges (`EditableRangeStart` to `EditableRangeEnd`).
*/
READ_ONLY: "readOnly",
/**
* ## Comments
*
* Only comments can be added, and the editable ranges changed.
*/
COMMENTS: "comments",
/**
* ## Tracked Changes
*
* Anything can be changed, and every change is tracked, as a revision people can accept or reject.
*/
TRACKED_CHANGES: "trackedChanges",
/**
* ## Filling in Forms
*
* Only form fields can be filled in.
*/
FORMS: "forms",
} as const;
/**
* Options for protecting a document.
*
* @see {@link DocumentProtection}
*/
export type IDocumentProtectionOptions = {
/** What people can change in the document */
readonly type: (typeof DocumentProtectionType)[keyof typeof DocumentProtectionType];
/**
* The password that turns the protection off. Without one, anyone can turn it off in Word (Review > Restrict
* Editing > Stop Protection). Word only reads its first 15 characters.
*
* The document isn't encrypted, so the protection stops changes in Word, not people who read or change the file
* another way.
*/
readonly password?: string;
};
/**
* Attributes of the document protection element.
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_DocProtect">
* <xsd:attribute name="edit" type="ST_DocProtect" use="optional"/>
* <xsd:attribute name="formatting" type="s:ST_OnOff" use="optional"/>
* <xsd:attribute name="enforcement" type="s:ST_OnOff"/>
* <xsd:attributeGroup ref="AG_Password"/>
* <xsd:attributeGroup ref="AG_TransitionalPassword"/>
* </xsd:complexType>
* ```
*/
class DocumentProtectionAttributes extends XmlAttributeComponent<{
readonly edit: string;
readonly enforcement: boolean;
readonly cryptProviderType?: string;
readonly cryptAlgorithmClass?: string;
readonly cryptAlgorithmType?: string;
readonly cryptAlgorithmSid?: number;
readonly cryptSpinCount?: number;
readonly hash?: string;
readonly salt?: string;
}> {
protected readonly xmlKeys = {
edit: "w:edit",
enforcement: "w:enforcement",
cryptProviderType: "w:cryptProviderType",
cryptAlgorithmClass: "w:cryptAlgorithmClass",
cryptAlgorithmType: "w:cryptAlgorithmType",
cryptAlgorithmSid: "w:cryptAlgorithmSid",
cryptSpinCount: "w:cryptSpinCount",
hash: "w:hash",
salt: "w:salt",
};
}
const toBase64 = (bytes: readonly number[]): string => btoa(String.fromCharCode(...bytes));
/**
* Represents a document's protection (`w:documentProtection`), which limits what people can change in it in Word.
*
* A password is hashed as Word hashes it, with a random 16-byte salt, 100,000 times, after Word's legacy key
* derivation, but with SHA-256 (`w:cryptAlgorithmSid` 12), which is much faster here than the SHA-512 Word uses. These
* are the transitional password attributes, which Word writes.
*
* Reference: ISO/IEC 29500-1 17.15.1.29 (documentProtection)
*
* @example
* ```typescript
* new DocumentProtection({ type: DocumentProtectionType.READ_ONLY, password: "secret" });
* ```
*/
export class DocumentProtection extends XmlComponent {
public constructor({ type, password }: IDocumentProtectionOptions) {
super("w:documentProtection");
// Word turns protection off for anyone when its password is empty, and writes no hash for it
if (password === undefined || password === "") {
this.root.push(new DocumentProtectionAttributes({ edit: type, enforcement: true }));
return;
}
const salt = randomSalt(16);
this.root.push(
new DocumentProtectionAttributes({
edit: type,
enforcement: true,
cryptProviderType: "rsaAES",
cryptAlgorithmClass: "hash",
cryptAlgorithmType: "typeAny",
// SHA-256
cryptAlgorithmSid: 12,
cryptSpinCount: PROTECTION_PASSWORD_SPIN_COUNT,
hash: toBase64(hashProtectionPassword(password, salt, PROTECTION_PASSWORD_SPIN_COUNT)),
salt: toBase64(salt),
}),
);
}
}
@@ -0,0 +1,93 @@
// cspell:words unstub
import { afterEach, describe, expect, it, vi } from "vitest";
import { PROTECTION_PASSWORD_SPIN_COUNT, hashProtectionPassword, legacyPasswordKey, randomSalt } from "./protection-password";
const fromBase64 = (text: string): readonly number[] => [...atob(text)].map((character) => character.charCodeAt(0));
const toBase64 = (bytes: readonly number[]): string => btoa(String.fromCharCode(...bytes));
describe("legacyPasswordKey", () => {
it("should give the standard's example key, in reversed byte order", () => {
// ECMA-376 Part 4 2.15.1.28: "Example" gives 0x64CEED7E, written 7EEDCE64
expect(legacyPasswordKey("Example")).to.equal("7EEDCE64");
});
it("should only read the first 15 characters", () => {
expect(legacyPasswordKey("abcdefghijklmnopqrstuvwxyz")).to.equal(legacyPasswordKey("abcdefghijklmno"));
expect(legacyPasswordKey("abcdefghijklmn")).not.to.equal(legacyPasswordKey("abcdefghijklmno"));
});
it("should read each UTF-16 code unit of a character outside the Basic Multilingual Plane, as Word does", () => {
// U+1F600 and U+1F601 are the surrogate pairs D83D DE00 and D83D DE01, which differ only in the second
expect(legacyPasswordKey("\u{1F600}A")).not.to.equal(legacyPasswordKey("\u{1F601}A"));
});
it("should read a character's high byte when its low byte is 0", () => {
// U+4E00 has the low byte 0x00 and the high byte 0x4E, which is "N"
expect(legacyPasswordKey("一")).to.equal(legacyPasswordKey("N"));
});
});
describe("hashProtectionPassword", () => {
// Word for Mac 16 turned off the protection of a document with each salt and hash below when given the password,
// and refused a wrong one. Word writes SHA-512 itself, so the hashes are docx's, checked in Word
it("should hash a password so that Word accepts it", () => {
const hash = hashProtectionPassword("Example", fromBase64("E7Z4pK9vZJtgEIUrL2UL3w=="), PROTECTION_PASSWORD_SPIN_COUNT);
expect(toBase64(hash)).to.equal("MZHm/PwSL2XqNHWnrQFREO8SwF9ZeosDyD3uS3/jbiU=");
});
it("should hash a long password with characters outside ASCII so that Word accepts it", () => {
const hash = hashProtectionPassword(
/* cspell:disable-next-line */
"Pässwort密码abcdefghijklmnop",
fromBase64("v61srLQZvvOFtTTJHbPd+Q=="),
PROTECTION_PASSWORD_SPIN_COUNT,
);
expect(toBase64(hash)).to.equal("3vCPYtiBiMryITfhIFJ0JYH+jZYaqN13ShVrlgN3vwQ=");
});
it("should hash a password with an emoji so that Word accepts it", () => {
/* cspell:disable-next-line */
const hash = hashProtectionPassword("\u{1F600}A", fromBase64("CYsnXnAl+DFslgfN1qMaMA=="), PROTECTION_PASSWORD_SPIN_COUNT);
expect(toBase64(hash)).to.equal("dpP7q9Lj2LC2lDz9nRn34GE7Mgke2Fhp8b0svGCfc2E=");
});
it("should give a 32-byte SHA-256 hash that depends on the salt and the spin count", () => {
const salt = Array.from({ length: 16 }, (_, index) => index);
const hash = hashProtectionPassword("secret", salt, 10);
expect(hash).to.have.length(32);
expect(hashProtectionPassword("secret", salt, 10)).to.deep.equal(hash);
expect(hashProtectionPassword("secret", salt, 11)).not.to.deep.equal(hash);
expect(hashProtectionPassword("secret", [...salt].reverse(), 10)).not.to.deep.equal(hash);
});
});
describe("randomSalt", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it("should give bytes from the platform's secure random numbers", () => {
const getRandomValues = vi.spyOn(globalThis.crypto, "getRandomValues");
const salt = randomSalt(16);
expect(salt).to.have.length(16);
expect(getRandomValues).toHaveBeenCalledOnce();
getRandomValues.mockRestore();
});
it("should give random bytes without the platform's secure random numbers, as on Node.js before 19", () => {
vi.stubGlobal("crypto", undefined);
const salt = randomSalt(16);
expect(salt).to.have.length(16);
expect(salt.every((byte) => Number.isInteger(byte) && byte >= 0 && byte <= 255)).to.equal(true);
expect(randomSalt(16)).not.to.deep.equal(salt);
});
});
+121
View File
@@ -0,0 +1,121 @@
/**
* Hashes the password that stops a document's protection, as Word does.
*
* Reference: ISO/IEC 29500-1 17.15.1.29 (documentProtection) and the legacy password algorithm it builds on,
* ECMA-376 Part 4 2.15.1.28
*
* @module
*/
/* eslint-disable no-bitwise -- the legacy key is made of 16-bit words, and the iteration numbers are hashed as bytes */
import hash from "hash.js";
/** How many times Word hashes the password again, which is what it writes in `w:cryptSpinCount` */
export const PROTECTION_PASSWORD_SPIN_COUNT = 100000;
// Word only reads the first 15 characters of the password, counted in UTF-16 code units
const MAX_PASSWORD_LENGTH = 15;
// The legacy algorithm's starting values for the key's high-order word, one for each password length
const INITIAL_CODES = [
0xe1f0, 0x1d0f, 0xcc9c, 0x84c0, 0x110c, 0x0e10, 0xf1ce, 0x313e, 0x1872, 0xe139, 0xd40f, 0x84f9, 0x280c, 0xa96a, 0x4ec3,
];
// The legacy algorithm's encryption matrix: a row for each character position (counted back from the 15th), and a
// column for each of the character's low seven bits
const ENCRYPTION_MATRIX = [
[0xaefc, 0x4dd9, 0x9bb2, 0x2745, 0x4e8a, 0x9d14, 0x2a09],
[0x7b61, 0xf6c2, 0xfda5, 0xeb6b, 0xc6f7, 0x9dcf, 0x2bbf],
[0x4563, 0x8ac6, 0x05ad, 0x0b5a, 0x16b4, 0x2d68, 0x5ad0],
[0x0375, 0x06ea, 0x0dd4, 0x1ba8, 0x3750, 0x6ea0, 0xdd40],
[0xd849, 0xa0b3, 0x5147, 0xa28e, 0x553d, 0xaa7a, 0x44d5],
[0x6f45, 0xde8a, 0xad35, 0x4a4b, 0x9496, 0x390d, 0x721a],
[0xeb23, 0xc667, 0x9cef, 0x29ff, 0x53fe, 0xa7fc, 0x5fd9],
[0x47d3, 0x8fa6, 0x0f6d, 0x1eda, 0x3db4, 0x7b68, 0xf6d0],
[0xb861, 0x60e3, 0xc1c6, 0x93ad, 0x377b, 0x6ef6, 0xddec],
[0x45a0, 0x8b40, 0x06a1, 0x0d42, 0x1a84, 0x3508, 0x6a10],
[0xaa51, 0x4483, 0x8906, 0x022d, 0x045a, 0x08b4, 0x1168],
[0x76b4, 0xed68, 0xcaf1, 0x85c3, 0x1ba7, 0x374e, 0x6e9c],
[0x3730, 0x6e60, 0xdcc0, 0xa9a1, 0x4363, 0x86c6, 0x1dad],
[0x3331, 0x6662, 0xccc4, 0x89a9, 0x0373, 0x06e6, 0x0dcc],
[0x1021, 0x2042, 0x4084, 0x8108, 0x1231, 0x2462, 0x48c4],
];
// Rotates a 15-bit value left by one bit
const rotateLeft15 = (value: number): number => ((value >> 14) & 1) | ((value << 1) & 0x7fff);
/**
* The legacy key Word derives from a password before hashing it, as uppercase hex in reversed byte order. The
* standard's example is "Example", whose key 0x64CEED7E is written "7EEDCE64".
*
* @internal
*/
export const legacyPasswordKey = (password: string): string => {
// Each UTF-16 code unit becomes one byte: its low byte, or its high byte when the low byte is 0. Word reads code
// units, not code points, so an emoji is two, with a byte from each half of its surrogate pair
const bytes = password
.slice(0, MAX_PASSWORD_LENGTH)
.split("")
.map((character) => {
const code = character.charCodeAt(0);
return (code & 0xff) !== 0 ? code & 0xff : (code >> 8) & 0xff;
});
const highOrderWord = bytes.reduce(
(word, byte, index) =>
ENCRYPTION_MATRIX[MAX_PASSWORD_LENGTH - bytes.length + index].reduce(
(current, code, bit) => ((byte >> bit) & 1 ? current ^ code : current),
word,
),
INITIAL_CODES[bytes.length - 1],
);
const lowOrderWord = (rotateLeft15(bytes.reduceRight((word, byte) => rotateLeft15(word) ^ byte, 0)) ^ bytes.length ^ 0xce4b) & 0xffff;
return [lowOrderWord & 0xff, lowOrderWord >> 8, highOrderWord & 0xff, highOrderWord >> 8]
.map((byte) => byte.toString(16).toUpperCase().padStart(2, "0"))
.join("");
};
/**
* Hashes a password for `w:documentProtection` as Word does, with SHA-256: SHA-256 of the salt and the password's
* legacy key (in UTF-16LE), then SHA-256 of each hash and its iteration number (32-bit little-endian), `spinCount`
* times.
*
* Word itself uses SHA-512, and reads either. hash.js's SHA-512 works its 64-bit words out in 32-bit halves, so
* 100,000 rounds of it take a second or more, where SHA-256 takes about a tenth of that.
*
* @param password - The password, of at least one character
* @param salt - The salt Word reads from `w:salt`
* @param spinCount - How many times to hash again, which Word reads from `w:cryptSpinCount`
* @returns The hash Word reads from `w:hash`
*
* @internal
*/
export const hashProtectionPassword = (password: string, salt: readonly number[], spinCount: number): readonly number[] => {
const key = [...legacyPasswordKey(password)].flatMap((character) => [character.charCodeAt(0), 0]);
let digest: readonly number[] = hash.sha256().update(salt).update(key).digest();
for (let iteration = 0; iteration < spinCount; iteration++) {
digest = hash
.sha256()
.update(digest)
.update([iteration & 0xff, (iteration >> 8) & 0xff, (iteration >> 16) & 0xff, (iteration >>> 24) & 0xff])
.digest();
}
return digest;
};
/**
* Random bytes for a password's salt, from the platform's secure random numbers where it has them (browsers, and
* Node.js from 19 on). The salt is written in the document beside the hash, so it only has to differ between
* documents, and `Math.random` does that on older Node.js.
*
* @internal
*/
export const randomSalt = (length: number): readonly number[] => {
const bytes = new Uint8Array(length);
if (typeof globalThis.crypto?.getRandomValues === "function") {
globalThis.crypto.getRandomValues(bytes);
return [...bytes];
}
return [...bytes].map(() => Math.floor(Math.random() * 256));
};
+13
View File
@@ -73,6 +73,17 @@ describe("Settings", () => {
});
});
it("should protect the document", () => {
const settings = new Settings({
protection: { type: "comments" },
});
const tree = new Formatter().format(settings);
expect(tree["w:settings"]).to.deep.include({
"w:documentProtection": { _attr: { "w:edit": "comments", "w:enforcement": true } },
});
});
it("should add compatibility setting with default compatability version", () => {
const settings = new Settings({
compatibility: {},
@@ -219,6 +230,7 @@ describe("Settings", () => {
autoHyphenation: true,
},
defaultTabStop: 100,
protection: { type: "readOnly" },
trackRevisions: true,
embedFonts: true,
});
@@ -230,6 +242,7 @@ describe("Settings", () => {
"w:displayBackgroundShape",
"w:embedTrueTypeFonts",
"w:trackRevisions",
"w:documentProtection",
"w:defaultTabStop",
"w:autoHyphenation",
"w:consecutiveHyphenLimit",
+8
View File
@@ -11,6 +11,7 @@
import { NumberValueElement, OnOffElement, XmlAttributeComponent, XmlComponent } from "@file/xml-components";
import { Compatibility, type ICompatibilityOptions } from "./compatibility";
import { DocumentProtection, type IDocumentProtectionOptions } from "./document-protection";
/**
* Attributes for the settings element with XML namespace declarations.
@@ -187,6 +188,8 @@ export type ISettingsOptions = {
readonly defaultTabStop?: number;
/** Hyphenation settings */
readonly hyphenation?: IHyphenationOptions;
/** What people can change in the document in Word, and the password that turns that protection off */
readonly protection?: IDocumentProtectionOptions;
};
/**
@@ -219,6 +222,7 @@ export type IHyphenationOptions = {
* <xsd:sequence>
* <xsd:element name="embedTrueTypeFonts" type="CT_OnOff" minOccurs="0"/>
* <xsd:element name="trackRevisions" type="CT_OnOff" minOccurs="0"/>
* <xsd:element name="documentProtection" type="CT_DocProtect" minOccurs="0"/>
* <xsd:element name="defaultTabStop" type="CT_TwipsMeasure" minOccurs="0"/>
* <xsd:element name="autoHyphenation" type="CT_OnOff" minOccurs="0"/>
* <xsd:element name="consecutiveHyphenLimit" type="CT_DecimalNumber" minOccurs="0"/>
@@ -293,6 +297,10 @@ export class Settings extends XmlComponent {
this.root.push(new OnOffElement("w:trackRevisions", options.trackRevisions));
}
if (options.protection !== undefined) {
this.root.push(new DocumentProtection(options.protection));
}
// https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_defaultTabStop_topic_ID0EIXSX.html
if (options.defaultTabStop !== undefined) {
this.root.push(new NumberValueElement("w:defaultTabStop", options.defaultTabStop));