aboutsummaryrefslogtreecommitdiffstats
path: root/modules/web/chromium/extensions/lib.nix
blob: 119786840f7780ae4403b7e4c3aac379f06409b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
{
  lib,
  pkgs,
  config,
  checkForUpdates ? true,
}:
rec {
  # Fetch using the Releases API (Finds the latest official GitHub Release)
  fetchLatestGithubReleaseTag =
    { owner, repo }:
    let
      raw = builtins.fetchurl {
        url = "https://api.github.com/repos/${owner}/${repo}/releases/latest";
        name = "${repo}-latest-release.json";
      };
      json = builtins.fromJSON (builtins.readFile raw);
    in
    json.tag_name;

  # Fetch using the Tags API (Finds the newest tag matching a prefix/regex)
  fetchLatestGithubTag =
    {
      owner,
      repo,
      tagPrefix ? "",
      tagRegex ? null,
    }:
    let
      raw = builtins.fetchurl {
        url = "https://api.github.com/repos/${owner}/${repo}/tags";
        name = "${repo}-tags.json";
      };
      tags = builtins.fromJSON (builtins.readFile raw);

      isValidTag =
        t:
        let
          matchesPrefix = tagPrefix == "" || lib.hasPrefix tagPrefix t.name;
          matchesRegex = tagRegex == null || builtins.match tagRegex t.name != null;
        in
        matchesPrefix && matchesRegex;

      matchingTags = builtins.filter isValidTag tags;
    in
    if builtins.length matchingTags > 0 then
      (builtins.head matchingTags).name
    else
      throw "No tags found for ${owner}/${repo} matching prefix '${tagPrefix}' and regex '${toString tagRegex}'";

  # Internal helper to handle the version comparison and error message
  _verifyAndThrow =
    {
      pname,
      version,
      latestTag,
      tagPrefix,
      urlTemplate,
      updateType,
    }:
    let
      latestVersion =
        if lib.hasPrefix tagPrefix latestTag then lib.removePrefix tagPrefix latestTag else latestTag;
    in
    if latestVersion != version then
      throw ''
        [${pname}] A newer ${updateType} is available upstream — refusing to build a stale extension.

          pinned version : ${version}
          latest version : ${latestVersion}  (tag: ${latestTag})

        To upgrade, edit extensions/${pname}.nix:
          1. Set   version = "${latestVersion}";
          2. Point the url at the new release asset:
               ${urlTemplate}
          3. Set   hash = lib.fakeHash;
             then re-run your switch — it'll fail with a hash mismatch showing
             the real sha256. Paste that in as the final hash.
          4. Re-run once more. This check passes once pinned == latest.

        To skip this check for now (e.g. offline / pure eval), set:
          web.chromium.checkForUpdates = false;
      ''
    else
      version;

  checkExtensionVersion =
    {
      pname,
      owner,
      repo,
      version,
      urlTemplate,
      tagPrefix ? "",
    }:
    if !checkForUpdates then
      version
    else
      let
        latestTag = fetchLatestGithubReleaseTag { inherit owner repo; };
      in
      _verifyAndThrow {
        inherit
          pname
          version
          latestTag
          tagPrefix
          urlTemplate
          ;
        updateType = "release";
      };

  checkExtensionVersionByTag =
    {
      pname,
      owner,
      repo,
      version,
      urlTemplate,
      tagPrefix ? "",
      tagRegex ? null,
    }:
    if !checkForUpdates then
      version
    else
      let
        latestTag = fetchLatestGithubTag {
          inherit
            owner
            repo
            tagPrefix
            tagRegex
            ;
        };
      in
      _verifyAndThrow {
        inherit
          pname
          version
          latestTag
          tagPrefix
          urlTemplate
          ;
        updateType = "tag";
      };

  # ==========================================
  # 3. EXTENSION BUILDERS
  # ==========================================

  # Download and unpack a zip or crx file into an unpacked extension directory
  fetchUnpackedExtension =
    {
      pname,
      version,
      url,
      hash,
      isCrx ? false,
      extensionKey ? null,
    }:
    pkgs.stdenv.mkDerivation {
      inherit pname version;
      src = pkgs.fetchurl { inherit url hash; };

      nativeBuildInputs = [
        config.file-management.ouch.package
        pkgs.python3
      ];
      dontUnpack = true;

      buildPhase = ''
        runHook preBuild
        mkdir -p $out

        if [ "${lib.boolToString isCrx}" = "true" ]; then
          # Verify the Cr24 magic header
          magic=$(head -c 4 "$src")
          if [ "$magic" != "Cr24" ]; then
            echo "Error: $src is not a valid CRX file" >&2
            exit 1
          fi

          # Extract header length in bytes 8 to 11
          bytes=$(od -An -j8 -N4 -tu1 "$src")
          read b1 b2 b3 b4 <<< $bytes
          hlen=$(( b1 + (b2 << 8) + (b3 << 16) + (b4 << 24) ))
          offset=$(( 12 + hlen ))

          dd if=$src of=payload.zip bs=1 skip=$offset status=none
          ouch decompress payload.zip --dir $out
        else
          ouch decompress $src --dir $out
        fi

        # Flatten a single wrapping folder
        if [ "$(ls -1 $out | wc -l)" -eq 1 ] && [ -d "$out"/* ]; then
          shopt -s dotglob
          mv "$out"/*/* "$out"/ 2>/dev/null || true
          rmdir "$out"/*/ 2>/dev/null || true
          shopt -u dotglob
        fi

        # Inject the public key into manifest.json if provided
        ${lib.optionalString (extensionKey != null) ''
                    if [ -f "$out/manifest.json" ]; then
                      echo "Injecting extension key into manifest.json to lock the extension ID..."
                      python3 -c '
          import json, sys, re

          manifest_path = sys.argv[1]
          ext_key = sys.argv[2]

          with open(manifest_path, "r", encoding="utf-8", errors="ignore") as f:
              content = f.read()

          # 1. Strip JS comments without corrupting URLs inside strings
          pattern = r"(\"[^\"]*?\")|//.*?$|/\*.*?\*/"
          clean = re.sub(pattern, lambda m: m.group(1) if m.group(1) else "", content, flags=re.DOTALL | re.MULTILINE)

          # 2. Strip trailing commas in JSON objects/arrays
          clean = re.sub(r",\s*([\]}])", r"\1", clean)

          data = json.loads(clean)
          data["key"] = ext_key

          with open(manifest_path, "w", encoding="utf-8") as f:
              json.dump(data, f, indent=2)
          ' "$out/manifest.json" "${extensionKey}"
                    else
                      echo "Warning: No manifest.json found in $out to inject the key!" >&2
                    fi
        ''}

        runHook postBuild
      '';

      installPhase = "true";
    };

  mkLocalExtension =
    {
      pname,
      srcDir,
      version ? "1.0.0",
    }:
    pkgs.stdenv.mkDerivation {
      inherit pname version;
      src = srcDir;
      phases = [ "installPhase" ];
      installPhase = ''
        mkdir -p $out
        cp -r $src/* $out/
      '';
    };
}